title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How many ways are there to initialize the instance variables of a class in java?
You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks. Whenever you make a method final, you cannot override it. i.e. you cannot provide implementation to the superclass’s final method from the subclass. i.e. The purpose of making a method final is to prevent modification of a method from outside (child class). You can also use these final methods to initialize the instance variables. Live Demo import java.util.Scanner; public class FinalMethods { int age = getAge(); String name = getName(); static Scanner sc = new Scanner(System.in); public static final int getAge() { System.out.println("Enter age value"); return sc.nextInt(); } public static final String getName() { System.out.println("Enter name value"); return sc.next(); } public void display(){ System.out.println("Name and age values: "); System.out.println(this.name); System.out.println(this.age); } public static void main(String args[]){ FinalMethods obj = new FinalMethods(); obj.display(); } } Enter age value 25 Enter name value Krishna Name and age values: Krishna 25 A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have the same name as their class and, have no return type. There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation. Live Demo public class Test { String name; int age; public Test(String name, int age){ this.name = name; this.age = age; } public static void main(String args[]) { Test obj = new Test("Krishna", 25); System.out.println("Name: "+obj.name); System.out.println("Age: "+obj.age); } } Name: Krishna Age: 25 Similar to static blocks, Java also provides instance initialization blocks which are used to initialize instance variables, as an alternative to constructors. Whenever you define an initialization block Java copies its code to the constructors. Therefore, you can also use these to share code between the constructors of a class. Live Demo public class Student { String name; int age; { name = "Krishna"; age = 25; } public static void main(String args[]){ Student std = new Student(); System.out.println(std.age); System.out.println(std.name); } } 25 Krishna
[ { "code": null, "e": 1185, "s": 1062, "text": "You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks." }, { "code": null, "e": 1334, "s": 1185, "text": "Whenever you make a method final, you cannot override it. i.e. you cannot provide implementation to the superclass’s final method from the subclass." }, { "code": null, "e": 1518, "s": 1334, "text": "i.e. The purpose of making a method final is to prevent modification of a method from outside (child class). You can also use these final methods to initialize the instance variables." }, { "code": null, "e": 1529, "s": 1518, "text": " Live Demo" }, { "code": null, "e": 2184, "s": 1529, "text": "import java.util.Scanner;\npublic class FinalMethods {\n int age = getAge();\n String name = getName();\n static Scanner sc = new Scanner(System.in);\n public static final int getAge() {\n System.out.println(\"Enter age value\");\n return sc.nextInt();\n }\n public static final String getName() {\n System.out.println(\"Enter name value\");\n return sc.next();\n }\n public void display(){\n System.out.println(\"Name and age values: \");\n System.out.println(this.name);\n System.out.println(this.age);\n }\n public static void main(String args[]){\n FinalMethods obj = new FinalMethods();\n obj.display();\n }\n}" }, { "code": null, "e": 2260, "s": 2184, "text": "Enter age value\n25\nEnter name value\nKrishna\nName and age values:\nKrishna\n25" }, { "code": null, "e": 2467, "s": 2260, "text": "A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have the same name as their class and, have no return type." }, { "code": null, "e": 2580, "s": 2467, "text": "There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation." }, { "code": null, "e": 2591, "s": 2580, "text": " Live Demo" }, { "code": null, "e": 2909, "s": 2591, "text": "public class Test {\n String name;\n int age;\n public Test(String name, int age){\n this.name = name;\n this.age = age;\n }\n public static void main(String args[]) {\n Test obj = new Test(\"Krishna\", 25);\n System.out.println(\"Name: \"+obj.name);\n System.out.println(\"Age: \"+obj.age);\n }\n}" }, { "code": null, "e": 2931, "s": 2909, "text": "Name: Krishna\nAge: 25" }, { "code": null, "e": 3091, "s": 2931, "text": "Similar to static blocks, Java also provides instance initialization blocks which are used to initialize instance variables, as an alternative to constructors." }, { "code": null, "e": 3262, "s": 3091, "text": "Whenever you define an initialization block Java copies its code to the constructors. Therefore, you can also use these to share code between the constructors of a class." }, { "code": null, "e": 3273, "s": 3262, "text": " Live Demo" }, { "code": null, "e": 3530, "s": 3273, "text": "public class Student {\n String name;\n int age;\n {\n name = \"Krishna\";\n age = 25;\n }\n public static void main(String args[]){\n Student std = new Student();\n System.out.println(std.age);\n System.out.println(std.name);\n }\n}" }, { "code": null, "e": 3541, "s": 3530, "text": "25\nKrishna" } ]
Using Object Detection for Complex Image Classification Scenarios Part 3: | by Aaron (Ari) Bornstein | Towards Data Science
TLDR; This series is based on the work detecting complex policies in the following real life code story. Code for the series can be found here. In the previous tutorials we outlined our policy classification challenge and showed how we can approach it using the Custom Vision Cognitive Service. This tutorial introduces deep transfer learning as a means to leverage multiple data sources to overcome data scarcity problem. Before we try to build a classifier for our complex policy let’s first look at the MNIST dataset to better understand key image classification concepts such as One Hot Encoding, Linear Modeling, Multi Layer Perception, Masking and Convolutions then we will put these concepts together and apply them to our own dataset. To train a classification model on MNIST we first need a way to represent our images and labels . There are many ways to represent images as either Tensors, Matrices or Vectors. For our first model we will use a vector representation. To do this we will first flatten the images to a long vector, in a manner similar to how one might unravel the thread of a cloth. When we apply this process to the image of a “3” below with dimensions of 28 x 28 image pixels, it will result in a flattened array of length 784 pixels. Now even though it is easy for us to look at this image and know it is a “3”, computers do not innately know this, we need to train a model to learn the how recognize that there is a “3” in the image. To do so we first need a way of representing the fact that the picture above contains an image of a “3”. To accomplish we associate each of our image with a one 1-hot encoded label, where the first index corresponds to digit 0 and the last one corresponds to digit 9. When we train a model we use this value as our target. The Keras code below loads the MNIST data from keras.datasets import mnist from keras.utils import np_utils output_dim = nb_classes = 10 batch_size = 128 nb_epoch = 5# the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data()input_dim = 784 #28*28 X_train = x_train.reshape(60000, input_dim) X_test = x_test.reshape(10000, input_dim) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) Now that we have processed the MNIST images and their labels let’s train our first image classification model using Keras. Logistic Regression (LR) is a fundamental machine learning technique that uses a linear weighted combination of features and generates probability-based predictions of different classes. To train the LR model above on MNIST, we apply the following steps: Initialize a random weight vector of 784 valuesTake the first 784bit MNIST training image vector like the “3” above and multiply it by our weight vector.Take the result of our multiplication and sum each of our 784 values until we get one numberPass the number into an function which takes our sum and fits it into a distribution between 0-9 and one hot encode the output. For the first example this number will most likely be incorrect, since we multiplied by random valuesCompare the output vector to the image label vector and calculate how close our prediction was using a loss function. The output of the loss function is called a loss.Apply an optimization such as SGD with respect to the value of the loss to update each value in the weight vector. Initialize a random weight vector of 784 values Take the first 784bit MNIST training image vector like the “3” above and multiply it by our weight vector. Take the result of our multiplication and sum each of our 784 values until we get one number Pass the number into an function which takes our sum and fits it into a distribution between 0-9 and one hot encode the output. For the first example this number will most likely be incorrect, since we multiplied by random values Compare the output vector to the image label vector and calculate how close our prediction was using a loss function. The output of the loss function is called a loss. Apply an optimization such as SGD with respect to the value of the loss to update each value in the weight vector. medium.com We then repeat this process on every image in our MNIST training set. For each image the weight values are updated so that they can better transform our input MNIST vectors into a value that matches it’s label. When we finish running the steps above on our training set that is called an Epoch. After the first Epoch the values are still likely to be poor but after shuffling the dataset and repeating the process for a couple more Epochs the linear model learns linear weights that they converge on the decent representation of our data. The Keras code below show the the results of this process. from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential() model.add(Dense(output_dim, input_dim=input_dim, activation='softmax')) model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,verbose=1, validation_data=(X_test, Y_test)) score = model.evaluate(X_test, Y_test, verbose=0) print('Test Loss:', score[0]) print('Test accuracy:', score[1]) Train on 60000 samples, validate on 10000 samplesEpoch 1/560000/60000 [==============================] - 1s 16us/step - loss: 1.2899 - acc: 0.6898 - val_loss: 0.8185 - val_acc: 0.8255Epoch 2/560000/60000 [==============================] - 1s 17us/step - loss: 0.7228 - acc: 0.8374 - val_loss: 0.6113 - val_acc: 0.8588Epoch 3/560000/60000 [==============================] - 1s 11us/step - loss: 0.5912 - acc: 0.8575 - val_loss: 0.5281 - val_acc: 0.8724Epoch 4/560000/60000 [==============================] - 1s 11us/step - loss: 0.5280 - acc: 0.8681 - val_loss: 0.4821 - val_acc: 0.8800Epoch 5/560000/60000 [==============================] - 1s 13us/step - loss: 0.4897 - acc: 0.8749 - val_loss: 0.4514 - val_acc: 0.8858Test Loss: 0.4514175675392151Test accuracy: 0.8858 One can imagine, that just incrementing and summing weight vector values based on one output is sub-optimal and in some cases unproductive. After all, not all data is linear. Take the following example for two image classes called spam and not-spam. No matter how we update our weights there is no linear weights we can learn to differentiate between these classes. But what if we had a way of combining multiple linear models for better representation power? We could then train a model that could differentiate between the two image classes. We can do this with a feed forward neural network such as the Multi Layer Perception. For MLPs to work we need a non linear activation function such as RELU for the sake of brevity we will treat this as a black box for more on this topic see the following post. medium.com The keras code below shows how to train a multi-layer perceptron on MNIST to get even better results than provided by our linear model. from keras.models import Sequential from keras.layers import Dense, Activation output_dim = nb_classes = 10 batch_size = 128 nb_epoch = 5model = Sequential() model.add(Dense(input_dim, input_dim=input_dim, activation='relu')) model.add(Dense(input_dim, input_dim=input_dim, activation='relu'))model.add(Dense(output_dim, input_dim=input_dim, activation='softmax')) model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,verbose=1, validation_data=(X_test, Y_test)) score = model.evaluate(X_test, Y_test, verbose=0) print('Test Loss:', score[0]) print('Test accuracy:', score[1]) Train on 60000 samples, validate on 10000 samplesEpoch 1/560000/60000 [==============================] - 9s 150us/step - loss: 1.0790 - acc: 0.7676 - val_loss: 0.5100 - val_acc: 0.8773Epoch 2/560000/60000 [==============================] - 9s 143us/step - loss: 0.4401 - acc: 0.8866 - val_loss: 0.3650 - val_acc: 0.9011Epoch 3/560000/60000 [==============================] - 12s 194us/step - loss: 0.3530 - acc: 0.9032 - val_loss: 0.3136 - val_acc: 0.9127Epoch 4/560000/60000 [==============================] - 16s 272us/step - loss: 0.3129 - acc: 0.9124 - val_loss: 0.2868 - val_acc: 0.9188Epoch 5/560000/60000 [==============================] - 12s 203us/step - loss: 0.2875 - acc: 0.9194 - val_loss: 0.2659 - val_acc: 0.9246Test Loss: 0.2659078140795231Test accuracy: 0.9246 Notice how much more accurate, yet slower the MLP model was than our simple linear model. When we have images greater than 500Kb to 1Mb it gets increasingly more computationally expensive to process our image as a sequence additionally it becomes much more challenging to detect complex self referential and hierarchical patterns in our sequence data. This curse of dimensionality, was one of the key reasons the computer vision field was stalled until the advent of AlexNet in 2012. What if instead of passing our full image as vector representation we represented our image as a matrix (28x28) and instead extracted representative features for making a classification decision? That is how computer vision worked until recently. Lets take a deeper look at traditional image feature extraction by trying to use edges as a feature for a model. To do this we first we take an image such as the one below. Then we take a predefined image mask in this case a sobel matrix that is used to extract edges We apply the sobel matrix mask to our image in strides like a filter When we visualize the resulting image we get the following edges which we can use as features Creating masks such as the Sobel mask by hand is hard work and brittle what if we could learn masks? That is the key insight behind the convolutional neural network or CNN. A CNN is a deep neural network comprised of a bunch of layers in such a way that the output of one layer is fed to the next layer (There are more complex architecture that skip layers with dropout we will take this as a given for now). Usually, CNN’s start with alternating between convolution layer and pooling layer (down sample), then end up with fully connected layer for the classification part. A convolution layer is a set of filters. Each filter is defined by a weight (W) matrix, and bias (b). Once we apply our mask we use pooling to reduce the dimensionality of the previous layer, which speeds up the network. There are many different pooling methods max and average pooling are the most common. Here an example of max and average pooling with a stride of 2: In most CNNs we stack a set of convolutional and pooling layers until we have a representational set of features that we can flatten and use for class predictions. The code below shows how to train a CNN on the MNIST images from above. from keras.layers import Dropout, Flattenfrom keras.layers import Conv2D, MaxPooling2Dmodel = Sequential()model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(nb_classes, activation='softmax'))model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])model.fit(x_train, y_train, batch_size=batch_size, epochs=nb_epoch, verbose=1, validation_data=(x_test, y_test))score = model.evaluate(x_test, y_test, verbose=0)print('Test loss:', score[0])print('Test accuracy:', score[1]) Train on 60000 samples, validate on 10000 samplesEpoch 1/560000/60000 [==============================] - 177s 3ms/step - loss: 0.2638 - acc: 0.9204 - val_loss: 0.0662 - val_acc: 0.9790Epoch 2/560000/60000 [==============================] - 173s 3ms/step - loss: 0.0882 - acc: 0.9732 - val_loss: 0.0404 - val_acc: 0.9865Epoch 3/560000/60000 [==============================] - 166s 3ms/step - loss: 0.0651 - acc: 0.9806 - val_loss: 0.0350 - val_acc: 0.9883Epoch 4/560000/60000 [==============================] - 163s 3ms/step - loss: 0.0549 - acc: 0.9836 - val_loss: 0.0334 - val_acc: 0.9887Epoch 5/560000/60000 [==============================] - 159s 3ms/step - loss: 0.0472 - acc: 0.9859 - val_loss: 0.0322 - val_acc: 0.9899Test loss: 0.03221080291894468Test accuracy: 0.9899 In the MNIST dataset we had tens of thousands of training examples what if we have less data like in our policy task? That is where we can use transfer learning. Training a Deep Neural Network from scratch requires tens of thousands of images, but training one that has already learned features in the domain you are adapting it to requires far fewer. Transfer Learning, uses a pre-trained model and adapts it to our own problem. In transfer learning we leverage the features and concepts that were learned during the training of the base model. The input to the old and the new prediction layer is the same as the base model, we simply reuse the trained features. Then we train this modified network, either only the new weights of the new prediction layer or all weights of the entire network. This can be used, for instance, when we have a small set of images that are in a similar domain to an existing trained model. In our case, this means adapting a network trained on ImageNet images to the task of policy classification. The repo and post by Aditya Ananthram was used for inspiration for this section I strongly suggest you check it out. For this task, we have chosen to use pretrained MobileNet model as our base model. While there are many classification architectures we’ll use MobileNet since it runs fast on a CPU and provides strong results. from keras.layers import Dense,GlobalAveragePooling2Dfrom keras.applications import MobileNetfrom keras.preprocessing import imagefrom keras.applications.mobilenet import preprocess_inputfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.models import Modelfrom keras.optimizers import Adambase_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.x=base_model.outputx=GlobalAveragePooling2D()(x)x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.x=Dense(1024,activation='relu')(x) #dense layer 2x=Dense(512,activation='relu')(x) #dense layer 3preds=Dense(2,activation='softmax')(x) #final layer with softmax activationmodel=Model(inputs=base_model.input,outputs=preds) for layer in model.layers[:20]: layer.trainable=Falsefor layer in model.layers[20:]: layer.trainable=TrueDownloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.6/mobilenet_1_0_224_tf_no_top.h517227776/17225924 [==============================] - 13s 1us/step model.summary()_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) (None, None, None, 3) 0 _________________________________________________________________conv1_pad (ZeroPadding2D) (None, None, None, 3) 0 _________________________________________________________________conv1 (Conv2D) (None, None, None, 32) 864 _________________________________________________________________conv1_bn (BatchNormalization (None, None, None, 32) 128 _________________________________________________________________conv1_relu (ReLU) (None, None, None, 32) 0 _________________________________________________________________conv_dw_1 (DepthwiseConv2D) (None, None, None, 32) 288 _________________________________________________________________conv_dw_1_bn (BatchNormaliza (None, None, None, 32) 128 _________________________________________________________________conv_dw_1_relu (ReLU) (None, None, None, 32) 0 _________________________________________________________________conv_pw_1 (Conv2D) (None, None, None, 64) 2048 _________________________________________________________________conv_pw_1_bn (BatchNormaliza (None, None, None, 64) 256 _________________________________________________________________conv_pw_1_relu (ReLU) (None, None, None, 64) 0 _________________________________________________________________conv_pad_2 (ZeroPadding2D) (None, None, None, 64) 0 _________________________________________________________________conv_dw_2 (DepthwiseConv2D) (None, None, None, 64) 576 _________________________________________________________________conv_dw_2_bn (BatchNormaliza (None, None, None, 64) 256 _________________________________________________________________conv_dw_2_relu (ReLU) (None, None, None, 64) 0 _________________________________________________________________conv_pw_2 (Conv2D) (None, None, None, 128) 8192 _________________________________________________________________conv_pw_2_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_pw_2_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_dw_3 (DepthwiseConv2D) (None, None, None, 128) 1152 _________________________________________________________________conv_dw_3_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_dw_3_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_pw_3 (Conv2D) (None, None, None, 128) 16384 _________________________________________________________________conv_pw_3_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_pw_3_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_pad_4 (ZeroPadding2D) (None, None, None, 128) 0 _________________________________________________________________conv_dw_4 (DepthwiseConv2D) (None, None, None, 128) 1152 _________________________________________________________________conv_dw_4_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_dw_4_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_pw_4 (Conv2D) (None, None, None, 256) 32768 _________________________________________________________________conv_pw_4_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_pw_4_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_dw_5 (DepthwiseConv2D) (None, None, None, 256) 2304 _________________________________________________________________conv_dw_5_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_dw_5_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_pw_5 (Conv2D) (None, None, None, 256) 65536 _________________________________________________________________conv_pw_5_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_pw_5_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_pad_6 (ZeroPadding2D) (None, None, None, 256) 0 _________________________________________________________________conv_dw_6 (DepthwiseConv2D) (None, None, None, 256) 2304 _________________________________________________________________conv_dw_6_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_dw_6_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_pw_6 (Conv2D) (None, None, None, 512) 131072 _________________________________________________________________conv_pw_6_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_6_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_7 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_7_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_dw_7_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_7 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_7_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_7_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_8 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_8_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_dw_8_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_8 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_8_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_8_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_9 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_9_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_dw_9_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_9 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_9_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_9_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_10 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_10_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_dw_10_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_10 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_10_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_pw_10_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_11 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_11_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_dw_11_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_11 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_11_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_pw_11_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pad_12 (ZeroPadding2D) (None, None, None, 512) 0 _________________________________________________________________conv_dw_12 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_12_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_dw_12_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_12 (Conv2D) (None, None, None, 1024) 524288 _________________________________________________________________conv_pw_12_bn (BatchNormaliz (None, None, None, 1024) 4096 _________________________________________________________________conv_pw_12_relu (ReLU) (None, None, None, 1024) 0 _________________________________________________________________conv_dw_13 (DepthwiseConv2D) (None, None, None, 1024) 9216 _________________________________________________________________conv_dw_13_bn (BatchNormaliz (None, None, None, 1024) 4096 _________________________________________________________________conv_dw_13_relu (ReLU) (None, None, None, 1024) 0 _________________________________________________________________conv_pw_13 (Conv2D) (None, None, None, 1024) 1048576 _________________________________________________________________conv_pw_13_bn (BatchNormaliz (None, None, None, 1024) 4096 _________________________________________________________________conv_pw_13_relu (ReLU) (None, None, None, 1024) 0 _________________________________________________________________global_average_pooling2d_1 ( (None, 1024) 0 _________________________________________________________________dense_7 (Dense) (None, 1024) 1049600 _________________________________________________________________dense_8 (Dense) (None, 1024) 1049600 _________________________________________________________________dense_9 (Dense) (None, 512) 524800 _________________________________________________________________dense_10 (Dense) (None, 2) 1026 =================================================================Total params: 5,853,890Trainable params: 5,817,986Non-trainable params: 35,904_________________________________________________________________ The code below shows how to train a custom MobileNet model on our custom policy using Keras. train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependenciestrain_generator=train_datagen.flow_from_directory('/data/dataset/Beverages/Train/',target_size=(224,224),color_mode='rgb',batch_size=32,class_mode='categorical',shuffle=True)test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)test_generator = test_datagen.flow_from_directory( directory=r"/data/dataset/Beverages/Test/", target_size=(224, 224), color_mode="rgb", batch_size=1, class_mode='categorical', shuffle=False, seed=42) Found 180 images belonging to 2 classes.Found 60 images belonging to 2 classes. i = 0for data in test_generator: if i > 3: break else: i+=1 img, cls = data print(np.argmax(cls)) plt.imshow(img[0]) plt.show() Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0 Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0 Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0 Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0 model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])# Adam optimizer# loss function will be categorical cross entropy# evaluation metric will be accuracystep_size_train=train_generator.n//train_generator.batch_sizemodel.fit_generator(generator=train_generator, steps_per_epoch=step_size_train, epochs=5) Epoch 1/55/5 [==============================] - 96s 19s/step - loss: 0.8017 - acc: 0.7313Epoch 2/55/5 [==============================] - 77s 15s/step - loss: 0.0101 - acc: 1.0000Epoch 3/55/5 [==============================] - 79s 16s/step - loss: 0.0289 - acc: 0.9937Epoch 4/55/5 [==============================] - 111s 22s/step - loss: 0.0023 - acc: 1.0000Epoch 5/55/5 [==============================] - 87s 17s/step - loss: 0.0025 - acc: 1.0000 As we can see below the MobileNet is a really strong model for learning and representing our toy policy. from utils import classification_reporty_true = np.concatenate([np.argmax(test_generator[i][1], axis=1) for i in range(test_generator.n)])y_pred = np.argmax(model.predict_generator(test_generator, steps=test_generator.n), axis=1)classification_report(y_true, y_pred) precision recall f1-score support 0 1.00 1.00 1.00 30 1 1.00 1.00 1.00 30 micro avg 1.00 1.00 1.00 60 macro avg 1.00 1.00 1.00 60weighted avg 1.00 1.00 1.00 60Confusion matrix, without normalization[[30 0] [ 0 30]]Normalized confusion matrix[[1. 0.] [0. 1.]] However if our policy was more complex it might have been challenging for us to model this way. In the next post we will dive into how to use object detection for complex image classification scenarios. medium.com github.com azure.microsoft.com towardsdatascience.com towardsdatascience.com In the next post we will dive into how to use object detection for complex image classification scenarios. Future posts will cover. Training and Computer Vision Models on the Cloud using Azure ML Service Train a Computer Vision Model on a Remote Cluster with Azure Machine Learning If you have any questions, comments, or topics you would like me to discuss feel free to follow me on Twitter if there is a milestone you feel I missed please let me know. Aaron (Ari) Bornstein is an avid AI enthusiast with a passion for history, engaging with new technologies and computational medicine. As an Open Source Engineer at Microsoft’s Cloud Developer Advocacy team, he collaborates with Israeli Hi-Tech Community, to solve real world problems with game changing technologies that are then documented, open sourced, and shared with the rest of the world.
[ { "code": null, "e": 315, "s": 171, "text": "TLDR; This series is based on the work detecting complex policies in the following real life code story. Code for the series can be found here." }, { "code": null, "e": 594, "s": 315, "text": "In the previous tutorials we outlined our policy classification challenge and showed how we can approach it using the Custom Vision Cognitive Service. This tutorial introduces deep transfer learning as a means to leverage multiple data sources to overcome data scarcity problem." }, { "code": null, "e": 914, "s": 594, "text": "Before we try to build a classifier for our complex policy let’s first look at the MNIST dataset to better understand key image classification concepts such as One Hot Encoding, Linear Modeling, Multi Layer Perception, Masking and Convolutions then we will put these concepts together and apply them to our own dataset." }, { "code": null, "e": 1092, "s": 914, "text": "To train a classification model on MNIST we first need a way to represent our images and labels . There are many ways to represent images as either Tensors, Matrices or Vectors." }, { "code": null, "e": 1279, "s": 1092, "text": "For our first model we will use a vector representation. To do this we will first flatten the images to a long vector, in a manner similar to how one might unravel the thread of a cloth." }, { "code": null, "e": 1433, "s": 1279, "text": "When we apply this process to the image of a “3” below with dimensions of 28 x 28 image pixels, it will result in a flattened array of length 784 pixels." }, { "code": null, "e": 1739, "s": 1433, "text": "Now even though it is easy for us to look at this image and know it is a “3”, computers do not innately know this, we need to train a model to learn the how recognize that there is a “3” in the image. To do so we first need a way of representing the fact that the picture above contains an image of a “3”." }, { "code": null, "e": 1902, "s": 1739, "text": "To accomplish we associate each of our image with a one 1-hot encoded label, where the first index corresponds to digit 0 and the last one corresponds to digit 9." }, { "code": null, "e": 1999, "s": 1902, "text": "When we train a model we use this value as our target. The Keras code below loads the MNIST data" }, { "code": null, "e": 2553, "s": 1999, "text": "from keras.datasets import mnist from keras.utils import np_utils output_dim = nb_classes = 10 batch_size = 128 nb_epoch = 5# the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data()input_dim = 784 #28*28 X_train = x_train.reshape(60000, input_dim) X_test = x_test.reshape(10000, input_dim) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes)" }, { "code": null, "e": 2676, "s": 2553, "text": "Now that we have processed the MNIST images and their labels let’s train our first image classification model using Keras." }, { "code": null, "e": 2863, "s": 2676, "text": "Logistic Regression (LR) is a fundamental machine learning technique that uses a linear weighted combination of features and generates probability-based predictions of different classes." }, { "code": null, "e": 2931, "s": 2863, "text": "To train the LR model above on MNIST, we apply the following steps:" }, { "code": null, "e": 3687, "s": 2931, "text": "Initialize a random weight vector of 784 valuesTake the first 784bit MNIST training image vector like the “3” above and multiply it by our weight vector.Take the result of our multiplication and sum each of our 784 values until we get one numberPass the number into an function which takes our sum and fits it into a distribution between 0-9 and one hot encode the output. For the first example this number will most likely be incorrect, since we multiplied by random valuesCompare the output vector to the image label vector and calculate how close our prediction was using a loss function. The output of the loss function is called a loss.Apply an optimization such as SGD with respect to the value of the loss to update each value in the weight vector." }, { "code": null, "e": 3735, "s": 3687, "text": "Initialize a random weight vector of 784 values" }, { "code": null, "e": 3842, "s": 3735, "text": "Take the first 784bit MNIST training image vector like the “3” above and multiply it by our weight vector." }, { "code": null, "e": 3935, "s": 3842, "text": "Take the result of our multiplication and sum each of our 784 values until we get one number" }, { "code": null, "e": 4165, "s": 3935, "text": "Pass the number into an function which takes our sum and fits it into a distribution between 0-9 and one hot encode the output. For the first example this number will most likely be incorrect, since we multiplied by random values" }, { "code": null, "e": 4333, "s": 4165, "text": "Compare the output vector to the image label vector and calculate how close our prediction was using a loss function. The output of the loss function is called a loss." }, { "code": null, "e": 4448, "s": 4333, "text": "Apply an optimization such as SGD with respect to the value of the loss to update each value in the weight vector." }, { "code": null, "e": 4459, "s": 4448, "text": "medium.com" }, { "code": null, "e": 4670, "s": 4459, "text": "We then repeat this process on every image in our MNIST training set. For each image the weight values are updated so that they can better transform our input MNIST vectors into a value that matches it’s label." }, { "code": null, "e": 4998, "s": 4670, "text": "When we finish running the steps above on our training set that is called an Epoch. After the first Epoch the values are still likely to be poor but after shuffling the dataset and repeating the process for a couple more Epochs the linear model learns linear weights that they converge on the decent representation of our data." }, { "code": null, "e": 5057, "s": 4998, "text": "The Keras code below show the the results of this process." }, { "code": null, "e": 5553, "s": 5057, "text": "from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential() model.add(Dense(output_dim, input_dim=input_dim, activation='softmax')) model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,verbose=1, validation_data=(X_test, Y_test)) score = model.evaluate(X_test, Y_test, verbose=0) print('Test Loss:', score[0]) print('Test accuracy:', score[1])" }, { "code": null, "e": 6323, "s": 5553, "text": "Train on 60000 samples, validate on 10000 samplesEpoch 1/560000/60000 [==============================] - 1s 16us/step - loss: 1.2899 - acc: 0.6898 - val_loss: 0.8185 - val_acc: 0.8255Epoch 2/560000/60000 [==============================] - 1s 17us/step - loss: 0.7228 - acc: 0.8374 - val_loss: 0.6113 - val_acc: 0.8588Epoch 3/560000/60000 [==============================] - 1s 11us/step - loss: 0.5912 - acc: 0.8575 - val_loss: 0.5281 - val_acc: 0.8724Epoch 4/560000/60000 [==============================] - 1s 11us/step - loss: 0.5280 - acc: 0.8681 - val_loss: 0.4821 - val_acc: 0.8800Epoch 5/560000/60000 [==============================] - 1s 13us/step - loss: 0.4897 - acc: 0.8749 - val_loss: 0.4514 - val_acc: 0.8858Test Loss: 0.4514175675392151Test accuracy: 0.8858" }, { "code": null, "e": 6463, "s": 6323, "text": "One can imagine, that just incrementing and summing weight vector values based on one output is sub-optimal and in some cases unproductive." }, { "code": null, "e": 6498, "s": 6463, "text": "After all, not all data is linear." }, { "code": null, "e": 6689, "s": 6498, "text": "Take the following example for two image classes called spam and not-spam. No matter how we update our weights there is no linear weights we can learn to differentiate between these classes." }, { "code": null, "e": 6867, "s": 6689, "text": "But what if we had a way of combining multiple linear models for better representation power? We could then train a model that could differentiate between the two image classes." }, { "code": null, "e": 6953, "s": 6867, "text": "We can do this with a feed forward neural network such as the Multi Layer Perception." }, { "code": null, "e": 7129, "s": 6953, "text": "For MLPs to work we need a non linear activation function such as RELU for the sake of brevity we will treat this as a black box for more on this topic see the following post." }, { "code": null, "e": 7140, "s": 7129, "text": "medium.com" }, { "code": null, "e": 7276, "s": 7140, "text": "The keras code below shows how to train a multi-layer perceptron on MNIST to get even better results than provided by our linear model." }, { "code": null, "e": 7965, "s": 7276, "text": "from keras.models import Sequential from keras.layers import Dense, Activation output_dim = nb_classes = 10 batch_size = 128 nb_epoch = 5model = Sequential() model.add(Dense(input_dim, input_dim=input_dim, activation='relu')) model.add(Dense(input_dim, input_dim=input_dim, activation='relu'))model.add(Dense(output_dim, input_dim=input_dim, activation='softmax')) model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,verbose=1, validation_data=(X_test, Y_test)) score = model.evaluate(X_test, Y_test, verbose=0) print('Test Loss:', score[0]) print('Test accuracy:', score[1])" }, { "code": null, "e": 8743, "s": 7965, "text": "Train on 60000 samples, validate on 10000 samplesEpoch 1/560000/60000 [==============================] - 9s 150us/step - loss: 1.0790 - acc: 0.7676 - val_loss: 0.5100 - val_acc: 0.8773Epoch 2/560000/60000 [==============================] - 9s 143us/step - loss: 0.4401 - acc: 0.8866 - val_loss: 0.3650 - val_acc: 0.9011Epoch 3/560000/60000 [==============================] - 12s 194us/step - loss: 0.3530 - acc: 0.9032 - val_loss: 0.3136 - val_acc: 0.9127Epoch 4/560000/60000 [==============================] - 16s 272us/step - loss: 0.3129 - acc: 0.9124 - val_loss: 0.2868 - val_acc: 0.9188Epoch 5/560000/60000 [==============================] - 12s 203us/step - loss: 0.2875 - acc: 0.9194 - val_loss: 0.2659 - val_acc: 0.9246Test Loss: 0.2659078140795231Test accuracy: 0.9246" }, { "code": null, "e": 9095, "s": 8743, "text": "Notice how much more accurate, yet slower the MLP model was than our simple linear model. When we have images greater than 500Kb to 1Mb it gets increasingly more computationally expensive to process our image as a sequence additionally it becomes much more challenging to detect complex self referential and hierarchical patterns in our sequence data." }, { "code": null, "e": 9227, "s": 9095, "text": "This curse of dimensionality, was one of the key reasons the computer vision field was stalled until the advent of AlexNet in 2012." }, { "code": null, "e": 9587, "s": 9227, "text": "What if instead of passing our full image as vector representation we represented our image as a matrix (28x28) and instead extracted representative features for making a classification decision? That is how computer vision worked until recently. Lets take a deeper look at traditional image feature extraction by trying to use edges as a feature for a model." }, { "code": null, "e": 9647, "s": 9587, "text": "To do this we first we take an image such as the one below." }, { "code": null, "e": 9742, "s": 9647, "text": "Then we take a predefined image mask in this case a sobel matrix that is used to extract edges" }, { "code": null, "e": 9811, "s": 9742, "text": "We apply the sobel matrix mask to our image in strides like a filter" }, { "code": null, "e": 9905, "s": 9811, "text": "When we visualize the resulting image we get the following edges which we can use as features" }, { "code": null, "e": 10078, "s": 9905, "text": "Creating masks such as the Sobel mask by hand is hard work and brittle what if we could learn masks? That is the key insight behind the convolutional neural network or CNN." }, { "code": null, "e": 10479, "s": 10078, "text": "A CNN is a deep neural network comprised of a bunch of layers in such a way that the output of one layer is fed to the next layer (There are more complex architecture that skip layers with dropout we will take this as a given for now). Usually, CNN’s start with alternating between convolution layer and pooling layer (down sample), then end up with fully connected layer for the classification part." }, { "code": null, "e": 10581, "s": 10479, "text": "A convolution layer is a set of filters. Each filter is defined by a weight (W) matrix, and bias (b)." }, { "code": null, "e": 10700, "s": 10581, "text": "Once we apply our mask we use pooling to reduce the dimensionality of the previous layer, which speeds up the network." }, { "code": null, "e": 10786, "s": 10700, "text": "There are many different pooling methods max and average pooling are the most common." }, { "code": null, "e": 10849, "s": 10786, "text": "Here an example of max and average pooling with a stride of 2:" }, { "code": null, "e": 11013, "s": 10849, "text": "In most CNNs we stack a set of convolutional and pooling layers until we have a representational set of features that we can flatten and use for class predictions." }, { "code": null, "e": 11085, "s": 11013, "text": "The code below shows how to train a CNN on the MNIST images from above." }, { "code": null, "e": 11958, "s": 11085, "text": "from keras.layers import Dropout, Flattenfrom keras.layers import Conv2D, MaxPooling2Dmodel = Sequential()model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(nb_classes, activation='softmax'))model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])model.fit(x_train, y_train, batch_size=batch_size, epochs=nb_epoch, verbose=1, validation_data=(x_test, y_test))score = model.evaluate(x_test, y_test, verbose=0)print('Test loss:', score[0])print('Test accuracy:', score[1])" }, { "code": null, "e": 12734, "s": 11958, "text": "Train on 60000 samples, validate on 10000 samplesEpoch 1/560000/60000 [==============================] - 177s 3ms/step - loss: 0.2638 - acc: 0.9204 - val_loss: 0.0662 - val_acc: 0.9790Epoch 2/560000/60000 [==============================] - 173s 3ms/step - loss: 0.0882 - acc: 0.9732 - val_loss: 0.0404 - val_acc: 0.9865Epoch 3/560000/60000 [==============================] - 166s 3ms/step - loss: 0.0651 - acc: 0.9806 - val_loss: 0.0350 - val_acc: 0.9883Epoch 4/560000/60000 [==============================] - 163s 3ms/step - loss: 0.0549 - acc: 0.9836 - val_loss: 0.0334 - val_acc: 0.9887Epoch 5/560000/60000 [==============================] - 159s 3ms/step - loss: 0.0472 - acc: 0.9859 - val_loss: 0.0322 - val_acc: 0.9899Test loss: 0.03221080291894468Test accuracy: 0.9899" }, { "code": null, "e": 13086, "s": 12734, "text": "In the MNIST dataset we had tens of thousands of training examples what if we have less data like in our policy task? That is where we can use transfer learning. Training a Deep Neural Network from scratch requires tens of thousands of images, but training one that has already learned features in the domain you are adapting it to requires far fewer." }, { "code": null, "e": 13530, "s": 13086, "text": "Transfer Learning, uses a pre-trained model and adapts it to our own problem. In transfer learning we leverage the features and concepts that were learned during the training of the base model. The input to the old and the new prediction layer is the same as the base model, we simply reuse the trained features. Then we train this modified network, either only the new weights of the new prediction layer or all weights of the entire network." }, { "code": null, "e": 13764, "s": 13530, "text": "This can be used, for instance, when we have a small set of images that are in a similar domain to an existing trained model. In our case, this means adapting a network trained on ImageNet images to the task of policy classification." }, { "code": null, "e": 13881, "s": 13764, "text": "The repo and post by Aditya Ananthram was used for inspiration for this section I strongly suggest you check it out." }, { "code": null, "e": 14091, "s": 13881, "text": "For this task, we have chosen to use pretrained MobileNet model as our base model. While there are many classification architectures we’ll use MobileNet since it runs fast on a CPU and provides strong results." }, { "code": null, "e": 14935, "s": 14091, "text": "from keras.layers import Dense,GlobalAveragePooling2Dfrom keras.applications import MobileNetfrom keras.preprocessing import imagefrom keras.applications.mobilenet import preprocess_inputfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.models import Modelfrom keras.optimizers import Adambase_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.x=base_model.outputx=GlobalAveragePooling2D()(x)x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.x=Dense(1024,activation='relu')(x) #dense layer 2x=Dense(512,activation='relu')(x) #dense layer 3preds=Dense(2,activation='softmax')(x) #final layer with softmax activationmodel=Model(inputs=base_model.input,outputs=preds)" }, { "code": null, "e": 15236, "s": 14935, "text": "for layer in model.layers[:20]: layer.trainable=Falsefor layer in model.layers[20:]: layer.trainable=TrueDownloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.6/mobilenet_1_0_224_tf_no_top.h517227776/17225924 [==============================] - 13s 1us/step" }, { "code": null, "e": 27550, "s": 15236, "text": "model.summary()_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) (None, None, None, 3) 0 _________________________________________________________________conv1_pad (ZeroPadding2D) (None, None, None, 3) 0 _________________________________________________________________conv1 (Conv2D) (None, None, None, 32) 864 _________________________________________________________________conv1_bn (BatchNormalization (None, None, None, 32) 128 _________________________________________________________________conv1_relu (ReLU) (None, None, None, 32) 0 _________________________________________________________________conv_dw_1 (DepthwiseConv2D) (None, None, None, 32) 288 _________________________________________________________________conv_dw_1_bn (BatchNormaliza (None, None, None, 32) 128 _________________________________________________________________conv_dw_1_relu (ReLU) (None, None, None, 32) 0 _________________________________________________________________conv_pw_1 (Conv2D) (None, None, None, 64) 2048 _________________________________________________________________conv_pw_1_bn (BatchNormaliza (None, None, None, 64) 256 _________________________________________________________________conv_pw_1_relu (ReLU) (None, None, None, 64) 0 _________________________________________________________________conv_pad_2 (ZeroPadding2D) (None, None, None, 64) 0 _________________________________________________________________conv_dw_2 (DepthwiseConv2D) (None, None, None, 64) 576 _________________________________________________________________conv_dw_2_bn (BatchNormaliza (None, None, None, 64) 256 _________________________________________________________________conv_dw_2_relu (ReLU) (None, None, None, 64) 0 _________________________________________________________________conv_pw_2 (Conv2D) (None, None, None, 128) 8192 _________________________________________________________________conv_pw_2_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_pw_2_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_dw_3 (DepthwiseConv2D) (None, None, None, 128) 1152 _________________________________________________________________conv_dw_3_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_dw_3_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_pw_3 (Conv2D) (None, None, None, 128) 16384 _________________________________________________________________conv_pw_3_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_pw_3_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_pad_4 (ZeroPadding2D) (None, None, None, 128) 0 _________________________________________________________________conv_dw_4 (DepthwiseConv2D) (None, None, None, 128) 1152 _________________________________________________________________conv_dw_4_bn (BatchNormaliza (None, None, None, 128) 512 _________________________________________________________________conv_dw_4_relu (ReLU) (None, None, None, 128) 0 _________________________________________________________________conv_pw_4 (Conv2D) (None, None, None, 256) 32768 _________________________________________________________________conv_pw_4_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_pw_4_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_dw_5 (DepthwiseConv2D) (None, None, None, 256) 2304 _________________________________________________________________conv_dw_5_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_dw_5_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_pw_5 (Conv2D) (None, None, None, 256) 65536 _________________________________________________________________conv_pw_5_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_pw_5_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_pad_6 (ZeroPadding2D) (None, None, None, 256) 0 _________________________________________________________________conv_dw_6 (DepthwiseConv2D) (None, None, None, 256) 2304 _________________________________________________________________conv_dw_6_bn (BatchNormaliza (None, None, None, 256) 1024 _________________________________________________________________conv_dw_6_relu (ReLU) (None, None, None, 256) 0 _________________________________________________________________conv_pw_6 (Conv2D) (None, None, None, 512) 131072 _________________________________________________________________conv_pw_6_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_6_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_7 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_7_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_dw_7_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_7 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_7_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_7_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_8 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_8_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_dw_8_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_8 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_8_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_8_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_9 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_9_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_dw_9_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_9 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_9_bn (BatchNormaliza (None, None, None, 512) 2048 _________________________________________________________________conv_pw_9_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_10 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_10_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_dw_10_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_10 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_10_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_pw_10_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_dw_11 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_11_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_dw_11_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_11 (Conv2D) (None, None, None, 512) 262144 _________________________________________________________________conv_pw_11_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_pw_11_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pad_12 (ZeroPadding2D) (None, None, None, 512) 0 _________________________________________________________________conv_dw_12 (DepthwiseConv2D) (None, None, None, 512) 4608 _________________________________________________________________conv_dw_12_bn (BatchNormaliz (None, None, None, 512) 2048 _________________________________________________________________conv_dw_12_relu (ReLU) (None, None, None, 512) 0 _________________________________________________________________conv_pw_12 (Conv2D) (None, None, None, 1024) 524288 _________________________________________________________________conv_pw_12_bn (BatchNormaliz (None, None, None, 1024) 4096 _________________________________________________________________conv_pw_12_relu (ReLU) (None, None, None, 1024) 0 _________________________________________________________________conv_dw_13 (DepthwiseConv2D) (None, None, None, 1024) 9216 _________________________________________________________________conv_dw_13_bn (BatchNormaliz (None, None, None, 1024) 4096 _________________________________________________________________conv_dw_13_relu (ReLU) (None, None, None, 1024) 0 _________________________________________________________________conv_pw_13 (Conv2D) (None, None, None, 1024) 1048576 _________________________________________________________________conv_pw_13_bn (BatchNormaliz (None, None, None, 1024) 4096 _________________________________________________________________conv_pw_13_relu (ReLU) (None, None, None, 1024) 0 _________________________________________________________________global_average_pooling2d_1 ( (None, 1024) 0 _________________________________________________________________dense_7 (Dense) (None, 1024) 1049600 _________________________________________________________________dense_8 (Dense) (None, 1024) 1049600 _________________________________________________________________dense_9 (Dense) (None, 512) 524800 _________________________________________________________________dense_10 (Dense) (None, 2) 1026 =================================================================Total params: 5,853,890Trainable params: 5,817,986Non-trainable params: 35,904_________________________________________________________________" }, { "code": null, "e": 27643, "s": 27550, "text": "The code below shows how to train a custom MobileNet model on our custom policy using Keras." }, { "code": null, "e": 28216, "s": 27643, "text": "train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependenciestrain_generator=train_datagen.flow_from_directory('/data/dataset/Beverages/Train/',target_size=(224,224),color_mode='rgb',batch_size=32,class_mode='categorical',shuffle=True)test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)test_generator = test_datagen.flow_from_directory( directory=r\"/data/dataset/Beverages/Test/\", target_size=(224, 224), color_mode=\"rgb\", batch_size=1, class_mode='categorical', shuffle=False, seed=42)" }, { "code": null, "e": 28296, "s": 28216, "text": "Found 180 images belonging to 2 classes.Found 60 images belonging to 2 classes." }, { "code": null, "e": 28443, "s": 28296, "text": "i = 0for data in test_generator: if i > 3: break else: i+=1 img, cls = data print(np.argmax(cls)) plt.imshow(img[0]) plt.show()" }, { "code": null, "e": 28554, "s": 28443, "text": "Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0" }, { "code": null, "e": 28665, "s": 28554, "text": "Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0" }, { "code": null, "e": 28776, "s": 28665, "text": "Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0" }, { "code": null, "e": 28887, "s": 28776, "text": "Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).0" }, { "code": null, "e": 29259, "s": 28887, "text": "model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])# Adam optimizer# loss function will be categorical cross entropy# evaluation metric will be accuracystep_size_train=train_generator.n//train_generator.batch_sizemodel.fit_generator(generator=train_generator, steps_per_epoch=step_size_train, epochs=5)" }, { "code": null, "e": 29706, "s": 29259, "text": "Epoch 1/55/5 [==============================] - 96s 19s/step - loss: 0.8017 - acc: 0.7313Epoch 2/55/5 [==============================] - 77s 15s/step - loss: 0.0101 - acc: 1.0000Epoch 3/55/5 [==============================] - 79s 16s/step - loss: 0.0289 - acc: 0.9937Epoch 4/55/5 [==============================] - 111s 22s/step - loss: 0.0023 - acc: 1.0000Epoch 5/55/5 [==============================] - 87s 17s/step - loss: 0.0025 - acc: 1.0000" }, { "code": null, "e": 29811, "s": 29706, "text": "As we can see below the MobileNet is a really strong model for learning and representing our toy policy." }, { "code": null, "e": 30079, "s": 29811, "text": "from utils import classification_reporty_true = np.concatenate([np.argmax(test_generator[i][1], axis=1) for i in range(test_generator.n)])y_pred = np.argmax(model.predict_generator(test_generator, steps=test_generator.n), axis=1)classification_report(y_true, y_pred)" }, { "code": null, "e": 30484, "s": 30079, "text": "precision recall f1-score support 0 1.00 1.00 1.00 30 1 1.00 1.00 1.00 30 micro avg 1.00 1.00 1.00 60 macro avg 1.00 1.00 1.00 60weighted avg 1.00 1.00 1.00 60Confusion matrix, without normalization[[30 0] [ 0 30]]Normalized confusion matrix[[1. 0.] [0. 1.]]" }, { "code": null, "e": 30687, "s": 30484, "text": "However if our policy was more complex it might have been challenging for us to model this way. In the next post we will dive into how to use object detection for complex image classification scenarios." }, { "code": null, "e": 30698, "s": 30687, "text": "medium.com" }, { "code": null, "e": 30709, "s": 30698, "text": "github.com" }, { "code": null, "e": 30729, "s": 30709, "text": "azure.microsoft.com" }, { "code": null, "e": 30752, "s": 30729, "text": "towardsdatascience.com" }, { "code": null, "e": 30775, "s": 30752, "text": "towardsdatascience.com" }, { "code": null, "e": 30907, "s": 30775, "text": "In the next post we will dive into how to use object detection for complex image classification scenarios. Future posts will cover." }, { "code": null, "e": 30979, "s": 30907, "text": "Training and Computer Vision Models on the Cloud using Azure ML Service" }, { "code": null, "e": 31057, "s": 30979, "text": "Train a Computer Vision Model on a Remote Cluster with Azure Machine Learning" }, { "code": null, "e": 31229, "s": 31057, "text": "If you have any questions, comments, or topics you would like me to discuss feel free to follow me on Twitter if there is a milestone you feel I missed please let me know." } ]
Check if the current date falls in a given date range using MySQL query
Let us first create a table − mysql> create table DemoTable1448 -> ( -> StartDate date, -> EndDate date -> ); Query OK, 0 rows affected (0.46 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1448 values('2019-01-21','2019-03-22'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1448 values('2019-04-05','2019-10-10'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1448 values('2019-10-01','2019-10-29'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1448 values('2018-12-31','2019-12-31'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select * from DemoTable1448; This will produce the following output − +------------+------------+ | StartDate | EndDate | +------------+------------+ | 2019-01-21 | 2019-03-22 | | 2019-04-05 | 2019-10-10 | | 2019-10-01 | 2019-10-29 | | 2018-12-31 | 2019-12-31 | +------------+------------+ 4 rows in set (0.00 sec) Let’s say the current date is − 2019-10-05 Following is the query to check if the current date falls in a given date range − mysql> select (curdate() >=StartDate and curdate() <=EndDate) as DateInRange from DemoTable1448; This will produce the following output − +-------------+ | DateInRange | +-------------+ | 0 | | 1 | | 1 | | 1 | +-------------+ 4 rows in set (0.04 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1221, "s": 1092, "text": "mysql> create table DemoTable1448\n -> (\n -> StartDate date,\n -> EndDate date\n -> );\nQuery OK, 0 rows affected (0.46 sec)" }, { "code": null, "e": 1277, "s": 1221, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1693, "s": 1277, "text": "mysql> insert into DemoTable1448 values('2019-01-21','2019-03-22');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1448 values('2019-04-05','2019-10-10');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1448 values('2019-10-01','2019-10-29');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1448 values('2018-12-31','2019-12-31');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1753, "s": 1693, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1789, "s": 1753, "text": "mysql> select * from DemoTable1448;" }, { "code": null, "e": 1830, "s": 1789, "text": "This will produce the following output −" }, { "code": null, "e": 2079, "s": 1830, "text": "+------------+------------+\n| StartDate | EndDate |\n+------------+------------+\n| 2019-01-21 | 2019-03-22 |\n| 2019-04-05 | 2019-10-10 |\n| 2019-10-01 | 2019-10-29 |\n| 2018-12-31 | 2019-12-31 |\n+------------+------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2111, "s": 2079, "text": "Let’s say the current date is −" }, { "code": null, "e": 2122, "s": 2111, "text": "2019-10-05" }, { "code": null, "e": 2204, "s": 2122, "text": "Following is the query to check if the current date falls in a given date range −" }, { "code": null, "e": 2301, "s": 2204, "text": "mysql> select (curdate() >=StartDate and curdate() <=EndDate) as DateInRange from DemoTable1448;" }, { "code": null, "e": 2342, "s": 2301, "text": "This will produce the following output −" }, { "code": null, "e": 2495, "s": 2342, "text": "+-------------+\n| DateInRange |\n+-------------+\n| 0 |\n| 1 |\n| 1 |\n| 1 |\n+-------------+\n4 rows in set (0.04 sec)" } ]
Hands-on TensorFlow Tutorial: Train ResNet-50 From Scratch Using the ImageNet Dataset | by James Montantes | Towards Data Science
In this blog, we give a quick hands on tutorial on how to train the ResNet model in TensorFlow. While the official TensorFlow documentation does have the basic information you need, it may not entirely make sense right away, and it can be a little hard to sift through. We present here a step by step process for training, while documenting best practices, tips, tricks, and even some challenges we encountered and eventually overcame while conducting the training process. We cover everything you need to do, from launching TensorFlow, downloading and preparing ImageNet, all the way to documenting and reporting training. All experiments and training were done on a Exxact Valence Workstation utilizing 2 NVIDIA RTX 2080 Ti GPUs. Yes, however this tutorial is a good exercise for training a large neural network from scratch, using a large dataset (ImageNet). While transfer learning is a wonderful thing, and you can download pre-trained versions of ResNet-50, here are some compelling reasons why you may want to go through this training exercise: If you complete this tutorial, you’ve effectively trained a neural network that can be used as a general purpose image classifier.With a process in place, you can train a network on your own data. For example, let’s say you want to train a network that can classify medical images. If the images are preprocessed properly the network trained on your data should be able to classify those images.If you have a lot of unique training data, training a network from scratch should have higher accuracy than a general pretrained network.You can tune the training parameters specifically for your data.On pretrained models, checkpoints are fragile, and are not guaranteed to work with future versions of the code. If you complete this tutorial, you’ve effectively trained a neural network that can be used as a general purpose image classifier. With a process in place, you can train a network on your own data. For example, let’s say you want to train a network that can classify medical images. If the images are preprocessed properly the network trained on your data should be able to classify those images. If you have a lot of unique training data, training a network from scratch should have higher accuracy than a general pretrained network. You can tune the training parameters specifically for your data. On pretrained models, checkpoints are fragile, and are not guaranteed to work with future versions of the code. While transfer learning is a powerful knowledge-sharing technique, knowing how to train from scratch is still a must for deep learning engineers. So now, let’s begin. First and foremost, you’ll want to launch your TensorFlow environment. We like to work with Docker, as it gives us ultimate flexibility and a reproducible environment. Pop open a terminal window and let’s get started! NOTE: Be sure specify your -v tag to create a interactive volume within the container. nvidia-docker run -it -v /data:/datasets tensorflow/tensorflow:nightly-gpu bash OR if you plan to launch Tensorboard within the docker container, be sure to specify -p 6006:6006 and use the following command instead. nvidia-docker run -it -v /data:/datasets -p 6006:6006 tensorflow/tensorflow:nightly-gpu bash We decided to include this step, as it seems to cause a little confusion. NOTE: you’ll want to make sure you have 300+ GB of storage space (as we found out) when you do this step, as the download & preprocess step requires this! 2.1) For the first substep you’ll need to install ‘git’ if it’s not part of your environment. apt-get install git 2.2) Second, you must clone the TPU repo to your environment (No, we’re not using Google’s TPU, but essential preprocess scripts are contained here!) git clone https://github.com/tensorflow/tpu.git 2.3) Third, you need to install the GCS dependencies (even if you’re not using GCS, you still need to run this!) pip install gcloud google-cloud-storage 2.4) Finally, you will need to run the imagenet_to_gcs.py script, which downloads the files from Image-Net.org and processes them into TFRecords but does not upload them to GCS (hence the ‘nogcs_upload’ flag) full options are here. Also ‘local_scratch_dir=’ should point to where you want to save the dataset. python imagenet_to_gcs.py --local_scratch_dir=/data/imagenet --nogcs_upload Note: ImageNet is HUGE, depending on your connection, it may take several hours (maybe overnight) to download the complete dataset! This step is obvious, if you don’t have the models, clone the repo using: git clone https://github.com/tensorflow/models.git Export PYTONPATH to the folder where the models folder are located on your machine. The command below is where the models were located on MY machine! Be sure to replace the ‘/datasets/models’ syntax with the data path to your models folder! export PYTHONPATH="$PYTHONPATH:/datasets/models" Navigate to the models folder (if you’re not already there) and run the following command pip install --user -r official/requirements.txt or if your using Python3 pip3 install --user -r official/requirements.txt IMPORTANT NOTE: You’re almost ready to train! In our experience, in order for the training script to run properly, you need to copy (or move) the data from the validation folder and move it to the train folder!!! Run the training script python imagenet_main.py and set training parameters. Below is what I used for training ResNet-50, 120 training epochs is very much overkill for this exercise, but we just wanted to push our GPUs. Depending on you’re compute power, it may take several days to train on the full dataset! python imagenet_main.py --data_dir=/data/imagenet/train --num_gpus= 2 --batch_size=64 --resnet_size= 50 --model_dir=/data/imagenet/trained_model/Resnet50_bs64 --train_epochs=120 Note on training parameters: Note that there are many different options you can specify including: The above mentioned are only some of the options available for model training. See resnet_run_loop.py for the full list of options (you’ll have to dig through the code). You can also see your results using TensorBoard: tensorboard --logdir=/data/imagenet/trained_model/Resnet50_bs64 If you ran the steps above correctly (and used similar parameters), you should have similar results below. Note, these results are on par with the official TensorFlow results. Let’s see what you can do! Accuracy train_accuracy_1 accuracy_top_5 train_accuracy_top_5_1 Loss l2_loss cross_entropy_1 learning_rate_1 sec That’s about it! Please let us know if you have any issues in training ResNet. Also, what tips and tricks do you use when training models in TensorFlow? Let me know! Originally published at https://blog.exxactcorp.com on March 26, 2019.
[ { "code": null, "e": 442, "s": 172, "text": "In this blog, we give a quick hands on tutorial on how to train the ResNet model in TensorFlow. While the official TensorFlow documentation does have the basic information you need, it may not entirely make sense right away, and it can be a little hard to sift through." }, { "code": null, "e": 646, "s": 442, "text": "We present here a step by step process for training, while documenting best practices, tips, tricks, and even some challenges we encountered and eventually overcame while conducting the training process." }, { "code": null, "e": 904, "s": 646, "text": "We cover everything you need to do, from launching TensorFlow, downloading and preparing ImageNet, all the way to documenting and reporting training. All experiments and training were done on a Exxact Valence Workstation utilizing 2 NVIDIA RTX 2080 Ti GPUs." }, { "code": null, "e": 1224, "s": 904, "text": "Yes, however this tutorial is a good exercise for training a large neural network from scratch, using a large dataset (ImageNet). While transfer learning is a wonderful thing, and you can download pre-trained versions of ResNet-50, here are some compelling reasons why you may want to go through this training exercise:" }, { "code": null, "e": 1932, "s": 1224, "text": "If you complete this tutorial, you’ve effectively trained a neural network that can be used as a general purpose image classifier.With a process in place, you can train a network on your own data. For example, let’s say you want to train a network that can classify medical images. If the images are preprocessed properly the network trained on your data should be able to classify those images.If you have a lot of unique training data, training a network from scratch should have higher accuracy than a general pretrained network.You can tune the training parameters specifically for your data.On pretrained models, checkpoints are fragile, and are not guaranteed to work with future versions of the code." }, { "code": null, "e": 2063, "s": 1932, "text": "If you complete this tutorial, you’ve effectively trained a neural network that can be used as a general purpose image classifier." }, { "code": null, "e": 2329, "s": 2063, "text": "With a process in place, you can train a network on your own data. For example, let’s say you want to train a network that can classify medical images. If the images are preprocessed properly the network trained on your data should be able to classify those images." }, { "code": null, "e": 2467, "s": 2329, "text": "If you have a lot of unique training data, training a network from scratch should have higher accuracy than a general pretrained network." }, { "code": null, "e": 2532, "s": 2467, "text": "You can tune the training parameters specifically for your data." }, { "code": null, "e": 2644, "s": 2532, "text": "On pretrained models, checkpoints are fragile, and are not guaranteed to work with future versions of the code." }, { "code": null, "e": 2811, "s": 2644, "text": "While transfer learning is a powerful knowledge-sharing technique, knowing how to train from scratch is still a must for deep learning engineers. So now, let’s begin." }, { "code": null, "e": 3029, "s": 2811, "text": "First and foremost, you’ll want to launch your TensorFlow environment. We like to work with Docker, as it gives us ultimate flexibility and a reproducible environment. Pop open a terminal window and let’s get started!" }, { "code": null, "e": 3116, "s": 3029, "text": "NOTE: Be sure specify your -v tag to create a interactive volume within the container." }, { "code": null, "e": 3196, "s": 3116, "text": "nvidia-docker run -it -v /data:/datasets tensorflow/tensorflow:nightly-gpu bash" }, { "code": null, "e": 3333, "s": 3196, "text": "OR if you plan to launch Tensorboard within the docker container, be sure to specify -p 6006:6006 and use the following command instead." }, { "code": null, "e": 3426, "s": 3333, "text": "nvidia-docker run -it -v /data:/datasets -p 6006:6006 tensorflow/tensorflow:nightly-gpu bash" }, { "code": null, "e": 3655, "s": 3426, "text": "We decided to include this step, as it seems to cause a little confusion. NOTE: you’ll want to make sure you have 300+ GB of storage space (as we found out) when you do this step, as the download & preprocess step requires this!" }, { "code": null, "e": 3749, "s": 3655, "text": "2.1) For the first substep you’ll need to install ‘git’ if it’s not part of your environment." }, { "code": null, "e": 3769, "s": 3749, "text": "apt-get install git" }, { "code": null, "e": 3919, "s": 3769, "text": "2.2) Second, you must clone the TPU repo to your environment (No, we’re not using Google’s TPU, but essential preprocess scripts are contained here!)" }, { "code": null, "e": 3967, "s": 3919, "text": "git clone https://github.com/tensorflow/tpu.git" }, { "code": null, "e": 4080, "s": 3967, "text": "2.3) Third, you need to install the GCS dependencies (even if you’re not using GCS, you still need to run this!)" }, { "code": null, "e": 4120, "s": 4080, "text": "pip install gcloud google-cloud-storage" }, { "code": null, "e": 4430, "s": 4120, "text": "2.4) Finally, you will need to run the imagenet_to_gcs.py script, which downloads the files from Image-Net.org and processes them into TFRecords but does not upload them to GCS (hence the ‘nogcs_upload’ flag) full options are here. Also ‘local_scratch_dir=’ should point to where you want to save the dataset." }, { "code": null, "e": 4506, "s": 4430, "text": "python imagenet_to_gcs.py --local_scratch_dir=/data/imagenet --nogcs_upload" }, { "code": null, "e": 4638, "s": 4506, "text": "Note: ImageNet is HUGE, depending on your connection, it may take several hours (maybe overnight) to download the complete dataset!" }, { "code": null, "e": 4712, "s": 4638, "text": "This step is obvious, if you don’t have the models, clone the repo using:" }, { "code": null, "e": 4763, "s": 4712, "text": "git clone https://github.com/tensorflow/models.git" }, { "code": null, "e": 5004, "s": 4763, "text": "Export PYTONPATH to the folder where the models folder are located on your machine. The command below is where the models were located on MY machine! Be sure to replace the ‘/datasets/models’ syntax with the data path to your models folder!" }, { "code": null, "e": 5053, "s": 5004, "text": "export PYTHONPATH=\"$PYTHONPATH:/datasets/models\"" }, { "code": null, "e": 5143, "s": 5053, "text": "Navigate to the models folder (if you’re not already there) and run the following command" }, { "code": null, "e": 5191, "s": 5143, "text": "pip install --user -r official/requirements.txt" }, { "code": null, "e": 5216, "s": 5191, "text": "or if your using Python3" }, { "code": null, "e": 5265, "s": 5216, "text": "pip3 install --user -r official/requirements.txt" }, { "code": null, "e": 5478, "s": 5265, "text": "IMPORTANT NOTE: You’re almost ready to train! In our experience, in order for the training script to run properly, you need to copy (or move) the data from the validation folder and move it to the train folder!!!" }, { "code": null, "e": 5788, "s": 5478, "text": "Run the training script python imagenet_main.py and set training parameters. Below is what I used for training ResNet-50, 120 training epochs is very much overkill for this exercise, but we just wanted to push our GPUs. Depending on you’re compute power, it may take several days to train on the full dataset!" }, { "code": null, "e": 5966, "s": 5788, "text": "python imagenet_main.py --data_dir=/data/imagenet/train --num_gpus= 2 --batch_size=64 --resnet_size= 50 --model_dir=/data/imagenet/trained_model/Resnet50_bs64 --train_epochs=120" }, { "code": null, "e": 6065, "s": 5966, "text": "Note on training parameters: Note that there are many different options you can specify including:" }, { "code": null, "e": 6235, "s": 6065, "text": "The above mentioned are only some of the options available for model training. See resnet_run_loop.py for the full list of options (you’ll have to dig through the code)." }, { "code": null, "e": 6284, "s": 6235, "text": "You can also see your results using TensorBoard:" }, { "code": null, "e": 6348, "s": 6284, "text": "tensorboard --logdir=/data/imagenet/trained_model/Resnet50_bs64" }, { "code": null, "e": 6551, "s": 6348, "text": "If you ran the steps above correctly (and used similar parameters), you should have similar results below. Note, these results are on par with the official TensorFlow results. Let’s see what you can do!" }, { "code": null, "e": 6560, "s": 6551, "text": "Accuracy" }, { "code": null, "e": 6577, "s": 6560, "text": "train_accuracy_1" }, { "code": null, "e": 6592, "s": 6577, "text": "accuracy_top_5" }, { "code": null, "e": 6615, "s": 6592, "text": "train_accuracy_top_5_1" }, { "code": null, "e": 6620, "s": 6615, "text": "Loss" }, { "code": null, "e": 6628, "s": 6620, "text": "l2_loss" }, { "code": null, "e": 6644, "s": 6628, "text": "cross_entropy_1" }, { "code": null, "e": 6660, "s": 6644, "text": "learning_rate_1" }, { "code": null, "e": 6664, "s": 6660, "text": "sec" }, { "code": null, "e": 6830, "s": 6664, "text": "That’s about it! Please let us know if you have any issues in training ResNet. Also, what tips and tricks do you use when training models in TensorFlow? Let me know!" } ]
Quiver Plots using Plotly in Python - GeeksforGeeks
05 Sep, 2020 A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. A quiver plot displays velocity vectors as arrows with the components (u, v) at the points (x, y). The quiver(x, y, u, v) plots vectors as arrows at the coordinates which are specified in each corresponding pair of elements in x and y. The main advantage of using a quiver plot is it can represent a wider range of magnitudes without having the arrows shrink to dots or overlap one another. Syntax: create_quiver(x, y, u, v, scale=0.1, arrow_scale=0.3, angle=0.3490658503988659, scaleratio=None) Parameters: x: x coordinates of the arrow locations y: y coordinates of the arrow locations u: x components of the arrow vectors v: y components of the arrow vectors arrow_scale: value multiplied to length of barb to get length of arrowhead. Default = .3 angle: angle of arrowhead. Default = pi/9 Example: Python3 import plotly.figure_factory as ffimport numpy as np x = np.linspace(-2, 2, 60)y = np.linspace(-1, 1, 60)Y, X = np.meshgrid(x, y)u = 1 - X**2 + Yv = -1 + X - Y**2 # Create quiver plotfig = ff.create_quiver(x, y, u, v, arrow_scale=.1) fig.show() Output: A quiver plot can be shown with the points with the help of the add_trace() method of graph_objects class. The scatter plot is added in such a way that shows the origin of the quivers. Example: Python3 import plotly.figure_factory as ffimport plotly.graph_objects as goimport numpy as np x = np.linspace(-2, 2, 60)y = np.linspace(-1, 1, 60)Y, X = np.meshgrid(x, y)u = np.cos(X)*Yv = np.sin(X)*Y # Create quiver plotfig = ff.create_quiver(x, y, u, v, arrow_scale=.1) # Adding scatter as the originfig.add_trace(go.Scatter(x = [0], y = [0], mode = 'markers', marker_size = 15 )) fig.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 25015, "s": 24987, "text": "\n05 Sep, 2020" }, { "code": null, "e": 25319, "s": 25015, "text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library." }, { "code": null, "e": 25710, "s": 25319, "text": "A quiver plot displays velocity vectors as arrows with the components (u, v) at the points (x, y). The quiver(x, y, u, v) plots vectors as arrows at the coordinates which are specified in each corresponding pair of elements in x and y. The main advantage of using a quiver plot is it can represent a wider range of magnitudes without having the arrows shrink to dots or overlap one another." }, { "code": null, "e": 25815, "s": 25710, "text": "Syntax: create_quiver(x, y, u, v, scale=0.1, arrow_scale=0.3, angle=0.3490658503988659, scaleratio=None)" }, { "code": null, "e": 25827, "s": 25815, "text": "Parameters:" }, { "code": null, "e": 25867, "s": 25827, "text": "x: x coordinates of the arrow locations" }, { "code": null, "e": 25907, "s": 25867, "text": "y: y coordinates of the arrow locations" }, { "code": null, "e": 25944, "s": 25907, "text": "u: x components of the arrow vectors" }, { "code": null, "e": 25981, "s": 25944, "text": "v: y components of the arrow vectors" }, { "code": null, "e": 26070, "s": 25981, "text": "arrow_scale: value multiplied to length of barb to get length of arrowhead. Default = .3" }, { "code": null, "e": 26112, "s": 26070, "text": "angle: angle of arrowhead. Default = pi/9" }, { "code": null, "e": 26121, "s": 26112, "text": "Example:" }, { "code": null, "e": 26129, "s": 26121, "text": "Python3" }, { "code": "import plotly.figure_factory as ffimport numpy as np x = np.linspace(-2, 2, 60)y = np.linspace(-1, 1, 60)Y, X = np.meshgrid(x, y)u = 1 - X**2 + Yv = -1 + X - Y**2 # Create quiver plotfig = ff.create_quiver(x, y, u, v, arrow_scale=.1) fig.show()", "e": 26377, "s": 26129, "text": null }, { "code": null, "e": 26385, "s": 26377, "text": "Output:" }, { "code": null, "e": 26570, "s": 26385, "text": "A quiver plot can be shown with the points with the help of the add_trace() method of graph_objects class. The scatter plot is added in such a way that shows the origin of the quivers." }, { "code": null, "e": 26579, "s": 26570, "text": "Example:" }, { "code": null, "e": 26587, "s": 26579, "text": "Python3" }, { "code": "import plotly.figure_factory as ffimport plotly.graph_objects as goimport numpy as np x = np.linspace(-2, 2, 60)y = np.linspace(-1, 1, 60)Y, X = np.meshgrid(x, y)u = np.cos(X)*Yv = np.sin(X)*Y # Create quiver plotfig = ff.create_quiver(x, y, u, v, arrow_scale=.1) # Adding scatter as the originfig.add_trace(go.Scatter(x = [0], y = [0], mode = 'markers', marker_size = 15 )) fig.show()", "e": 27047, "s": 26587, "text": null }, { "code": null, "e": 27055, "s": 27047, "text": "Output:" }, { "code": null, "e": 27069, "s": 27055, "text": "Python-Plotly" }, { "code": null, "e": 27076, "s": 27069, "text": "Python" }, { "code": null, "e": 27174, "s": 27076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27202, "s": 27174, "text": "Read JSON file using Python" }, { "code": null, "e": 27252, "s": 27202, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27274, "s": 27252, "text": "Python map() function" }, { "code": null, "e": 27318, "s": 27274, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27336, "s": 27318, "text": "Python Dictionary" }, { "code": null, "e": 27359, "s": 27336, "text": "Taking input in Python" }, { "code": null, "e": 27394, "s": 27359, "text": "Read a file line by line in Python" }, { "code": null, "e": 27426, "s": 27394, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27448, "s": 27426, "text": "Enumerate() in Python" } ]
Program for Goldbach’s Conjecture (Two Primes with given Sum) - GeeksforGeeks
24 May, 2021 Goldbach’s conjecture is one of the oldest and best-known unsolved problems in the number theory of mathematics. Every even integer greater than 2 can be expressed as the sum of two primes. Examples: Input : n = 44 Output : 3 + 41 (both are primes) Input : n = 56 Output : 3 + 53 (both are primes) Find the prime numbers using Sieve of SundaramCheck if the entered number is an even number greater than 2 or not, if no return.If yes, then one by one subtract a prime from N and then check if the difference is also a prime. If yes, then express it as a sum. Find the prime numbers using Sieve of Sundaram Check if the entered number is an even number greater than 2 or not, if no return. If yes, then one by one subtract a prime from N and then check if the difference is also a prime. If yes, then express it as a sum. C++ Java Python3 C# PHP Javascript // C++ program to implement Goldbach's conjecture#include<bits/stdc++.h>using namespace std;const int MAX = 10000; // Array to store all prime less than and equal to 10^6vector <int> primes; // Utility function for Sieve of Sundaramvoid sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i + j + 2*i*j from others where 1 <= i <= j bool marked[MAX/2 + 100] = {0}; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i=1; i<=(sqrt(MAX)-1)/2; i++) for (int j=(i*(i+1))<<1; j<=MAX/2; j=j+2*i+1) marked[j] = true; // Since 2 is a prime number primes.push_back(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i=1; i<=MAX/2; i++) if (marked[i] == false) primes.push_back(2*i + 1);} // Function to perform Goldbach's conjecturevoid findPrimes(int n){ // Return if number is not even or less than 3 if (n<=2 || n%2 != 0) { cout << "Invalid Input \n"; return; } // Check only upto half of number for (int i=0 ; primes[i] <= n/2; i++) { // find difference by subtracting current prime from n int diff = n - primes[i]; // Search if the difference is also a prime number if (binary_search(primes.begin(), primes.end(), diff)) { // Express as a sum of primes cout << primes[i] << " + " << diff << " = " << n << endl; return; } }} // Driver codeint main(){ // Finding all prime numbers before limit sieveSundaram(); // Express number as a sum of two primes findPrimes(4); findPrimes(38); findPrimes(100); return 0;} // Java program to implement Goldbach's conjectureimport java.util.*; class GFG{ static int MAX = 10000; // Array to store all prime less// than and equal to 10^6static ArrayList<Integer> primes = new ArrayList<Integer>(); // Utility function for Sieve of Sundaramstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for // a number given number x. Since // we want primes smaller than MAX, // we reduce MAX to half This array is // used to separate numbers of the form // i + j + 2*i*j from others where 1 <= i <= j boolean[] marked = new boolean[MAX / 2 + 100]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.sqrt(MAX) - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.add(2 * i + 1);} // Function to perform Goldbach's conjecturestatic void findPrimes(int n){ // Return if number is not even or less than 3 if (n <= 2 || n % 2 != 0) { System.out.println("Invalid Input "); return; } // Check only upto half of number for (int i = 0 ; primes.get(i) <= n / 2; i++) { // find difference by subtracting // current prime from n int diff = n - primes.get(i); // Search if the difference is // also a prime number if (primes.contains(diff)) { // Express as a sum of primes System.out.println(primes.get(i) + " + " + diff + " = " + n); return; } }} // Driver codepublic static void main (String[] args){ // Finding all prime numbers before limit sieveSundaram(); // Express number as a sum of two primes findPrimes(4); findPrimes(38); findPrimes(100);}} // This code is contributed by mits # Python3 program to implement Goldbach's# conjectureimport mathMAX = 10000; # Array to store all prime less# than and equal to 10^6primes = []; # Utility function for Sieve of Sundaramdef sieveSundaram(): # In general Sieve of Sundaram, produces # primes smaller than (2*x + 2) for a # number given number x. Since we want # primes smaller than MAX, we reduce # MAX to half. This array is used to # separate numbers of the form i + j + 2*i*j # from others where 1 <= i <= j marked = [False] * (int(MAX / 2) + 100); # Main logic of Sundaram. Mark all # numbers which do not generate prime # number by doing 2*i+1 for i in range(1, int((math.sqrt(MAX) - 1) / 2) + 1): for j in range((i * (i + 1)) << 1, int(MAX / 2) + 1, 2 * i + 1): marked[j] = True; # Since 2 is a prime number primes.append(2); # Print other primes. Remaining primes # are of the form 2*i + 1 such that # marked[i] is false. for i in range(1, int(MAX / 2) + 1): if (marked[i] == False): primes.append(2 * i + 1); # Function to perform Goldbach's conjecturedef findPrimes(n): # Return if number is not even # or less than 3 if (n <= 2 or n % 2 != 0): print("Invalid Input"); return; # Check only upto half of number i = 0; while (primes[i] <= n // 2): # find difference by subtracting # current prime from n diff = n - primes[i]; # Search if the difference is also # a prime number if diff in primes: # Express as a sum of primes print(primes[i], "+", diff, "=", n); return; i += 1; # Driver code # Finding all prime numbers before limitsieveSundaram(); # Express number as a sum of two primesfindPrimes(4);findPrimes(38);findPrimes(100); # This code is contributed# by chandan_jnu // C# program to implement Goldbach's conjectureusing System;using System.Collections.Generic; class GFG{ static int MAX = 10000; // Array to store all prime less// than and equal to 10^6static List<int> primes = new List<int>(); // Utility function for Sieve of Sundaramstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for // a number given number x. Since // we want primes smaller than MAX, // we reduce MAX to half This array is // used to separate numbers of the form // i + j + 2*i*j from others where 1 <= i <= j Boolean[] marked = new Boolean[MAX / 2 + 100]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.Sqrt(MAX) - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.Add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.Add(2 * i + 1);} // Function to perform Goldbach's conjecturestatic void findPrimes(int n){ // Return if number is not even or less than 3 if (n <= 2 || n % 2 != 0) { Console.WriteLine("Invalid Input "); return; } // Check only upto half of number for (int i = 0 ; primes[i] <= n / 2; i++) { // find difference by subtracting // current prime from n int diff = n - primes[i]; // Search if the difference is // also a prime number if (primes.Contains(diff)) { // Express as a sum of primes Console.WriteLine(primes[i] + " + " + diff + " = " + n); return; } }} // Driver codepublic static void Main (String[] args){ // Finding all prime numbers before limit sieveSundaram(); // Express number as a sum of two primes findPrimes(4); findPrimes(38); findPrimes(100);}} /* This code contributed by PrinciRaj1992 */ <?php// PHP program to implement Goldbach's// conjecture$MAX = 10000; // Array to store all prime less than// and equal to 10^6$primes = array(); // Utility function for Sieve of Sundaramfunction sieveSundaram(){ global $MAX, $primes; // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than MAX, we reduce // MAX to half. This array is used to // separate numbers of the form i + j + 2*i*j // from others where 1 <= i <= j $marked = array_fill(0, (int)($MAX / 2) + 100, false); // Main logic of Sundaram. Mark all // numbers which do not generate prime // number by doing 2*i+1 for ($i = 1; $i <= (sqrt($MAX) - 1) / 2; $i++) for ($j = ($i * ($i + 1)) << 1; $j <= $MAX / 2; $j = $j + 2 * $i + 1) $marked[$j] = true; // Since 2 is a prime number array_push($primes, 2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for ($i = 1; $i <= $MAX / 2; $i++) if ($marked[$i] == false) array_push($primes, 2 * $i + 1);} // Function to perform Goldbach's conjecturefunction findPrimes($n){ global $MAX, $primes; // Return if number is not even // or less than 3 if ($n <= 2 || $n % 2 != 0) { print("Invalid Input \n"); return; } // Check only upto half of number for ($i = 0; $primes[$i] <= $n / 2; $i++) { // find difference by subtracting // current prime from n $diff = $n - $primes[$i]; // Search if the difference is also a // prime number if (in_array($diff, $primes)) { // Express as a sum of primes print($primes[$i] . " + " . $diff . " = " . $n . "\n"); return; } }} // Driver code // Finding all prime numbers before limitsieveSundaram(); // Express number as a sum of two primesfindPrimes(4);findPrimes(38);findPrimes(100); // This code is contributed by chandan_jnu?> <script>// Javascript program to implement Goldbach's// conjecturelet MAX = 10000; // Array to store all prime less than// and equal to 10^6let primes = new Array(); // Utility function for Sieve of Sundaramfunction sieveSundaram(){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than MAX, we reduce // MAX to half. This array is used to // separate numbers of the form i + j + 2*i*j // from others where 1 <= i <= j let marked = new Array(parseInt(MAX / 2) + 100).fill(false); // Main logic of Sundaram. Mark all // numbers which do not generate prime // number by doing 2*i+1 for (let i = 1; i <= (Math.sqrt(MAX) - 1) / 2; i++) for (let j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.push(2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for (let i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.push(2 * i + 1);} // Function to perform Goldbach's conjecturefunction findPrimes(n){ // Return if number is not even // or less than 3 if (n <= 2 || n % 2 != 0) { document.write("Invalid Input <br>"); return; } // Check only upto half of number for (let i = 0; primes[i] <= n / 2; i++) { // find difference by subtracting // current prime from n let diff = n - primes[i]; // Search if the difference is also a // prime number if (primes.includes(diff)) { // Express as a sum of primes document.write(primes[i] + " + " + diff + " = " + n + "<br>"); return; } }} // Driver code // Finding all prime numbers before limitsieveSundaram(); // Express number as a sum of two primesfindPrimes(4);findPrimes(38);findPrimes(100); // This code is contributed by gfgking</script> Output: 2 + 2 = 4 7 + 31 = 38 3 + 97 = 100 A Goldbach number is a positive integer that can be expressed as the sum of two odd primes. Since four is the only even number greater than two that requires the even prime 2 in order to be written as the sum of two primes, another form of the statement of Goldbach’s conjecture is that all even integers greater than 4 are Goldbach numbers. This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. Chandan_Kumar Mithun Kumar princiraj1992 gfgking number-theory Prime Number Mathematical number-theory Mathematical Prime Number 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 Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Find minimum number of coins that make a given value Program to find sum of elements in a given array Program to print prime numbers from 1 to N.
[ { "code": null, "e": 25949, "s": 25921, "text": "\n24 May, 2021" }, { "code": null, "e": 26139, "s": 25949, "text": "Goldbach’s conjecture is one of the oldest and best-known unsolved problems in the number theory of mathematics. Every even integer greater than 2 can be expressed as the sum of two primes." }, { "code": null, "e": 26151, "s": 26139, "text": "Examples: " }, { "code": null, "e": 26257, "s": 26151, "text": "Input : n = 44\nOutput : 3 + 41 (both are primes)\n\nInput : n = 56\nOutput : 3 + 53 (both are primes) " }, { "code": null, "e": 26517, "s": 26257, "text": "Find the prime numbers using Sieve of SundaramCheck if the entered number is an even number greater than 2 or not, if no return.If yes, then one by one subtract a prime from N and then check if the difference is also a prime. If yes, then express it as a sum." }, { "code": null, "e": 26564, "s": 26517, "text": "Find the prime numbers using Sieve of Sundaram" }, { "code": null, "e": 26647, "s": 26564, "text": "Check if the entered number is an even number greater than 2 or not, if no return." }, { "code": null, "e": 26779, "s": 26647, "text": "If yes, then one by one subtract a prime from N and then check if the difference is also a prime. If yes, then express it as a sum." }, { "code": null, "e": 26785, "s": 26781, "text": "C++" }, { "code": null, "e": 26790, "s": 26785, "text": "Java" }, { "code": null, "e": 26798, "s": 26790, "text": "Python3" }, { "code": null, "e": 26801, "s": 26798, "text": "C#" }, { "code": null, "e": 26805, "s": 26801, "text": "PHP" }, { "code": null, "e": 26816, "s": 26805, "text": "Javascript" }, { "code": "// C++ program to implement Goldbach's conjecture#include<bits/stdc++.h>using namespace std;const int MAX = 10000; // Array to store all prime less than and equal to 10^6vector <int> primes; // Utility function for Sieve of Sundaramvoid sieveSundaram(){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. Since // we want primes smaller than MAX, we reduce MAX to half // This array is used to separate numbers of the form // i + j + 2*i*j from others where 1 <= i <= j bool marked[MAX/2 + 100] = {0}; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i=1; i<=(sqrt(MAX)-1)/2; i++) for (int j=(i*(i+1))<<1; j<=MAX/2; j=j+2*i+1) marked[j] = true; // Since 2 is a prime number primes.push_back(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i=1; i<=MAX/2; i++) if (marked[i] == false) primes.push_back(2*i + 1);} // Function to perform Goldbach's conjecturevoid findPrimes(int n){ // Return if number is not even or less than 3 if (n<=2 || n%2 != 0) { cout << \"Invalid Input \\n\"; return; } // Check only upto half of number for (int i=0 ; primes[i] <= n/2; i++) { // find difference by subtracting current prime from n int diff = n - primes[i]; // Search if the difference is also a prime number if (binary_search(primes.begin(), primes.end(), diff)) { // Express as a sum of primes cout << primes[i] << \" + \" << diff << \" = \" << n << endl; return; } }} // Driver codeint main(){ // Finding all prime numbers before limit sieveSundaram(); // Express number as a sum of two primes findPrimes(4); findPrimes(38); findPrimes(100); return 0;}", "e": 28760, "s": 26816, "text": null }, { "code": "// Java program to implement Goldbach's conjectureimport java.util.*; class GFG{ static int MAX = 10000; // Array to store all prime less// than and equal to 10^6static ArrayList<Integer> primes = new ArrayList<Integer>(); // Utility function for Sieve of Sundaramstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for // a number given number x. Since // we want primes smaller than MAX, // we reduce MAX to half This array is // used to separate numbers of the form // i + j + 2*i*j from others where 1 <= i <= j boolean[] marked = new boolean[MAX / 2 + 100]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.sqrt(MAX) - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.add(2 * i + 1);} // Function to perform Goldbach's conjecturestatic void findPrimes(int n){ // Return if number is not even or less than 3 if (n <= 2 || n % 2 != 0) { System.out.println(\"Invalid Input \"); return; } // Check only upto half of number for (int i = 0 ; primes.get(i) <= n / 2; i++) { // find difference by subtracting // current prime from n int diff = n - primes.get(i); // Search if the difference is // also a prime number if (primes.contains(diff)) { // Express as a sum of primes System.out.println(primes.get(i) + \" + \" + diff + \" = \" + n); return; } }} // Driver codepublic static void main (String[] args){ // Finding all prime numbers before limit sieveSundaram(); // Express number as a sum of two primes findPrimes(4); findPrimes(38); findPrimes(100);}} // This code is contributed by mits", "e": 30891, "s": 28760, "text": null }, { "code": "# Python3 program to implement Goldbach's# conjectureimport mathMAX = 10000; # Array to store all prime less# than and equal to 10^6primes = []; # Utility function for Sieve of Sundaramdef sieveSundaram(): # In general Sieve of Sundaram, produces # primes smaller than (2*x + 2) for a # number given number x. Since we want # primes smaller than MAX, we reduce # MAX to half. This array is used to # separate numbers of the form i + j + 2*i*j # from others where 1 <= i <= j marked = [False] * (int(MAX / 2) + 100); # Main logic of Sundaram. Mark all # numbers which do not generate prime # number by doing 2*i+1 for i in range(1, int((math.sqrt(MAX) - 1) / 2) + 1): for j in range((i * (i + 1)) << 1, int(MAX / 2) + 1, 2 * i + 1): marked[j] = True; # Since 2 is a prime number primes.append(2); # Print other primes. Remaining primes # are of the form 2*i + 1 such that # marked[i] is false. for i in range(1, int(MAX / 2) + 1): if (marked[i] == False): primes.append(2 * i + 1); # Function to perform Goldbach's conjecturedef findPrimes(n): # Return if number is not even # or less than 3 if (n <= 2 or n % 2 != 0): print(\"Invalid Input\"); return; # Check only upto half of number i = 0; while (primes[i] <= n // 2): # find difference by subtracting # current prime from n diff = n - primes[i]; # Search if the difference is also # a prime number if diff in primes: # Express as a sum of primes print(primes[i], \"+\", diff, \"=\", n); return; i += 1; # Driver code # Finding all prime numbers before limitsieveSundaram(); # Express number as a sum of two primesfindPrimes(4);findPrimes(38);findPrimes(100); # This code is contributed# by chandan_jnu", "e": 32804, "s": 30891, "text": null }, { "code": "// C# program to implement Goldbach's conjectureusing System;using System.Collections.Generic; class GFG{ static int MAX = 10000; // Array to store all prime less// than and equal to 10^6static List<int> primes = new List<int>(); // Utility function for Sieve of Sundaramstatic void sieveSundaram(){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for // a number given number x. Since // we want primes smaller than MAX, // we reduce MAX to half This array is // used to separate numbers of the form // i + j + 2*i*j from others where 1 <= i <= j Boolean[] marked = new Boolean[MAX / 2 + 100]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.Sqrt(MAX) - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.Add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.Add(2 * i + 1);} // Function to perform Goldbach's conjecturestatic void findPrimes(int n){ // Return if number is not even or less than 3 if (n <= 2 || n % 2 != 0) { Console.WriteLine(\"Invalid Input \"); return; } // Check only upto half of number for (int i = 0 ; primes[i] <= n / 2; i++) { // find difference by subtracting // current prime from n int diff = n - primes[i]; // Search if the difference is // also a prime number if (primes.Contains(diff)) { // Express as a sum of primes Console.WriteLine(primes[i] + \" + \" + diff + \" = \" + n); return; } }} // Driver codepublic static void Main (String[] args){ // Finding all prime numbers before limit sieveSundaram(); // Express number as a sum of two primes findPrimes(4); findPrimes(38); findPrimes(100);}} /* This code contributed by PrinciRaj1992 */", "e": 34937, "s": 32804, "text": null }, { "code": "<?php// PHP program to implement Goldbach's// conjecture$MAX = 10000; // Array to store all prime less than// and equal to 10^6$primes = array(); // Utility function for Sieve of Sundaramfunction sieveSundaram(){ global $MAX, $primes; // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than MAX, we reduce // MAX to half. This array is used to // separate numbers of the form i + j + 2*i*j // from others where 1 <= i <= j $marked = array_fill(0, (int)($MAX / 2) + 100, false); // Main logic of Sundaram. Mark all // numbers which do not generate prime // number by doing 2*i+1 for ($i = 1; $i <= (sqrt($MAX) - 1) / 2; $i++) for ($j = ($i * ($i + 1)) << 1; $j <= $MAX / 2; $j = $j + 2 * $i + 1) $marked[$j] = true; // Since 2 is a prime number array_push($primes, 2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for ($i = 1; $i <= $MAX / 2; $i++) if ($marked[$i] == false) array_push($primes, 2 * $i + 1);} // Function to perform Goldbach's conjecturefunction findPrimes($n){ global $MAX, $primes; // Return if number is not even // or less than 3 if ($n <= 2 || $n % 2 != 0) { print(\"Invalid Input \\n\"); return; } // Check only upto half of number for ($i = 0; $primes[$i] <= $n / 2; $i++) { // find difference by subtracting // current prime from n $diff = $n - $primes[$i]; // Search if the difference is also a // prime number if (in_array($diff, $primes)) { // Express as a sum of primes print($primes[$i] . \" + \" . $diff . \" = \" . $n . \"\\n\"); return; } }} // Driver code // Finding all prime numbers before limitsieveSundaram(); // Express number as a sum of two primesfindPrimes(4);findPrimes(38);findPrimes(100); // This code is contributed by chandan_jnu?>", "e": 37048, "s": 34937, "text": null }, { "code": "<script>// Javascript program to implement Goldbach's// conjecturelet MAX = 10000; // Array to store all prime less than// and equal to 10^6let primes = new Array(); // Utility function for Sieve of Sundaramfunction sieveSundaram(){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x. Since we want // primes smaller than MAX, we reduce // MAX to half. This array is used to // separate numbers of the form i + j + 2*i*j // from others where 1 <= i <= j let marked = new Array(parseInt(MAX / 2) + 100).fill(false); // Main logic of Sundaram. Mark all // numbers which do not generate prime // number by doing 2*i+1 for (let i = 1; i <= (Math.sqrt(MAX) - 1) / 2; i++) for (let j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.push(2); // Print other primes. Remaining primes // are of the form 2*i + 1 such that // marked[i] is false. for (let i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.push(2 * i + 1);} // Function to perform Goldbach's conjecturefunction findPrimes(n){ // Return if number is not even // or less than 3 if (n <= 2 || n % 2 != 0) { document.write(\"Invalid Input <br>\"); return; } // Check only upto half of number for (let i = 0; primes[i] <= n / 2; i++) { // find difference by subtracting // current prime from n let diff = n - primes[i]; // Search if the difference is also a // prime number if (primes.includes(diff)) { // Express as a sum of primes document.write(primes[i] + \" + \" + diff + \" = \" + n + \"<br>\"); return; } }} // Driver code // Finding all prime numbers before limitsieveSundaram(); // Express number as a sum of two primesfindPrimes(4);findPrimes(38);findPrimes(100); // This code is contributed by gfgking</script>", "e": 39074, "s": 37048, "text": null }, { "code": null, "e": 39084, "s": 39074, "text": "Output: " }, { "code": null, "e": 39119, "s": 39084, "text": "2 + 2 = 4\n7 + 31 = 38\n3 + 97 = 100" }, { "code": null, "e": 39889, "s": 39119, "text": "A Goldbach number is a positive integer that can be expressed as the sum of two odd primes. Since four is the only even number greater than two that requires the even prime 2 in order to be written as the sum of two primes, another form of the statement of Goldbach’s conjecture is that all even integers greater than 4 are Goldbach numbers. This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. " }, { "code": null, "e": 39903, "s": 39889, "text": "Chandan_Kumar" }, { "code": null, "e": 39916, "s": 39903, "text": "Mithun Kumar" }, { "code": null, "e": 39930, "s": 39916, "text": "princiraj1992" }, { "code": null, "e": 39938, "s": 39930, "text": "gfgking" }, { "code": null, "e": 39952, "s": 39938, "text": "number-theory" }, { "code": null, "e": 39965, "s": 39952, "text": "Prime Number" }, { "code": null, "e": 39978, "s": 39965, "text": "Mathematical" }, { "code": null, "e": 39992, "s": 39978, "text": "number-theory" }, { "code": null, "e": 40005, "s": 39992, "text": "Mathematical" }, { "code": null, "e": 40018, "s": 40005, "text": "Prime Number" }, { "code": null, "e": 40116, "s": 40018, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40140, "s": 40116, "text": "Merge two sorted arrays" }, { "code": null, "e": 40183, "s": 40140, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 40197, "s": 40183, "text": "Prime Numbers" }, { "code": null, "e": 40270, "s": 40197, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 40291, "s": 40270, "text": "Operators in C / C++" }, { "code": null, "e": 40334, "s": 40291, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 40368, "s": 40334, "text": "Program for factorial of a number" }, { "code": null, "e": 40421, "s": 40368, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 40470, "s": 40421, "text": "Program to find sum of elements in a given array" } ]
Tailwind CSS Box Shadow - GeeksforGeeks
23 Mar, 2022 This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. By using this class we can control the box-shadow of an element. In CSS, we do that by using the CSS Shadow Effect properties of box-shadow. Box Shadow classes: shadow-sm: This class is used to create a faded or small shadow effects on the box. shadow: This class is used to create normal shadow effects on the box. shadow-md: This class is used to create md effects on the box. shadow-lg: This class is used to create lg shadow effects on the box. shadow-xl: This class is used to create xl shadow effects on the box. shadow-2xl: This class is used to create 2xl shadow effects on the box. shadow-inner: This class is used to create shadow effects inside the box. shadow-none: This class is used to dilute the shadow effects. Syntax: <element class="shadow-{shadow-depth}">...</element> Example: HTML <!DOCTYPE html> <head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Box Shadow Class</b> <div class="grid grid-flow-col text-center p-2"> <div class="shadow-sm w-24 h-24 bg-green-200 rounded-lg">shadow-sm </div> <div class="shadow w-24 h-24 bg-green-200 rounded-lg">shadow </div> <div class="shadow-md w-24 h-24 bg-green-200 rounded-lg">shadow-md </div> <div class="shadow-lg w-24 h-24 bg-green-200 rounded-lg">shadow-lg </div> <div class="shadow-xl w-24 h-24 bg-green-200 rounded-lg">shadow-xl </div> <div class="shadow-2xl w-24 h-24 bg-green-200 rounded-lg">shadow-2xl </div> </div> </body> </html> Output: Tailwind CSS Box shadow class Tailwind CSS Tailwind-Effects CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37385, "s": 37357, "text": "\n23 Mar, 2022" }, { "code": null, "e": 37631, "s": 37385, "text": "This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. By using this class we can control the box-shadow of an element. In CSS, we do that by using the CSS Shadow Effect properties of box-shadow. " }, { "code": null, "e": 37651, "s": 37631, "text": "Box Shadow classes:" }, { "code": null, "e": 37735, "s": 37651, "text": "shadow-sm: This class is used to create a faded or small shadow effects on the box." }, { "code": null, "e": 37806, "s": 37735, "text": "shadow: This class is used to create normal shadow effects on the box." }, { "code": null, "e": 37869, "s": 37806, "text": "shadow-md: This class is used to create md effects on the box." }, { "code": null, "e": 37939, "s": 37869, "text": "shadow-lg: This class is used to create lg shadow effects on the box." }, { "code": null, "e": 38009, "s": 37939, "text": "shadow-xl: This class is used to create xl shadow effects on the box." }, { "code": null, "e": 38081, "s": 38009, "text": "shadow-2xl: This class is used to create 2xl shadow effects on the box." }, { "code": null, "e": 38155, "s": 38081, "text": "shadow-inner: This class is used to create shadow effects inside the box." }, { "code": null, "e": 38217, "s": 38155, "text": "shadow-none: This class is used to dilute the shadow effects." }, { "code": null, "e": 38225, "s": 38217, "text": "Syntax:" }, { "code": null, "e": 38278, "s": 38225, "text": "<element class=\"shadow-{shadow-depth}\">...</element>" }, { "code": null, "e": 38287, "s": 38278, "text": "Example:" }, { "code": null, "e": 38292, "s": 38287, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Box Shadow Class</b> <div class=\"grid grid-flow-col text-center p-2\"> <div class=\"shadow-sm w-24 h-24 bg-green-200 rounded-lg\">shadow-sm </div> <div class=\"shadow w-24 h-24 bg-green-200 rounded-lg\">shadow </div> <div class=\"shadow-md w-24 h-24 bg-green-200 rounded-lg\">shadow-md </div> <div class=\"shadow-lg w-24 h-24 bg-green-200 rounded-lg\">shadow-lg </div> <div class=\"shadow-xl w-24 h-24 bg-green-200 rounded-lg\">shadow-xl </div> <div class=\"shadow-2xl w-24 h-24 bg-green-200 rounded-lg\">shadow-2xl </div> </div> </body> </html>", "e": 39317, "s": 38292, "text": null }, { "code": null, "e": 39325, "s": 39317, "text": "Output:" }, { "code": null, "e": 39355, "s": 39325, "text": "Tailwind CSS Box shadow class" }, { "code": null, "e": 39368, "s": 39355, "text": "Tailwind CSS" }, { "code": null, "e": 39385, "s": 39368, "text": "Tailwind-Effects" }, { "code": null, "e": 39389, "s": 39385, "text": "CSS" }, { "code": null, "e": 39406, "s": 39389, "text": "Web Technologies" }, { "code": null, "e": 39504, "s": 39406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39554, "s": 39504, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39616, "s": 39554, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39664, "s": 39616, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39722, "s": 39664, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 39777, "s": 39722, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 39817, "s": 39777, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 39850, "s": 39817, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39895, "s": 39850, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39938, "s": 39895, "text": "How to fetch data from an API in ReactJS ?" } ]
Stack | Set 2 (Infix to Postfix) - GeeksforGeeks
12 Apr, 2022 Prerequisite – Stack | Set 1 (Introduction) Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands.Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands.Why postfix representation of the expression? The compiler scans the expression either from left to right or from right to left. Consider the below expression: a op1 b op2 c op3 d If op1 = +, op2 = *, op3 = +The compiler first scans the expression to evaluate the expression b * c, then again scans the expression to add a to it. The result is then added to d after another scan.The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix) form before evaluation.The corresponding expression in postfix form is abc*+d+. The postfix expressions can be evaluated easily using a stack. We will cover postfix expression evaluation in a separate post.Algorithm 1. Scan the infix expression from left to right. 2. If the scanned character is an operand, output it. 3. Else, 1 If the precedence and associativity of the scanned operator is greater than the precedence and associativity of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it. 2 ‘^’ operator is right associative and other operators like ‘+’,’-‘,’*’ and ‘/’ are left associative. Check especially for a condition when both top of the operator stack and scanned operator are ‘^’. In this condition the precedence of scanned operator is higher due to it’s right associativity. So it will be pushed in the operator stack. In all the other cases when the top of operator stack is same as scanned operator we will pop the operator from the stack because of left associativity due to which the scanned operator has less precedence. 3 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) 4. If the scanned character is an ‘(‘, push it to the stack. 5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis. 6. Repeat steps 2-6 until infix expression is scanned. 7. Print the output 8. Pop and output from the stack until it is not empty. Following is the implementation of the above algorithm C++ C Java Python C# Javascript /* C++ implementation to convertinfix expression to postfix*/ #include <bits/stdc++.h>using namespace std; // Function to return precedence of operatorsint prec(char c){ if (c == '^') return 3; else if (c == '/' || c == '*') return 2; else if (c == '+' || c == '-') return 1; else return -1;} // The main function to convert infix expression// to postfix expressionvoid infixToPostfix(string s){ stack<char> st; // For stack operations, we are using // C++ built in stack string result; for (int i = 0; i < s.length(); i++) { char c = s[i]; // If the scanned character is // an operand, add it to output string. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) result += c; // If the scanned character is an // ‘(‘, push it to the stack. else if (c == '(') st.push('('); // If the scanned character is an ‘)’, // pop and to output string from the stack // until an ‘(‘ is encountered. else if (c == ')') { while (st.top() != '(') { result += st.top(); st.pop(); } st.pop(); } // If an operator is scanned else { while (!st.empty() && prec(s[i]) <= prec(st.top())) { if (c == '^' && st.top() == '^') break; else { result += st.top(); st.pop(); } } st.push(c); } } // Pop all the remaining elements from the stack while (!st.empty()) { result += st.top(); st.pop(); } cout << result << endl;} // Driver program to test above functionsint main(){ string exp = "a+b*(c^d-e)^(f+g*h)-i"; infixToPostfix(exp); return 0;} // C program to convert infix expression to postfix#include <stdio.h>#include <string.h>#include <stdlib.h> // Stack typestruct Stack{ int top; unsigned capacity; int* array;}; // Stack Operationsstruct Stack* createStack( unsigned capacity ){ struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int*) malloc(stack->capacity * sizeof(int)); return stack;}int isEmpty(struct Stack* stack){ return stack->top == -1 ;}char peek(struct Stack* stack){ return stack->array[stack->top];}char pop(struct Stack* stack){ if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$';}void push(struct Stack* stack, char op){ stack->array[++stack->top] = op;} // A utility function to check if// the given character is operandint isOperand(char ch){ return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');} // A utility function to return// precedence of a given operator// Higher returned value means// higher precedenceint Prec(char ch){ switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1;} // The main function that// converts given infix expression// to postfix expression.int infixToPostfix(char* exp){ int i, k; // Create a stack of capacity // equal to expression size struct Stack* stack = createStack(strlen(exp)); if(!stack) // See if stack was created successfully return -1 ; for (i = 0, k = -1; exp[i]; ++i) { // If the scanned character is // an operand, add it to output. if (isOperand(exp[i])) exp[++k] = exp[i]; // If the scanned character is an // ‘(‘, push it to the stack. else if (exp[i] == '(') push(stack, exp[i]); // If the scanned character is an ‘)’, // pop and output from the stack // until an ‘(‘ is encountered. else if (exp[i] == ')') { while (!isEmpty(stack) && peek(stack) != '(') exp[++k] = pop(stack); if (!isEmpty(stack) && peek(stack) != '(') return -1; // invalid expression else pop(stack); } else // an operator is encountered { while (!isEmpty(stack) && Prec(exp[i]) <= Prec(peek(stack))) exp[++k] = pop(stack); push(stack, exp[i]); } } // pop all the operators from the stack while (!isEmpty(stack)) exp[++k] = pop(stack ); exp[++k] = '\0'; printf( "%s", exp );} // Driver program to test above functionsint main(){ char exp[] = "a+b*(c^d-e)^(f+g*h)-i"; infixToPostfix(exp); return 0;} /* Java implementation to convert infix expression to postfix*/// Note that here we use Stack class for Stack operations import java.util.Stack; class Test{ // A utility function to return // precedence of a given operator // Higher returned value means // higher precedence static int Prec(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } // The main method that converts // given infix expression // to postfix expression. static String infixToPostfix(String exp) { // initializing empty String for result String result = new String(""); // initializing empty stack Stack<Character> stack = new Stack<>(); for (int i = 0; i<exp.length(); ++i) { char c = exp.charAt(i); // If the scanned character is an // operand, add it to output. if (Character.isLetterOrDigit(c)) result += c; // If the scanned character is an '(', // push it to the stack. else if (c == '(') stack.push(c); // If the scanned character is an ')', // pop and output from the stack // until an '(' is encountered. else if (c == ')') { while (!stack.isEmpty() && stack.peek() != '(') result += stack.pop(); stack.pop(); } else // an operator is encountered { while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){ result += stack.pop(); } stack.push(c); } } // pop all the operators from the stack while (!stack.isEmpty()){ if(stack.peek() == '(') return "Invalid Expression"; result += stack.pop(); } return result; } // Driver method public static void main(String[] args) { String exp = "a+b*(c^d-e)^(f+g*h)-i"; System.out.println(infixToPostfix(exp)); }} # Python program to convert infix expression to postfix # Class to convert the expression class Conversion: # Constructor to initialize the class variables def __init__(self, capacity): self.top = -1 self.capacity = capacity # This array is used a stack self.array = [] # Precedence setting self.output = [] self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} # check if the stack is empty def isEmpty(self): return True if self.top == -1 else False # Return the value of the top of the stack def peek(self): return self.array[-1] # Pop the element from the stack def pop(self): if not self.isEmpty(): self.top -= 1 return self.array.pop() else: return "$" # Push the element to the stack def push(self, op): self.top += 1 self.array.append(op) # A utility function to check is the given character # is operand def isOperand(self, ch): return ch.isalpha() # Check if the precedence of operator is strictly # less than top of stack or not def notGreater(self, i): try: a = self.precedence[i] b = self.precedence[self.peek()] return True if a <= b else False except KeyError: return False # The main function that # converts given infix expression # to postfix expression def infixToPostfix(self, exp): # Iterate over the expression for conversion for i in exp: # If the character is an operand, # add it to output if self.isOperand(i): self.output.append(i) # If the character is an '(', push it to stack elif i == '(': self.push(i) # If the scanned character is an ')', pop and # output from the stack until and '(' is found elif i == ')': while((not self.isEmpty()) and self.peek() != '('): a = self.pop() self.output.append(a) if (not self.isEmpty() and self.peek() != '('): return -1 else: self.pop() # An operator is encountered else: while(not self.isEmpty() and self.notGreater(i)): # this is to pass cases like a^b^c # without if ab^c^ # with if abc^^ if i == "^" and self.array[-1] == i: break self.output.append(self.pop()) self.push(i) # pop all the operator from the stack while not self.isEmpty(): self.output.append(self.pop()) print "".join(self.output) # Driver program to test above functionexp = "a+b*(c^d-e)^(f+g*h)-i"obj = Conversion(len(exp))obj.infixToPostfix(exp) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System;using System.Collections.Generic; /* c# implementation to convertinfix expression to postfix*/// Note that here we use Stack// class for Stack operations public class Test{ // A utility function to return // precedence of a given operator // Higher returned value means higher precedence internal static int Prec(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } // The main method that converts given infix expression // to postfix expression. public static string infixToPostfix(string exp) { // initializing empty String for result string result = ""; // initializing empty stack Stack<char> stack = new Stack<char>(); for (int i = 0; i < exp.Length; ++i) { char c = exp[i]; // If the scanned character is an // operand, add it to output. if (char.IsLetterOrDigit(c)) { result += c; } // If the scanned character is an '(', // push it to the stack. else if (c == '(') { stack.Push(c); } // If the scanned character is an ')', // pop and output from the stack // until an '(' is encountered. else if (c == ')') { while (stack.Count > 0 && stack.Peek() != '(') { result += stack.Pop(); } if (stack.Count > 0 && stack.Peek() != '(') { return "Invalid Expression"; // invalid expression } else { stack.Pop(); } } else // an operator is encountered { while (stack.Count > 0 && Prec(c) <= Prec(stack.Peek())) { result += stack.Pop(); } stack.Push(c); } } // pop all the operators from the stack while (stack.Count > 0) { result += stack.Pop(); } return result; } // Driver method public static void Main(string[] args) { string exp = "a+b*(c^d-e)^(f+g*h)-i"; Console.WriteLine(infixToPostfix(exp)); }} // This code is contributed by Shrikant13 <script> /* Javascript implementation to convert infix expression to postfix*/ //Function to return precedence of operators function prec(c) { if(c == '^') return 3; else if(c == '/' || c=='*') return 2; else if(c == '+' || c == '-') return 1; else return -1; } // The main function to convert infix expression //to postfix expression function infixToPostfix(s) { let st = []; //For stack operations, we are using C++ built in stack let result = ""; for(let i = 0; i < s.length; i++) { let c = s[i]; // If the scanned character is // an operand, add it to output string. if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) result += c; // If the scanned character is an // ‘(‘, push it to the stack. else if(c == '(') st.push('('); // If the scanned character is an ‘)’, // pop and to output string from the stack // until an ‘(‘ is encountered. else if(c == ')') { while(st[st.length - 1] != '(') { result += st[st.length - 1]; st.pop(); } st.pop(); } //If an operator is scanned else { while(st.length != 0 && prec(s[i]) <= prec(st[st.length - 1])) { result += st[st.length - 1]; st.pop(); } st.push(c); } } // Pop all the remaining elements from the stack while(st.length != 0) { result += st[st.length - 1]; st.pop(); } document.write(result + "</br>"); } let exp = "a+b*(c^d-e)^(f+g*h)-i"; infixToPostfix(exp); // This code is contributed by decode2207.</script> abcd^e-fgh*+^*+i- https://youtu.be/ysDharaQXkw?list=PLqM7alHXFySF7Lap-wi5qlaD8OEBx9RMV Quiz: Stack Questions Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. topcoder786 shrikanth13 viping74 vishwsr sudhanshublaze abraiyan kunalkumarsawece19 menonkartikeya decode2207 ganeshreddychimmula sudhirdaga1998 Amazon expression-evaluation Paytm Samsung VMWare Stack Paytm VMWare Amazon Samsung Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Implement Stack using Queues Merge Overlapping Intervals Difference between Stack and Queue Data Structures Implement two stacks in an array Largest Rectangular Area in a Histogram | Set 2 Maximum size rectangle binary sub-matrix with all 1s Iterative Depth First Traversal of Graph Design and Implement Special Stack Data Structure | Added Space Optimized Version Design a stack that supports getMin() in O(1) time and O(1) extra space Convert Infix To Prefix Notation
[ { "code": null, "e": 26165, "s": 26137, "text": "\n12 Apr, 2022" }, { "code": null, "e": 27453, "s": 26165, "text": "Prerequisite – Stack | Set 1 (Introduction) Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands.Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands.Why postfix representation of the expression? The compiler scans the expression either from left to right or from right to left. Consider the below expression: a op1 b op2 c op3 d If op1 = +, op2 = *, op3 = +The compiler first scans the expression to evaluate the expression b * c, then again scans the expression to add a to it. The result is then added to d after another scan.The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix) form before evaluation.The corresponding expression in postfix form is abc*+d+. The postfix expressions can be evaluated easily using a stack. We will cover postfix expression evaluation in a separate post.Algorithm 1. Scan the infix expression from left to right. 2. If the scanned character is an operand, output it. 3. Else, 1 If the precedence and associativity of the scanned operator is greater than the precedence and associativity of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it." }, { "code": null, "e": 28626, "s": 27453, "text": " 2 ‘^’ operator is right associative and other operators like ‘+’,’-‘,’*’ and ‘/’ are left associative. Check especially for a condition when both top of the operator stack and scanned operator are ‘^’. In this condition the precedence of scanned operator is higher due to it’s right associativity. So it will be pushed in the operator stack. In all the other cases when the top of operator stack is same as scanned operator we will pop the operator from the stack because of left associativity due to which the scanned operator has less precedence. 3 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) 4. If the scanned character is an ‘(‘, push it to the stack. 5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and discard both the parenthesis. 6. Repeat steps 2-6 until infix expression is scanned. 7. Print the output 8. Pop and output from the stack until it is not empty." }, { "code": null, "e": 28683, "s": 28626, "text": "Following is the implementation of the above algorithm " }, { "code": null, "e": 28687, "s": 28683, "text": "C++" }, { "code": null, "e": 28689, "s": 28687, "text": "C" }, { "code": null, "e": 28694, "s": 28689, "text": "Java" }, { "code": null, "e": 28701, "s": 28694, "text": "Python" }, { "code": null, "e": 28704, "s": 28701, "text": "C#" }, { "code": null, "e": 28715, "s": 28704, "text": "Javascript" }, { "code": "/* C++ implementation to convertinfix expression to postfix*/ #include <bits/stdc++.h>using namespace std; // Function to return precedence of operatorsint prec(char c){ if (c == '^') return 3; else if (c == '/' || c == '*') return 2; else if (c == '+' || c == '-') return 1; else return -1;} // The main function to convert infix expression// to postfix expressionvoid infixToPostfix(string s){ stack<char> st; // For stack operations, we are using // C++ built in stack string result; for (int i = 0; i < s.length(); i++) { char c = s[i]; // If the scanned character is // an operand, add it to output string. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) result += c; // If the scanned character is an // ‘(‘, push it to the stack. else if (c == '(') st.push('('); // If the scanned character is an ‘)’, // pop and to output string from the stack // until an ‘(‘ is encountered. else if (c == ')') { while (st.top() != '(') { result += st.top(); st.pop(); } st.pop(); } // If an operator is scanned else { while (!st.empty() && prec(s[i]) <= prec(st.top())) { if (c == '^' && st.top() == '^') break; else { result += st.top(); st.pop(); } } st.push(c); } } // Pop all the remaining elements from the stack while (!st.empty()) { result += st.top(); st.pop(); } cout << result << endl;} // Driver program to test above functionsint main(){ string exp = \"a+b*(c^d-e)^(f+g*h)-i\"; infixToPostfix(exp); return 0;}", "e": 30628, "s": 28715, "text": null }, { "code": "// C program to convert infix expression to postfix#include <stdio.h>#include <string.h>#include <stdlib.h> // Stack typestruct Stack{ int top; unsigned capacity; int* array;}; // Stack Operationsstruct Stack* createStack( unsigned capacity ){ struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int*) malloc(stack->capacity * sizeof(int)); return stack;}int isEmpty(struct Stack* stack){ return stack->top == -1 ;}char peek(struct Stack* stack){ return stack->array[stack->top];}char pop(struct Stack* stack){ if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$';}void push(struct Stack* stack, char op){ stack->array[++stack->top] = op;} // A utility function to check if// the given character is operandint isOperand(char ch){ return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');} // A utility function to return// precedence of a given operator// Higher returned value means// higher precedenceint Prec(char ch){ switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1;} // The main function that// converts given infix expression// to postfix expression.int infixToPostfix(char* exp){ int i, k; // Create a stack of capacity // equal to expression size struct Stack* stack = createStack(strlen(exp)); if(!stack) // See if stack was created successfully return -1 ; for (i = 0, k = -1; exp[i]; ++i) { // If the scanned character is // an operand, add it to output. if (isOperand(exp[i])) exp[++k] = exp[i]; // If the scanned character is an // ‘(‘, push it to the stack. else if (exp[i] == '(') push(stack, exp[i]); // If the scanned character is an ‘)’, // pop and output from the stack // until an ‘(‘ is encountered. else if (exp[i] == ')') { while (!isEmpty(stack) && peek(stack) != '(') exp[++k] = pop(stack); if (!isEmpty(stack) && peek(stack) != '(') return -1; // invalid expression else pop(stack); } else // an operator is encountered { while (!isEmpty(stack) && Prec(exp[i]) <= Prec(peek(stack))) exp[++k] = pop(stack); push(stack, exp[i]); } } // pop all the operators from the stack while (!isEmpty(stack)) exp[++k] = pop(stack ); exp[++k] = '\\0'; printf( \"%s\", exp );} // Driver program to test above functionsint main(){ char exp[] = \"a+b*(c^d-e)^(f+g*h)-i\"; infixToPostfix(exp); return 0;}", "e": 33543, "s": 30628, "text": null }, { "code": "/* Java implementation to convert infix expression to postfix*/// Note that here we use Stack class for Stack operations import java.util.Stack; class Test{ // A utility function to return // precedence of a given operator // Higher returned value means // higher precedence static int Prec(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } // The main method that converts // given infix expression // to postfix expression. static String infixToPostfix(String exp) { // initializing empty String for result String result = new String(\"\"); // initializing empty stack Stack<Character> stack = new Stack<>(); for (int i = 0; i<exp.length(); ++i) { char c = exp.charAt(i); // If the scanned character is an // operand, add it to output. if (Character.isLetterOrDigit(c)) result += c; // If the scanned character is an '(', // push it to the stack. else if (c == '(') stack.push(c); // If the scanned character is an ')', // pop and output from the stack // until an '(' is encountered. else if (c == ')') { while (!stack.isEmpty() && stack.peek() != '(') result += stack.pop(); stack.pop(); } else // an operator is encountered { while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){ result += stack.pop(); } stack.push(c); } } // pop all the operators from the stack while (!stack.isEmpty()){ if(stack.peek() == '(') return \"Invalid Expression\"; result += stack.pop(); } return result; } // Driver method public static void main(String[] args) { String exp = \"a+b*(c^d-e)^(f+g*h)-i\"; System.out.println(infixToPostfix(exp)); }}", "e": 35922, "s": 33543, "text": null }, { "code": "# Python program to convert infix expression to postfix # Class to convert the expression class Conversion: # Constructor to initialize the class variables def __init__(self, capacity): self.top = -1 self.capacity = capacity # This array is used a stack self.array = [] # Precedence setting self.output = [] self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} # check if the stack is empty def isEmpty(self): return True if self.top == -1 else False # Return the value of the top of the stack def peek(self): return self.array[-1] # Pop the element from the stack def pop(self): if not self.isEmpty(): self.top -= 1 return self.array.pop() else: return \"$\" # Push the element to the stack def push(self, op): self.top += 1 self.array.append(op) # A utility function to check is the given character # is operand def isOperand(self, ch): return ch.isalpha() # Check if the precedence of operator is strictly # less than top of stack or not def notGreater(self, i): try: a = self.precedence[i] b = self.precedence[self.peek()] return True if a <= b else False except KeyError: return False # The main function that # converts given infix expression # to postfix expression def infixToPostfix(self, exp): # Iterate over the expression for conversion for i in exp: # If the character is an operand, # add it to output if self.isOperand(i): self.output.append(i) # If the character is an '(', push it to stack elif i == '(': self.push(i) # If the scanned character is an ')', pop and # output from the stack until and '(' is found elif i == ')': while((not self.isEmpty()) and self.peek() != '('): a = self.pop() self.output.append(a) if (not self.isEmpty() and self.peek() != '('): return -1 else: self.pop() # An operator is encountered else: while(not self.isEmpty() and self.notGreater(i)): # this is to pass cases like a^b^c # without if ab^c^ # with if abc^^ if i == \"^\" and self.array[-1] == i: break self.output.append(self.pop()) self.push(i) # pop all the operator from the stack while not self.isEmpty(): self.output.append(self.pop()) print \"\".join(self.output) # Driver program to test above functionexp = \"a+b*(c^d-e)^(f+g*h)-i\"obj = Conversion(len(exp))obj.infixToPostfix(exp) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 38923, "s": 35922, "text": null }, { "code": "using System;using System.Collections.Generic; /* c# implementation to convertinfix expression to postfix*/// Note that here we use Stack// class for Stack operations public class Test{ // A utility function to return // precedence of a given operator // Higher returned value means higher precedence internal static int Prec(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } // The main method that converts given infix expression // to postfix expression. public static string infixToPostfix(string exp) { // initializing empty String for result string result = \"\"; // initializing empty stack Stack<char> stack = new Stack<char>(); for (int i = 0; i < exp.Length; ++i) { char c = exp[i]; // If the scanned character is an // operand, add it to output. if (char.IsLetterOrDigit(c)) { result += c; } // If the scanned character is an '(', // push it to the stack. else if (c == '(') { stack.Push(c); } // If the scanned character is an ')', // pop and output from the stack // until an '(' is encountered. else if (c == ')') { while (stack.Count > 0 && stack.Peek() != '(') { result += stack.Pop(); } if (stack.Count > 0 && stack.Peek() != '(') { return \"Invalid Expression\"; // invalid expression } else { stack.Pop(); } } else // an operator is encountered { while (stack.Count > 0 && Prec(c) <= Prec(stack.Peek())) { result += stack.Pop(); } stack.Push(c); } } // pop all the operators from the stack while (stack.Count > 0) { result += stack.Pop(); } return result; } // Driver method public static void Main(string[] args) { string exp = \"a+b*(c^d-e)^(f+g*h)-i\"; Console.WriteLine(infixToPostfix(exp)); }} // This code is contributed by Shrikant13", "e": 41497, "s": 38923, "text": null }, { "code": "<script> /* Javascript implementation to convert infix expression to postfix*/ //Function to return precedence of operators function prec(c) { if(c == '^') return 3; else if(c == '/' || c=='*') return 2; else if(c == '+' || c == '-') return 1; else return -1; } // The main function to convert infix expression //to postfix expression function infixToPostfix(s) { let st = []; //For stack operations, we are using C++ built in stack let result = \"\"; for(let i = 0; i < s.length; i++) { let c = s[i]; // If the scanned character is // an operand, add it to output string. if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) result += c; // If the scanned character is an // ‘(‘, push it to the stack. else if(c == '(') st.push('('); // If the scanned character is an ‘)’, // pop and to output string from the stack // until an ‘(‘ is encountered. else if(c == ')') { while(st[st.length - 1] != '(') { result += st[st.length - 1]; st.pop(); } st.pop(); } //If an operator is scanned else { while(st.length != 0 && prec(s[i]) <= prec(st[st.length - 1])) { result += st[st.length - 1]; st.pop(); } st.push(c); } } // Pop all the remaining elements from the stack while(st.length != 0) { result += st[st.length - 1]; st.pop(); } document.write(result + \"</br>\"); } let exp = \"a+b*(c^d-e)^(f+g*h)-i\"; infixToPostfix(exp); // This code is contributed by decode2207.</script>", "e": 43470, "s": 41497, "text": null }, { "code": null, "e": 43488, "s": 43470, "text": "abcd^e-fgh*+^*+i-" }, { "code": null, "e": 43579, "s": 43488, "text": "https://youtu.be/ysDharaQXkw?list=PLqM7alHXFySF7Lap-wi5qlaD8OEBx9RMV Quiz: Stack Questions" }, { "code": null, "e": 43707, "s": 43581, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 43721, "s": 43709, "text": "topcoder786" }, { "code": null, "e": 43733, "s": 43721, "text": "shrikanth13" }, { "code": null, "e": 43742, "s": 43733, "text": "viping74" }, { "code": null, "e": 43750, "s": 43742, "text": "vishwsr" }, { "code": null, "e": 43765, "s": 43750, "text": "sudhanshublaze" }, { "code": null, "e": 43774, "s": 43765, "text": "abraiyan" }, { "code": null, "e": 43793, "s": 43774, "text": "kunalkumarsawece19" }, { "code": null, "e": 43808, "s": 43793, "text": "menonkartikeya" }, { "code": null, "e": 43819, "s": 43808, "text": "decode2207" }, { "code": null, "e": 43839, "s": 43819, "text": "ganeshreddychimmula" }, { "code": null, "e": 43854, "s": 43839, "text": "sudhirdaga1998" }, { "code": null, "e": 43861, "s": 43854, "text": "Amazon" }, { "code": null, "e": 43883, "s": 43861, "text": "expression-evaluation" }, { "code": null, "e": 43889, "s": 43883, "text": "Paytm" }, { "code": null, "e": 43897, "s": 43889, "text": "Samsung" }, { "code": null, "e": 43904, "s": 43897, "text": "VMWare" }, { "code": null, "e": 43910, "s": 43904, "text": "Stack" }, { "code": null, "e": 43916, "s": 43910, "text": "Paytm" }, { "code": null, "e": 43923, "s": 43916, "text": "VMWare" }, { "code": null, "e": 43930, "s": 43923, "text": "Amazon" }, { "code": null, "e": 43938, "s": 43930, "text": "Samsung" }, { "code": null, "e": 43944, "s": 43938, "text": "Stack" }, { "code": null, "e": 44042, "s": 43944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44071, "s": 44042, "text": "Implement Stack using Queues" }, { "code": null, "e": 44099, "s": 44071, "text": "Merge Overlapping Intervals" }, { "code": null, "e": 44150, "s": 44099, "text": "Difference between Stack and Queue Data Structures" }, { "code": null, "e": 44183, "s": 44150, "text": "Implement two stacks in an array" }, { "code": null, "e": 44231, "s": 44183, "text": "Largest Rectangular Area in a Histogram | Set 2" }, { "code": null, "e": 44284, "s": 44231, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 44325, "s": 44284, "text": "Iterative Depth First Traversal of Graph" }, { "code": null, "e": 44407, "s": 44325, "text": "Design and Implement Special Stack Data Structure | Added Space Optimized Version" }, { "code": null, "e": 44479, "s": 44407, "text": "Design a stack that supports getMin() in O(1) time and O(1) extra space" } ]
What is the advantage of collapsing white space ? - GeeksforGeeks
21 Oct, 2021 White space refers to empty or blank values in the code which the browser reads and renders. Html has a special feature of collapsing these white spaces. If you put extra/consecutive white spaces or newlines in the code it will regard it as one white space this is known as collapsing of white spaces. In this article, we will discuss the advantages of collapsing white space in HTML. Advantages of collapsing white spaces : While you are writing the HTML for your web page you want the code to be more understandable/readable to the users. Collapsing white spaces decreases the transmission time between the server and the client because collapsing features remove unnecessary bytes that are occupied by the white spaces. By mistake, if you leave extra white space, the browser will ignore it and display the UI perfectly. Example 1: The following example shows the basic example for collapsing white space. The h1 tag contains a lot of space between the short form and the full form. If you run this code in the browser you will see the following output. All the white space in between the two has been converted into a single white space. HTML <!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h1>Welcome to GFG. GeeksforGeeks.</h1></body></html> Output: Collapsed_White_Space Example 2: The following example shows a 2d array of Integers type in code as a structure with each row in a different line. If you will see the output it will come in one line with all the white spaces collapsed. HTML <!DOCTYPE html><html><body> <h1>Example of a 2 D Array of Integers : [ [1,2,3,4,5], [6,7,8,9,10] ] </h1></body></html> Output: Collapsed_White_Space Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions Picked HTML Web Technologies 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 Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n21 Oct, 2021" }, { "code": null, "e": 26524, "s": 26139, "text": "White space refers to empty or blank values in the code which the browser reads and renders. Html has a special feature of collapsing these white spaces. If you put extra/consecutive white spaces or newlines in the code it will regard it as one white space this is known as collapsing of white spaces. In this article, we will discuss the advantages of collapsing white space in HTML." }, { "code": null, "e": 26564, "s": 26524, "text": "Advantages of collapsing white spaces :" }, { "code": null, "e": 26682, "s": 26564, "text": "While you are writing the HTML for your web page you want the code to be more understandable/readable to the users. " }, { "code": null, "e": 26864, "s": 26682, "text": "Collapsing white spaces decreases the transmission time between the server and the client because collapsing features remove unnecessary bytes that are occupied by the white spaces." }, { "code": null, "e": 26965, "s": 26864, "text": "By mistake, if you leave extra white space, the browser will ignore it and display the UI perfectly." }, { "code": null, "e": 27285, "s": 26965, "text": "Example 1: The following example shows the basic example for collapsing white space. The h1 tag contains a lot of space between the short form and the full form. If you run this code in the browser you will see the following output. All the white space in between the two has been converted into a single white space." }, { "code": null, "e": 27290, "s": 27285, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h1>Welcome to GFG. GeeksforGeeks.</h1></body></html>", "e": 27431, "s": 27290, "text": null }, { "code": null, "e": 27440, "s": 27431, "text": "Output: " }, { "code": null, "e": 27462, "s": 27440, "text": "Collapsed_White_Space" }, { "code": null, "e": 27677, "s": 27462, "text": "Example 2: The following example shows a 2d array of Integers type in code as a structure with each row in a different line. If you will see the output it will come in one line with all the white spaces collapsed." }, { "code": null, "e": 27682, "s": 27677, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h1>Example of a 2 D Array of Integers : [ [1,2,3,4,5], [6,7,8,9,10] ] </h1></body></html>", "e": 27855, "s": 27682, "text": null }, { "code": null, "e": 27864, "s": 27855, "text": "Output: " }, { "code": null, "e": 27886, "s": 27864, "text": "Collapsed_White_Space" }, { "code": null, "e": 28023, "s": 27886, "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": 28038, "s": 28023, "text": "HTML-Questions" }, { "code": null, "e": 28045, "s": 28038, "text": "Picked" }, { "code": null, "e": 28050, "s": 28045, "text": "HTML" }, { "code": null, "e": 28067, "s": 28050, "text": "Web Technologies" }, { "code": null, "e": 28072, "s": 28067, "text": "HTML" }, { "code": null, "e": 28170, "s": 28072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28194, "s": 28170, "text": "REST API (Introduction)" }, { "code": null, "e": 28235, "s": 28194, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28272, "s": 28235, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28301, "s": 28272, "text": "Form validation using jQuery" }, { "code": null, "e": 28321, "s": 28301, "text": "Angular File Upload" }, { "code": null, "e": 28361, "s": 28321, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28394, "s": 28361, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28439, "s": 28394, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28482, "s": 28439, "text": "How to fetch data from an API in ReactJS ?" } ]
Minimum step to reach one - GeeksforGeeks
13 Jul, 2021 Given a positive number N, we need to reach to 1 in minimum number of steps where a step is defined as converting N to (N-1) or converting N to its one of the bigger divisor. Formally, if we are at N, then in 1 step we can reach to (N – 1) or if N = u*v then we can reach to max(u, v) where u > 1 and v > 1. Examples: Input : N = 17 Output : 4 We can reach to 1 in 4 steps as shown below, 17 -> 16(from 17 - 1) -> 4(from 4 * 4) -> 2(from 2 * 2) -> 1(from 2 - 1) Input : N = 50 Output : 5 We can reach to 1 in 5 steps as shown below, 50 -> 10(from 5 * 10) -> 5(from 2 * 5) -> 4(from 5 - 1) -> 2(from 2 *2) -> 1(from 2 - 1) We can solve this problem using breadth first search because it works level by level so we will reach to 1 in minimum number of steps where next level for N contains (N – 1) and bigger proper factors of N. Complete BFS procedure will be as follows, First we will push N with steps 0 into the data queue then at each level we will push their next level elements with 1 step more than its previous level elements. In this way when 1 will be popped out from queue, it will contain minimum number of steps with it, which will be our final result. In below code a queue of a structure of ‘data’ type is used which stores value and steps from N in it, another set of integer type is used to save ourselves from pushing the same element more than once which can lead to an infinite loop. So at each step, we push the value into set after pushing that into the queue so that the value won’t be visited more than once. Please see below code for better understanding, C++ Java C# Javascript // C++ program to get minimum step to reach 1// under given constraints#include <bits/stdc++.h>using namespace std; // structure represent one node in queuestruct data{ int val; int steps; data(int val, int steps) : val(val), steps(steps) {}}; // method returns minimum step to reach oneint minStepToReachOne(int N){ queue<data> q; q.push(data(N, 0)); // set is used to visit numbers so that they // won't be pushed in queue again set<int> st; // loop until we reach to 1 while (!q.empty()) { data t = q.front(); q.pop(); // if current data value is 1, return its // steps from N if (t.val == 1) return t.steps; // check curr - 1, only if it not visited yet if (st.find(t.val - 1) == st.end()) { q.push(data(t.val - 1, t.steps + 1)); st.insert(t.val - 1); } // loop from 2 to sqrt(value) for its divisors for (int i = 2; i*i <= t.val; i++) { // check divisor, only if it is not visited yet // if i is divisor of val, then val / i will // be its bigger divisor if (t.val % i == 0 && st.find(t.val / i) == st.end()) { q.push(data(t.val / i, t.steps + 1)); st.insert(t.val / i); } } }} // Driver code to test above methodsint main(){ int N = 17; cout << minStepToReachOne(N) << endl;} // Java program to get minimum step to reach 1// under given constraintsimport java.util.*; class GFG{ // structure represent one node in queuestatic class data{ int val; int steps; public data(int val, int steps) { this.val = val; this.steps = steps; } }; // method returns minimum step to reach onestatic int minStepToReachOne(int N){ Queue<data> q = new LinkedList<>(); q.add(new data(N, 0)); // set is used to visit numbers so that they // won't be pushed in queue again HashSet<Integer> st = new HashSet<Integer>(); // loop until we reach to 1 while (!q.isEmpty()) { data t = q.peek(); q.remove(); // if current data value is 1, return its // steps from N if (t.val == 1) return t.steps; // check curr - 1, only if it not visited yet if (!st.contains(t.val - 1)) { q.add(new data(t.val - 1, t.steps + 1)); st.add(t.val - 1); } // loop from 2 to Math.sqrt(value) for its divisors for (int i = 2; i*i <= t.val; i++) { // check divisor, only if it is not visited yet // if i is divisor of val, then val / i will // be its bigger divisor if (t.val % i == 0 && !st.contains(t.val / i) ) { q.add(new data(t.val / i, t.steps + 1)); st.add(t.val / i); } } } return -1;} // Driver code public static void main(String[] args){ int N = 17; System.out.print(minStepToReachOne(N) +"\n");}} // This code is contributed by 29AjayKumar // C# program to get minimum step to reach 1// under given constraintsusing System;using System.Collections.Generic; class GFG{ // structure represent one node in queueclass data{ public int val; public int steps; public data(int val, int steps) { this.val = val; this.steps = steps; }}; // method returns minimum step to reach onestatic int minStepToReachOne(int N){ Queue<data> q = new Queue<data>(); q.Enqueue(new data(N, 0)); // set is used to visit numbers so that they // won't be pushed in queue again HashSet<int> st = new HashSet<int>(); // loop until we reach to 1 while (q.Count != 0) { data t = q.Peek(); q.Dequeue(); // if current data value is 1, return its // steps from N if (t.val == 1) return t.steps; // check curr - 1, only if it not visited yet if (!st.Contains(t.val - 1)) { q.Enqueue(new data(t.val - 1, t.steps + 1)); st.Add(t.val - 1); } // loop from 2 to Math.Sqrt(value) for its divisors for (int i = 2; i*i <= t.val; i++) { // check divisor, only if it is not visited yet // if i is divisor of val, then val / i will // be its bigger divisor if (t.val % i == 0 && !st.Contains(t.val / i) ) { q.Enqueue(new data(t.val / i, t.steps + 1)); st.Add(t.val / i); } } } return -1;} // Driver codepublic static void Main(String[] args){ int N = 17; Console.Write(minStepToReachOne(N) +"\n");}} // This code is contributed by 29AjayKumar <script> // Javascript program to get minimum step// to reach 1 under given constraints // Structure represent one node in queueclass data{ constructor(val, steps) { this.val = val; this.steps = steps; }} // Method returns minimum step to reach onefunction minStepToReachOne(N){ let q = []; q.push(new data(N, 0)); // Set is used to visit numbers // so that they won't be pushed // in queue again let st = new Set(); // Loop until we reach to 1 while (q.length != 0) { let t = q.shift(); // If current data value is 1, // return its steps from N if (t.val == 1) return t.steps; // Check curr - 1, only if // it not visited yet if (!st.has(t.val - 1)) { q.push(new data(t.val - 1, t.steps + 1)); st.add(t.val - 1); } // Loop from 2 to Math.sqrt(value) // for its divisors for(let i = 2; i*i <= t.val; i++) { // Check divisor, only if it is not // visited yet if i is divisor of val, // then val / i will be its bigger divisor if (t.val % i == 0 && !st.has(t.val / i)) { q.push(new data(t.val / i, t.steps + 1)); st.add(t.val / i); } } } return -1;} // Driver code let N = 17;document.write(minStepToReachOne(N) + "<br>"); // This code is contributed by rag2127 </script> Output: 4 This article is contributed by Utkarsh Trivedi. 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. 29AjayKumar rag2127 ruhelaa48 BFS Mathematical Mathematical BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25963, "s": 25935, "text": "\n13 Jul, 2021" }, { "code": null, "e": 26139, "s": 25963, "text": "Given a positive number N, we need to reach to 1 in minimum number of steps where a step is defined as converting N to (N-1) or converting N to its one of the bigger divisor. " }, { "code": null, "e": 26273, "s": 26139, "text": "Formally, if we are at N, then in 1 step we can reach to (N – 1) or if N = u*v then we can reach to max(u, v) where u > 1 and v > 1. " }, { "code": null, "e": 26283, "s": 26273, "text": "Examples:" }, { "code": null, "e": 26590, "s": 26283, "text": "Input : N = 17\nOutput : 4\nWe can reach to 1 in 4 steps as shown below,\n17 -> 16(from 17 - 1) -> 4(from 4 * 4) -> \n2(from 2 * 2) -> 1(from 2 - 1)\n\nInput : N = 50\nOutput : 5\nWe can reach to 1 in 5 steps as shown below,\n50 -> 10(from 5 * 10) -> 5(from 2 * 5) -> \n4(from 5 - 1) -> 2(from 2 *2) -> 1(from 2 - 1)" }, { "code": null, "e": 27501, "s": 26590, "text": "We can solve this problem using breadth first search because it works level by level so we will reach to 1 in minimum number of steps where next level for N contains (N – 1) and bigger proper factors of N. Complete BFS procedure will be as follows, First we will push N with steps 0 into the data queue then at each level we will push their next level elements with 1 step more than its previous level elements. In this way when 1 will be popped out from queue, it will contain minimum number of steps with it, which will be our final result. In below code a queue of a structure of ‘data’ type is used which stores value and steps from N in it, another set of integer type is used to save ourselves from pushing the same element more than once which can lead to an infinite loop. So at each step, we push the value into set after pushing that into the queue so that the value won’t be visited more than once. " }, { "code": null, "e": 27551, "s": 27501, "text": "Please see below code for better understanding, " }, { "code": null, "e": 27555, "s": 27551, "text": "C++" }, { "code": null, "e": 27560, "s": 27555, "text": "Java" }, { "code": null, "e": 27563, "s": 27560, "text": "C#" }, { "code": null, "e": 27574, "s": 27563, "text": "Javascript" }, { "code": "// C++ program to get minimum step to reach 1// under given constraints#include <bits/stdc++.h>using namespace std; // structure represent one node in queuestruct data{ int val; int steps; data(int val, int steps) : val(val), steps(steps) {}}; // method returns minimum step to reach oneint minStepToReachOne(int N){ queue<data> q; q.push(data(N, 0)); // set is used to visit numbers so that they // won't be pushed in queue again set<int> st; // loop until we reach to 1 while (!q.empty()) { data t = q.front(); q.pop(); // if current data value is 1, return its // steps from N if (t.val == 1) return t.steps; // check curr - 1, only if it not visited yet if (st.find(t.val - 1) == st.end()) { q.push(data(t.val - 1, t.steps + 1)); st.insert(t.val - 1); } // loop from 2 to sqrt(value) for its divisors for (int i = 2; i*i <= t.val; i++) { // check divisor, only if it is not visited yet // if i is divisor of val, then val / i will // be its bigger divisor if (t.val % i == 0 && st.find(t.val / i) == st.end()) { q.push(data(t.val / i, t.steps + 1)); st.insert(t.val / i); } } }} // Driver code to test above methodsint main(){ int N = 17; cout << minStepToReachOne(N) << endl;}", "e": 29039, "s": 27574, "text": null }, { "code": "// Java program to get minimum step to reach 1// under given constraintsimport java.util.*; class GFG{ // structure represent one node in queuestatic class data{ int val; int steps; public data(int val, int steps) { this.val = val; this.steps = steps; } }; // method returns minimum step to reach onestatic int minStepToReachOne(int N){ Queue<data> q = new LinkedList<>(); q.add(new data(N, 0)); // set is used to visit numbers so that they // won't be pushed in queue again HashSet<Integer> st = new HashSet<Integer>(); // loop until we reach to 1 while (!q.isEmpty()) { data t = q.peek(); q.remove(); // if current data value is 1, return its // steps from N if (t.val == 1) return t.steps; // check curr - 1, only if it not visited yet if (!st.contains(t.val - 1)) { q.add(new data(t.val - 1, t.steps + 1)); st.add(t.val - 1); } // loop from 2 to Math.sqrt(value) for its divisors for (int i = 2; i*i <= t.val; i++) { // check divisor, only if it is not visited yet // if i is divisor of val, then val / i will // be its bigger divisor if (t.val % i == 0 && !st.contains(t.val / i) ) { q.add(new data(t.val / i, t.steps + 1)); st.add(t.val / i); } } } return -1;} // Driver code public static void main(String[] args){ int N = 17; System.out.print(minStepToReachOne(N) +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 30660, "s": 29039, "text": null }, { "code": "// C# program to get minimum step to reach 1// under given constraintsusing System;using System.Collections.Generic; class GFG{ // structure represent one node in queueclass data{ public int val; public int steps; public data(int val, int steps) { this.val = val; this.steps = steps; }}; // method returns minimum step to reach onestatic int minStepToReachOne(int N){ Queue<data> q = new Queue<data>(); q.Enqueue(new data(N, 0)); // set is used to visit numbers so that they // won't be pushed in queue again HashSet<int> st = new HashSet<int>(); // loop until we reach to 1 while (q.Count != 0) { data t = q.Peek(); q.Dequeue(); // if current data value is 1, return its // steps from N if (t.val == 1) return t.steps; // check curr - 1, only if it not visited yet if (!st.Contains(t.val - 1)) { q.Enqueue(new data(t.val - 1, t.steps + 1)); st.Add(t.val - 1); } // loop from 2 to Math.Sqrt(value) for its divisors for (int i = 2; i*i <= t.val; i++) { // check divisor, only if it is not visited yet // if i is divisor of val, then val / i will // be its bigger divisor if (t.val % i == 0 && !st.Contains(t.val / i) ) { q.Enqueue(new data(t.val / i, t.steps + 1)); st.Add(t.val / i); } } } return -1;} // Driver codepublic static void Main(String[] args){ int N = 17; Console.Write(minStepToReachOne(N) +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 32308, "s": 30660, "text": null }, { "code": "<script> // Javascript program to get minimum step// to reach 1 under given constraints // Structure represent one node in queueclass data{ constructor(val, steps) { this.val = val; this.steps = steps; }} // Method returns minimum step to reach onefunction minStepToReachOne(N){ let q = []; q.push(new data(N, 0)); // Set is used to visit numbers // so that they won't be pushed // in queue again let st = new Set(); // Loop until we reach to 1 while (q.length != 0) { let t = q.shift(); // If current data value is 1, // return its steps from N if (t.val == 1) return t.steps; // Check curr - 1, only if // it not visited yet if (!st.has(t.val - 1)) { q.push(new data(t.val - 1, t.steps + 1)); st.add(t.val - 1); } // Loop from 2 to Math.sqrt(value) // for its divisors for(let i = 2; i*i <= t.val; i++) { // Check divisor, only if it is not // visited yet if i is divisor of val, // then val / i will be its bigger divisor if (t.val % i == 0 && !st.has(t.val / i)) { q.push(new data(t.val / i, t.steps + 1)); st.add(t.val / i); } } } return -1;} // Driver code let N = 17;document.write(minStepToReachOne(N) + \"<br>\"); // This code is contributed by rag2127 </script>", "e": 33851, "s": 32308, "text": null }, { "code": null, "e": 33860, "s": 33851, "text": "Output: " }, { "code": null, "e": 33862, "s": 33860, "text": "4" }, { "code": null, "e": 34286, "s": 33862, "text": "This article is contributed by Utkarsh Trivedi. 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": 34298, "s": 34286, "text": "29AjayKumar" }, { "code": null, "e": 34306, "s": 34298, "text": "rag2127" }, { "code": null, "e": 34316, "s": 34306, "text": "ruhelaa48" }, { "code": null, "e": 34320, "s": 34316, "text": "BFS" }, { "code": null, "e": 34333, "s": 34320, "text": "Mathematical" }, { "code": null, "e": 34346, "s": 34333, "text": "Mathematical" }, { "code": null, "e": 34350, "s": 34346, "text": "BFS" }, { "code": null, "e": 34448, "s": 34350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34492, "s": 34448, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34534, "s": 34492, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 34565, "s": 34534, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34636, "s": 34565, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 34661, "s": 34636, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34693, "s": 34661, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34726, "s": 34693, "text": "Program to multiply two matrices" }, { "code": null, "e": 34772, "s": 34726, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 34816, "s": 34772, "text": "Generate all permutation of a set in Python" } ]
Web scraper for extracting emails based on keywords and regions - GeeksforGeeks
29 Dec, 2020 Web scraping is a task that is normally performed to scrape structured data from the websites which are then stored accordingly, this kind of data is valuable enough to open the doors to a variety of fields from data mining-related stuff to the data science related applications where large amounts of data are required to make business decisions. And as for this article, we are going to discuss how to use web scrapers for extracting emails based on keywords and locations. So the question arises, why would we need something like that? Well, emails extracted based on specific topics and regions can be a very productive way of doing advertisement and product promotion, though one would say that this could be used for black hat SEO it actually depends on how you use it. Scrapy module: It is used as a Python framework for web scrapping. Getting data from a normal website is easier, and can be just achieved by just pulling HTML of the website and fetching data by filtering tags. It can be installed using the below command. pip install scrapy Selenium module: It is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc. It can be installed using the below command. pip install selenium Scrapy-Selenium module: It is a scrapy middleware to handle JavaScript pages using selenium. It can be installed using the below command. pip install scrapy-selenium Google module: Using python package google we can get the result of google search from a python script. It can be installed using the below command. pip install google Step 1: Creating scrapy project with the below command: scrapy startproject email_extraction After executing the above command you will see a folder with the tree like this ├── email_extraction │ ├── __init__.py │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── __pycache__ │ ├── settings.py │ └── spiders │ ├── email_extractor.py │ ├── __init__.py │ └── __pycache__ └── scrapy.cfg 4 directories, 8 files Create a python file in the spiders directory and open it up in any editor. Step 2: Importing the required libraries Python3 # import required modulesimport scrapyfrom scrapy.spiders import CrawlSpider, Requestfrom googlesearch import searchimport refrom scrapy_selenium import SeleniumRequestfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC Now the required libraries have been imported we can get to the next step of our script. Step 3: Setting up required parameters for the crawler Python3 # create class to extract email idsclass email_extractor(CrawlSpider): # adjusting parameters name = 'email_ex' def __init__(self, *args, **kwargs): super(email_extractor, self).__init__(*args, **kwargs) self.email_list = [] self.query = " 'market places'.gmail.com " In this we are creating class email_extractor and inheriting CrawlSpider class from the scrapy module, in the next line we are giving a unique name to our crawler which we will use later to run our spider, we don’t need to set allowed domain parameter as we will be jumping from one website domain to the other for extracting emails then we are creating a python constructor and declaring a list and a string variable, the string value given here is going to be fed to the google search engine which is our actual query defining keyword (health), location (usa) and .gmail.com for getting email oriented search results. Step 4: Getting results and sending requests Python3 # sending requests def start_requests(self): for results in search(self.query, num=10, stop=None, pause=2): yield SeleniumRequest( url=results, callback=self.parse, wait_until=EC.presence_of_element_located( (By.TAG_NAME, "html")), dont_filter=True ) Here, we are creating our method start_requests then we are using search() method from googlesearch module with parameters of query variable which has the actual search query that we declared before. 10 results after every 2 seconds of pause. We are getting all the results there exist for the query with the stop parameter set to None. After that, we are yielding a request with the method SeleniumRequest from scrapy_selenium module with parameters of: Getting the first URL sequentially from the search results. Calling back a method for each URL for further processing which we will see in a minute. Using wait_until parameter for checking whether the tag with the name html has appeared on the web page or not, it will keep on checking until it appears on the web page. The don’t_filter set as True will allow the revisiting of the website with the same domain name. Step 5: Extracting emails from the main page of each website Python3 # extracting emailsdef parse(self, response): EMAIL_REGEX = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+' emails = re.finditer(EMAIL_REGEX, str(response.text)) for email in emails: self.email_list.append(email.group()) for email in set(self.email_list): yield{ "emails": email } self.email_list.clear() In this step we are creating a method called parse() with the parameter response for getting request object from the start_request method, in the next line we are creating our regular expression system for parsing out the emails from the response HTML then we are appending the emails in the email_list list variable which we declared in the constructor method, and then we are iterating over the set and yielding a dictionary where emails is key or column header and email is an iterator or relative email value and at the very last we are clearing the list so that no duplicate values are written to the file when we start the crawler. Below is the complete program based on the above approach: Python3 # import required modulesimport scrapyfrom scrapy.spiders import CrawlSpider, Requestfrom googlesearch import searchimport refrom scrapy_selenium import SeleniumRequestfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC # create class to extract email idsclass email_extractor(CrawlSpider): # adjusting parameters name = 'email_ex' def __init__(self, *args, **kwargs): super(email_extractor, self).__init__(*args, **kwargs) self.email_list = [] self.query = " 'market places'.gmail.com " # sending requests def start_requests(self): for results in search(self.query, num=10, stop=None, pause=2): yield SeleniumRequest( url=results, callback=self.parse, wait_until=EC.presence_of_element_located( (By.TAG_NAME, "html")), dont_filter=True ) # extracting emails def parse(self, response): EMAIL_REGEX = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+' emails = re.finditer(EMAIL_REGEX, str(response.text)) for email in emails: self.email_list.append(email.group()) for email in set(self.email_list): yield{ "emails": email } self.email_list.clear() Now it’s time to run the code, open the terminal and go to the root directory of the project where scrapy.cfg file is located and run this command: scrapy crawl email_ex -o emails.csv Scraper will start scraping and storing all the emails to the file emails.csv that is created automatically. And so the results are: Extracted emails are stored in a csv file ahmadwaqar Python web-scraping-exercises Python-projects Python-selenium python-utility Technical Scripter 2020 Web-scraping Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n29 Dec, 2020" }, { "code": null, "e": 25909, "s": 25561, "text": "Web scraping is a task that is normally performed to scrape structured data from the websites which are then stored accordingly, this kind of data is valuable enough to open the doors to a variety of fields from data mining-related stuff to the data science related applications where large amounts of data are required to make business decisions." }, { "code": null, "e": 26037, "s": 25909, "text": "And as for this article, we are going to discuss how to use web scrapers for extracting emails based on keywords and locations." }, { "code": null, "e": 26337, "s": 26037, "text": "So the question arises, why would we need something like that? Well, emails extracted based on specific topics and regions can be a very productive way of doing advertisement and product promotion, though one would say that this could be used for black hat SEO it actually depends on how you use it." }, { "code": null, "e": 26593, "s": 26337, "text": "Scrapy module: It is used as a Python framework for web scrapping. Getting data from a normal website is easier, and can be just achieved by just pulling HTML of the website and fetching data by filtering tags. It can be installed using the below command." }, { "code": null, "e": 26612, "s": 26593, "text": "pip install scrapy" }, { "code": null, "e": 26880, "s": 26612, "text": "Selenium module: It is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc. It can be installed using the below command." }, { "code": null, "e": 26901, "s": 26880, "text": "pip install selenium" }, { "code": null, "e": 27039, "s": 26901, "text": "Scrapy-Selenium module: It is a scrapy middleware to handle JavaScript pages using selenium. It can be installed using the below command." }, { "code": null, "e": 27067, "s": 27039, "text": "pip install scrapy-selenium" }, { "code": null, "e": 27216, "s": 27067, "text": "Google module: Using python package google we can get the result of google search from a python script. It can be installed using the below command." }, { "code": null, "e": 27235, "s": 27216, "text": "pip install google" }, { "code": null, "e": 27292, "s": 27235, "text": "Step 1: Creating scrapy project with the below command: " }, { "code": null, "e": 27329, "s": 27292, "text": "scrapy startproject email_extraction" }, { "code": null, "e": 27410, "s": 27329, "text": "After executing the above command you will see a folder with the tree like this " }, { "code": null, "e": 27686, "s": 27410, "text": "├── email_extraction\n│ ├── __init__.py\n│ ├── items.py\n│ ├── middlewares.py\n│ ├── pipelines.py\n│ ├── __pycache__\n│ ├── settings.py\n│ └── spiders\n│ ├── email_extractor.py\n│ ├── __init__.py\n│ └── __pycache__\n└── scrapy.cfg\n\n4 directories, 8 files" }, { "code": null, "e": 27762, "s": 27686, "text": "Create a python file in the spiders directory and open it up in any editor." }, { "code": null, "e": 27805, "s": 27762, "text": "Step 2: Importing the required libraries " }, { "code": null, "e": 27813, "s": 27805, "text": "Python3" }, { "code": "# import required modulesimport scrapyfrom scrapy.spiders import CrawlSpider, Requestfrom googlesearch import searchimport refrom scrapy_selenium import SeleniumRequestfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC", "e": 28089, "s": 27813, "text": null }, { "code": null, "e": 28180, "s": 28089, "text": " Now the required libraries have been imported we can get to the next step of our script." }, { "code": null, "e": 28237, "s": 28180, "text": " Step 3: Setting up required parameters for the crawler " }, { "code": null, "e": 28245, "s": 28237, "text": "Python3" }, { "code": "# create class to extract email idsclass email_extractor(CrawlSpider): # adjusting parameters name = 'email_ex' def __init__(self, *args, **kwargs): super(email_extractor, self).__init__(*args, **kwargs) self.email_list = [] self.query = \" 'market places'.gmail.com \"", "e": 28549, "s": 28245, "text": null }, { "code": null, "e": 29171, "s": 28549, "text": " In this we are creating class email_extractor and inheriting CrawlSpider class from the scrapy module, in the next line we are giving a unique name to our crawler which we will use later to run our spider, we don’t need to set allowed domain parameter as we will be jumping from one website domain to the other for extracting emails then we are creating a python constructor and declaring a list and a string variable, the string value given here is going to be fed to the google search engine which is our actual query defining keyword (health), location (usa) and .gmail.com for getting email oriented search results." }, { "code": null, "e": 29218, "s": 29171, "text": " Step 4: Getting results and sending requests " }, { "code": null, "e": 29226, "s": 29218, "text": "Python3" }, { "code": "# sending requests def start_requests(self): for results in search(self.query, num=10, stop=None, pause=2): yield SeleniumRequest( url=results, callback=self.parse, wait_until=EC.presence_of_element_located( (By.TAG_NAME, \"html\")), dont_filter=True )", "e": 29588, "s": 29226, "text": null }, { "code": null, "e": 29718, "s": 29588, "text": " Here, we are creating our method start_requests then we are using search() method from googlesearch module with parameters of " }, { "code": null, "e": 29792, "s": 29718, "text": "query variable which has the actual search query that we declared before." }, { "code": null, "e": 29835, "s": 29792, "text": "10 results after every 2 seconds of pause." }, { "code": null, "e": 29929, "s": 29835, "text": "We are getting all the results there exist for the query with the stop parameter set to None." }, { "code": null, "e": 30050, "s": 29929, "text": "After that, we are yielding a request with the method SeleniumRequest from scrapy_selenium module with parameters of: " }, { "code": null, "e": 30110, "s": 30050, "text": "Getting the first URL sequentially from the search results." }, { "code": null, "e": 30199, "s": 30110, "text": "Calling back a method for each URL for further processing which we will see in a minute." }, { "code": null, "e": 30370, "s": 30199, "text": "Using wait_until parameter for checking whether the tag with the name html has appeared on the web page or not, it will keep on checking until it appears on the web page." }, { "code": null, "e": 30467, "s": 30370, "text": "The don’t_filter set as True will allow the revisiting of the website with the same domain name." }, { "code": null, "e": 30529, "s": 30467, "text": "Step 5: Extracting emails from the main page of each website " }, { "code": null, "e": 30537, "s": 30529, "text": "Python3" }, { "code": "# extracting emailsdef parse(self, response): EMAIL_REGEX = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+' emails = re.finditer(EMAIL_REGEX, str(response.text)) for email in emails: self.email_list.append(email.group()) for email in set(self.email_list): yield{ \"emails\": email } self.email_list.clear()", "e": 30893, "s": 30537, "text": null }, { "code": null, "e": 31533, "s": 30893, "text": " In this step we are creating a method called parse() with the parameter response for getting request object from the start_request method, in the next line we are creating our regular expression system for parsing out the emails from the response HTML then we are appending the emails in the email_list list variable which we declared in the constructor method, and then we are iterating over the set and yielding a dictionary where emails is key or column header and email is an iterator or relative email value and at the very last we are clearing the list so that no duplicate values are written to the file when we start the crawler." }, { "code": null, "e": 31593, "s": 31533, "text": "Below is the complete program based on the above approach: " }, { "code": null, "e": 31601, "s": 31593, "text": "Python3" }, { "code": "# import required modulesimport scrapyfrom scrapy.spiders import CrawlSpider, Requestfrom googlesearch import searchimport refrom scrapy_selenium import SeleniumRequestfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC # create class to extract email idsclass email_extractor(CrawlSpider): # adjusting parameters name = 'email_ex' def __init__(self, *args, **kwargs): super(email_extractor, self).__init__(*args, **kwargs) self.email_list = [] self.query = \" 'market places'.gmail.com \" # sending requests def start_requests(self): for results in search(self.query, num=10, stop=None, pause=2): yield SeleniumRequest( url=results, callback=self.parse, wait_until=EC.presence_of_element_located( (By.TAG_NAME, \"html\")), dont_filter=True ) # extracting emails def parse(self, response): EMAIL_REGEX = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+' emails = re.finditer(EMAIL_REGEX, str(response.text)) for email in emails: self.email_list.append(email.group()) for email in set(self.email_list): yield{ \"emails\": email } self.email_list.clear()", "e": 32948, "s": 31601, "text": null }, { "code": null, "e": 33096, "s": 32948, "text": "Now it’s time to run the code, open the terminal and go to the root directory of the project where scrapy.cfg file is located and run this command:" }, { "code": null, "e": 33132, "s": 33096, "text": "scrapy crawl email_ex -o emails.csv" }, { "code": null, "e": 33241, "s": 33132, "text": "Scraper will start scraping and storing all the emails to the file emails.csv that is created automatically." }, { "code": null, "e": 33265, "s": 33241, "text": "And so the results are:" }, { "code": null, "e": 33308, "s": 33265, "text": "Extracted emails are stored in a csv file " }, { "code": null, "e": 33319, "s": 33308, "text": "ahmadwaqar" }, { "code": null, "e": 33349, "s": 33319, "text": "Python web-scraping-exercises" }, { "code": null, "e": 33365, "s": 33349, "text": "Python-projects" }, { "code": null, "e": 33381, "s": 33365, "text": "Python-selenium" }, { "code": null, "e": 33396, "s": 33381, "text": "python-utility" }, { "code": null, "e": 33420, "s": 33396, "text": "Technical Scripter 2020" }, { "code": null, "e": 33433, "s": 33420, "text": "Web-scraping" }, { "code": null, "e": 33440, "s": 33433, "text": "Python" }, { "code": null, "e": 33459, "s": 33440, "text": "Technical Scripter" }, { "code": null, "e": 33557, "s": 33459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33589, "s": 33557, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33631, "s": 33589, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33673, "s": 33631, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33700, "s": 33673, "text": "Python Classes and Objects" }, { "code": null, "e": 33756, "s": 33700, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33778, "s": 33756, "text": "Defaultdict in Python" }, { "code": null, "e": 33817, "s": 33778, "text": "Python | Get unique values from a list" }, { "code": null, "e": 33848, "s": 33817, "text": "Python | os.path.join() method" }, { "code": null, "e": 33877, "s": 33848, "text": "Create a directory in Python" } ]
Create Local Binary Pattern of an image using OpenCV-Python - GeeksforGeeks
06 Mar, 2020 In this article, we will discuss the image and how to find a binary pattern using the pixel value of the image. As we all know, image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. As we can see in following example: import cv2image = cv2.imread("GFG.jpg") # Now, the variable 'image' stores the pixel values of imageprint(image) Examples: Input :Output : [[[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]] [[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]] [[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]] ... [[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]] [[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]] [[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]]] Pixel values of the image will be stored in the variable and below is a part of the NumPy array which stores the values. There are lots of different types of texture descriptors are used to extract features of an image. Local Binary Pattern, also known as LBP, is a simple and grey-scale invariant texture descriptor measure for classification. In LBP, a binary code is generated at each pixel by thresholding it’s neighbourhood pixels to either 0 or 1 based on the value of the centre pixel. The rule for finding LBP of an image is as follows: Set a pixel value as center pixel.Collect its neighbourhood pixels (Here I am taking a 3 x 3 matrix so; total number of neighbourhood pixel is 8)Threshold it’s neighbourhood pixel value to 1 if its value is greater than or equal to centre pixel value otherwise threshold it to 0.After thresholding, collect all threshold values from neighbourhood either clockwise or anti-clockwise. The collection will give you an 8-digit binary code. Convert the binary code into decimal.Replace the center pixel value with resulted decimal and do the same process for all pixel values present in image. Set a pixel value as center pixel. Collect its neighbourhood pixels (Here I am taking a 3 x 3 matrix so; total number of neighbourhood pixel is 8) Threshold it’s neighbourhood pixel value to 1 if its value is greater than or equal to centre pixel value otherwise threshold it to 0. After thresholding, collect all threshold values from neighbourhood either clockwise or anti-clockwise. The collection will give you an 8-digit binary code. Convert the binary code into decimal. Replace the center pixel value with resulted decimal and do the same process for all pixel values present in image. Let’s take an example to understand it properly. Let’s take a pixel value from the above output to find its binary pattern from its local neighbourhood. So, I am taking a value ‘149’ (present at 15th row and 19nd column) and its 8 neighbourhood pixels to form a 3 x 3 matrix. Collect the thresholding values either clockwise or anti-clockwise. Here, I am collecting them clockwise from top-left. So, after collecting, the binary value will be as follows: Then, convert the binary code into decimal and place it at center of matrix. 1 x 27 + 1 x 26 + 1 x 25 + 0 x 24 + 0 x 23 + 0 x 22 + 0 x 21 +1 x 20 = 128 + 64 + 32 + 0 + 0 + 0 + 0 + 1 = 225 Now, the resulted matrix will look like, Now, let’s do it using python import cv2import numpy as npfrom matplotlib import pyplot as plt def get_pixel(img, center, x, y): new_value = 0 try: # If local neighbourhood pixel # value is greater than or equal # to center pixel values then # set it to 1 if img[x][y] >= center: new_value = 1 except: # Exception is required when # neighbourhood value of a center # pixel value is null i.e. values # present at boundaries. pass return new_value # Function for calculating LBPdef lbp_calculated_pixel(img, x, y): center = img[x][y] val_ar = [] # top_left val_ar.append(get_pixel(img, center, x-1, y-1)) # top val_ar.append(get_pixel(img, center, x-1, y)) # top_right val_ar.append(get_pixel(img, center, x-1, y + 1)) # right val_ar.append(get_pixel(img, center, x, y + 1)) # bottom_right val_ar.append(get_pixel(img, center, x + 1, y + 1)) # bottom val_ar.append(get_pixel(img, center, x + 1, y)) # bottom_left val_ar.append(get_pixel(img, center, x + 1, y-1)) # left val_ar.append(get_pixel(img, center, x, y-1)) # Now, we need to convert binary # values to decimal power_val = [1, 2, 4, 8, 16, 32, 64, 128] val = 0 for i in range(len(val_ar)): val += val_ar[i] * power_val[i] return val path = 'GFG.png'img_bgr = cv2.imread(path, 1) height, width, _ = img_bgr.shape # We need to convert RGB image # into gray one because gray # image has one channel only.img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # Create a numpy array as # the same height and width # of RGB imageimg_lbp = np.zeros((height, width), np.uint8) for i in range(0, height): for j in range(0, width): img_lbp[i, j] = lbp_calculated_pixel(img_gray, i, j) plt.imshow(img_bgr)plt.show() plt.imshow(img_lbp, cmap ="gray")plt.show() print("LBP Program is finished") Output: The output shown in examples contains some values in its X-axis and Y-axis which refers to the width and height of the input image respectively. Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 25807, "s": 25779, "text": "\n06 Mar, 2020" }, { "code": null, "e": 25919, "s": 25807, "text": "In this article, we will discuss the image and how to find a binary pattern using the pixel value of the image." }, { "code": null, "e": 26184, "s": 25919, "text": "As we all know, image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image." }, { "code": null, "e": 26220, "s": 26184, "text": "As we can see in following example:" }, { "code": "import cv2image = cv2.imread(\"GFG.jpg\") # Now, the variable 'image' stores the pixel values of imageprint(image)", "e": 26334, "s": 26220, "text": null }, { "code": null, "e": 26344, "s": 26334, "text": "Examples:" }, { "code": null, "e": 26360, "s": 26344, "text": "Input :Output :" }, { "code": null, "e": 26990, "s": 26360, "text": "[[[255 255 255]\n [255 255 255]\n [255 255 255]\n ...\n [255 255 255]\n [255 255 255]\n [255 255 255]]\n\n [[255 255 255]\n [255 255 255]\n [255 255 255]\n ...\n [255 255 255]\n [255 255 255]\n [255 255 255]]\n\n [[255 255 255]\n [255 255 255]\n [255 255 255]\n ...\n [255 255 255]\n [255 255 255]\n [255 255 255]]\n\n ...\n\n [[255 255 255]\n [255 255 255]\n [255 255 255]\n ...\n [255 255 255]\n [255 255 255]\n [255 255 255]]\n\n [[255 255 255]\n [255 255 255]\n [255 255 255]\n ...\n [255 255 255]\n [255 255 255]\n [255 255 255]]\n\n [[255 255 255]\n [255 255 255]\n [255 255 255]\n ...\n [255 255 255]\n [255 255 255]\n [255 255 255]]]" }, { "code": null, "e": 27111, "s": 26990, "text": "Pixel values of the image will be stored in the variable and below is a part of the NumPy array which stores the values." }, { "code": null, "e": 27483, "s": 27111, "text": "There are lots of different types of texture descriptors are used to extract features of an image. Local Binary Pattern, also known as LBP, is a simple and grey-scale invariant texture descriptor measure for classification. In LBP, a binary code is generated at each pixel by thresholding it’s neighbourhood pixels to either 0 or 1 based on the value of the centre pixel." }, { "code": null, "e": 27535, "s": 27483, "text": "The rule for finding LBP of an image is as follows:" }, { "code": null, "e": 28124, "s": 27535, "text": "Set a pixel value as center pixel.Collect its neighbourhood pixels (Here I am taking a 3 x 3 matrix so; total number of neighbourhood pixel is 8)Threshold it’s neighbourhood pixel value to 1 if its value is greater than or equal to centre pixel value otherwise threshold it to 0.After thresholding, collect all threshold values from neighbourhood either clockwise or anti-clockwise. The collection will give you an 8-digit binary code. Convert the binary code into decimal.Replace the center pixel value with resulted decimal and do the same process for all pixel values present in image." }, { "code": null, "e": 28159, "s": 28124, "text": "Set a pixel value as center pixel." }, { "code": null, "e": 28271, "s": 28159, "text": "Collect its neighbourhood pixels (Here I am taking a 3 x 3 matrix so; total number of neighbourhood pixel is 8)" }, { "code": null, "e": 28406, "s": 28271, "text": "Threshold it’s neighbourhood pixel value to 1 if its value is greater than or equal to centre pixel value otherwise threshold it to 0." }, { "code": null, "e": 28601, "s": 28406, "text": "After thresholding, collect all threshold values from neighbourhood either clockwise or anti-clockwise. The collection will give you an 8-digit binary code. Convert the binary code into decimal." }, { "code": null, "e": 28717, "s": 28601, "text": "Replace the center pixel value with resulted decimal and do the same process for all pixel values present in image." }, { "code": null, "e": 28766, "s": 28717, "text": "Let’s take an example to understand it properly." }, { "code": null, "e": 28993, "s": 28766, "text": "Let’s take a pixel value from the above output to find its binary pattern from its local neighbourhood. So, I am taking a value ‘149’ (present at 15th row and 19nd column) and its 8 neighbourhood pixels to form a 3 x 3 matrix." }, { "code": null, "e": 29172, "s": 28993, "text": "Collect the thresholding values either clockwise or anti-clockwise. Here, I am collecting them clockwise from top-left. So, after collecting, the binary value will be as follows:" }, { "code": null, "e": 29249, "s": 29172, "text": "Then, convert the binary code into decimal and place it at center of matrix." }, { "code": null, "e": 29361, "s": 29249, "text": "1 x 27 + 1 x 26 + 1 x 25 + 0 x 24 + 0 x 23 + 0 x 22 + 0 x 21 +1 x 20 \n= 128 + 64 + 32 + 0 + 0 + 0 + 0 + 1\n= 225" }, { "code": null, "e": 29402, "s": 29361, "text": "Now, the resulted matrix will look like," }, { "code": null, "e": 29432, "s": 29402, "text": "Now, let’s do it using python" }, { "code": "import cv2import numpy as npfrom matplotlib import pyplot as plt def get_pixel(img, center, x, y): new_value = 0 try: # If local neighbourhood pixel # value is greater than or equal # to center pixel values then # set it to 1 if img[x][y] >= center: new_value = 1 except: # Exception is required when # neighbourhood value of a center # pixel value is null i.e. values # present at boundaries. pass return new_value # Function for calculating LBPdef lbp_calculated_pixel(img, x, y): center = img[x][y] val_ar = [] # top_left val_ar.append(get_pixel(img, center, x-1, y-1)) # top val_ar.append(get_pixel(img, center, x-1, y)) # top_right val_ar.append(get_pixel(img, center, x-1, y + 1)) # right val_ar.append(get_pixel(img, center, x, y + 1)) # bottom_right val_ar.append(get_pixel(img, center, x + 1, y + 1)) # bottom val_ar.append(get_pixel(img, center, x + 1, y)) # bottom_left val_ar.append(get_pixel(img, center, x + 1, y-1)) # left val_ar.append(get_pixel(img, center, x, y-1)) # Now, we need to convert binary # values to decimal power_val = [1, 2, 4, 8, 16, 32, 64, 128] val = 0 for i in range(len(val_ar)): val += val_ar[i] * power_val[i] return val path = 'GFG.png'img_bgr = cv2.imread(path, 1) height, width, _ = img_bgr.shape # We need to convert RGB image # into gray one because gray # image has one channel only.img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # Create a numpy array as # the same height and width # of RGB imageimg_lbp = np.zeros((height, width), np.uint8) for i in range(0, height): for j in range(0, width): img_lbp[i, j] = lbp_calculated_pixel(img_gray, i, j) plt.imshow(img_bgr)plt.show() plt.imshow(img_lbp, cmap =\"gray\")plt.show() print(\"LBP Program is finished\")", "e": 31502, "s": 29432, "text": null }, { "code": null, "e": 31510, "s": 31502, "text": "Output:" }, { "code": null, "e": 31655, "s": 31510, "text": "The output shown in examples contains some values in its X-axis and Y-axis which refers to the width and height of the input image respectively." }, { "code": null, "e": 31669, "s": 31655, "text": "Python-OpenCV" }, { "code": null, "e": 31676, "s": 31669, "text": "Python" }, { "code": null, "e": 31774, "s": 31676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31792, "s": 31774, "text": "Python Dictionary" }, { "code": null, "e": 31824, "s": 31792, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31846, "s": 31824, "text": "Enumerate() in Python" }, { "code": null, "e": 31888, "s": 31846, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31918, "s": 31888, "text": "Iterate over a list in Python" }, { "code": null, "e": 31944, "s": 31918, "text": "Python String | replace()" }, { "code": null, "e": 31973, "s": 31944, "text": "*args and **kwargs in Python" }, { "code": null, "e": 32017, "s": 31973, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 32054, "s": 32017, "text": "Create a Pandas DataFrame from Lists" } ]
Efficient search in an array where difference between adjacent is 1 - GeeksforGeeks
26 Mar, 2021 Given an array of n integers. Each array element is obtained by adding either +1 or -1 to previous element i.e absolute difference between any two consecutive elements is 1. The task is to search an element index with the minimum number of comparison (less than simple element by element search). If the element is present multiple time, then print the smallest index. If the element is not present print -1.Examples: Input : arr[] = {5, 4, 5, 6, 5, 4, 3, 2} x = 4. Output : 1 The first occurrence of element x is at index 1. Input : arr[] = { 5, 4, 5, 6, 4, 3, 2, 3 } x = 9. Output : -1 Element x is not present in arr[] Let element to be search is x. At any index i, if arr[i] != x, the possibility of x to be present is at location i + abs(arr[i] – a), since each element is obtained by adding either +1 or -1 to the previous element. There is no possibility of having el between i and i + abs(arr[i] – a). So directly jump to i + abs(arr[i] – a), if arr[i] != x. Algorithm to solve the problem: 1. Start from index = 0. 2. Compare arr[index] and x. a) If both are equal, return index. b) If not, set index = index + abs(arr[index] - x). 3. Repeat step 2. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // C++ program to search an element in an array// where each element is obtained by adding// either +1 or -1 to previous element.#include<bits/stdc++.h>using namespace std; // Return the index of the element to be searched.int search(int arr[], int n, int x){ // Searching x in arr[0..n-1] int i = 0; while (i <= n-1) { // Checking if element is found. if (arr[i] == x) return i; // Else jumping to abs(arr[i]-x). i += abs(arr[i]-x); } return -1;} // Driven Programint main(){ int arr[] = {5, 4, 5, 6, 5, 4, 3, 2}; int n = sizeof(arr)/sizeof(arr[0]); int x = 4; cout << search(arr, n, x) << endl; return 0;} // Java program to search an element// in an array where each element is// obtained by adding either +1 or// -1 to previous element.class GFG{ // Return the index of the// element to be searched.static int search(int arr[], int n, int x){ // Searching x in arr[0..n-1] int i = 0; while (i <= n-1) { // Checking if element is found. if (arr[i] == x) return i; // Else jumping to abs(arr[i]-x). i += Math.abs(arr[i]-x); } return -1;} // Driver codepublic static void main (String[] args){ int arr[] = {5, 4, 5, 6, 5, 4, 3, 2}; int n = arr.length; int x = 4; System.out.println(search(arr, n, x));}} // This code is contributed by Anant Agarwal. # Python program to search an element in# an array where each element is obtained# by adding either +1 or -1 to previous element # Return the index of the element to be searcheddef search(arr, n, x): # Searching x in arr[0..n-1] i = 0 while (i <= n-1): # Checking if element is found. if (arr[i] == x): return i # Else jumping to abs(arr[i]-x). i += abs(arr[i] - x) return -1 # Driver codearr = [5, 4, 5, 6, 5, 4, 3, 2]n = len(arr)x = 4 print(search(arr, n, x)) # This code is contributed by Anant Agarwal. // C# program to search an element in// an array where each element is// obtained by adding either + 1 or// -1 to previous element.using System; class GFG{ // Return the index of the// element to be searched.static int search(int []arr, int n, int x){ // Searching x in arr[0.. n - 1] int i = 0; while (i <= n - 1) { // Checking if element is found if (arr[i] == x) return i; // Else jumping to abs(arr[i] - x) i += Math.Abs(arr[i] - x); } return -1;} // Driver codepublic static void Main (){ int []arr = {5, 4, 5, 6, 5, 4, 3, 2}; int n = arr.Length; int x = 4; Console.WriteLine(search(arr, n, x));}} // This code is contributed by vt_m. <?php// PHP program to search an// element in an array where// each element is obtained// by adding either +1 or -1// to previous element. // Return the index of the// element to be searched.function search($arr, $n, $x){ // Searching x in arr[0..n-1] $i = 0; while ($i <= $n-1) { // Checking if element // is found. if ($arr[$i] == $x) return $i; // Else jumping to // abs(arr[i]-x). $i += abs($arr[$i] - $x); } return -1;} // Driver Code $arr= array(5, 4, 5, 6, 5, 4, 3, 2); $n = sizeof($arr); $x = 4; echo search($arr, $n, $x) ; // This code is contributed by nitin mittal.?> <script> // JavaScript program to search an element// in an array where each element is// obtained by adding either +1 or// -1 to previous element. // Return the index of the// element to be searched.function search(arr, n, x){ // Searching x in arr[0..n-1] let i = 0; while (i <= n-1) { // Checking if element is found. if (arr[i] == x) return i; // Else jumping to abs(arr[i]-x). i += Math.abs(arr[i]-x); } return -1;} // Driver code let arr = [5, 4, 5, 6, 5, 4, 3, 2]; let n = arr.length; let x = 4; document.write(search(arr, n, x)); </script> Output: 1 This article is contributed by Anuj Chauhan. 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. vt_m nitin mittal chinmoy1997pal Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Search an element in a sorted and rotated array Program to find largest element in an array k largest(or smallest) elements in an array Given an array of size n and a number k, find all elements that appear more than n/k times Median of two sorted arrays of different sizes Find the index of an array element in Java Two Pointers Technique Most frequent element in an array Best First Search (Informed Search) Find the smallest and second smallest elements in an array
[ { "code": null, "e": 26783, "s": 26755, "text": "\n26 Mar, 2021" }, { "code": null, "e": 27203, "s": 26783, "text": "Given an array of n integers. Each array element is obtained by adding either +1 or -1 to previous element i.e absolute difference between any two consecutive elements is 1. The task is to search an element index with the minimum number of comparison (less than simple element by element search). If the element is present multiple time, then print the smallest index. If the element is not present print -1.Examples: " }, { "code": null, "e": 27427, "s": 27203, "text": "Input : arr[] = {5, 4, 5, 6, 5, 4, 3, 2} \n x = 4.\nOutput : 1\nThe first occurrence of element x is at \nindex 1.\n\nInput : arr[] = { 5, 4, 5, 6, 4, 3, 2, 3 } \n x = 9.\nOutput : -1\nElement x is not present in arr[]" }, { "code": null, "e": 27775, "s": 27429, "text": "Let element to be search is x. At any index i, if arr[i] != x, the possibility of x to be present is at location i + abs(arr[i] – a), since each element is obtained by adding either +1 or -1 to the previous element. There is no possibility of having el between i and i + abs(arr[i] – a). So directly jump to i + abs(arr[i] – a), if arr[i] != x. " }, { "code": null, "e": 27973, "s": 27775, "text": "Algorithm to solve the problem:\n1. Start from index = 0.\n2. Compare arr[index] and x.\n a) If both are equal, return index.\n b) If not, set index = index + abs(arr[index] - x).\n3. Repeat step 2." }, { "code": null, "e": 28019, "s": 27973, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 28023, "s": 28019, "text": "C++" }, { "code": null, "e": 28028, "s": 28023, "text": "Java" }, { "code": null, "e": 28036, "s": 28028, "text": "Python3" }, { "code": null, "e": 28039, "s": 28036, "text": "C#" }, { "code": null, "e": 28043, "s": 28039, "text": "PHP" }, { "code": null, "e": 28054, "s": 28043, "text": "Javascript" }, { "code": "// C++ program to search an element in an array// where each element is obtained by adding// either +1 or -1 to previous element.#include<bits/stdc++.h>using namespace std; // Return the index of the element to be searched.int search(int arr[], int n, int x){ // Searching x in arr[0..n-1] int i = 0; while (i <= n-1) { // Checking if element is found. if (arr[i] == x) return i; // Else jumping to abs(arr[i]-x). i += abs(arr[i]-x); } return -1;} // Driven Programint main(){ int arr[] = {5, 4, 5, 6, 5, 4, 3, 2}; int n = sizeof(arr)/sizeof(arr[0]); int x = 4; cout << search(arr, n, x) << endl; return 0;}", "e": 28739, "s": 28054, "text": null }, { "code": "// Java program to search an element// in an array where each element is// obtained by adding either +1 or// -1 to previous element.class GFG{ // Return the index of the// element to be searched.static int search(int arr[], int n, int x){ // Searching x in arr[0..n-1] int i = 0; while (i <= n-1) { // Checking if element is found. if (arr[i] == x) return i; // Else jumping to abs(arr[i]-x). i += Math.abs(arr[i]-x); } return -1;} // Driver codepublic static void main (String[] args){ int arr[] = {5, 4, 5, 6, 5, 4, 3, 2}; int n = arr.length; int x = 4; System.out.println(search(arr, n, x));}} // This code is contributed by Anant Agarwal.", "e": 29458, "s": 28739, "text": null }, { "code": "# Python program to search an element in# an array where each element is obtained# by adding either +1 or -1 to previous element # Return the index of the element to be searcheddef search(arr, n, x): # Searching x in arr[0..n-1] i = 0 while (i <= n-1): # Checking if element is found. if (arr[i] == x): return i # Else jumping to abs(arr[i]-x). i += abs(arr[i] - x) return -1 # Driver codearr = [5, 4, 5, 6, 5, 4, 3, 2]n = len(arr)x = 4 print(search(arr, n, x)) # This code is contributed by Anant Agarwal.", "e": 30028, "s": 29458, "text": null }, { "code": "// C# program to search an element in// an array where each element is// obtained by adding either + 1 or// -1 to previous element.using System; class GFG{ // Return the index of the// element to be searched.static int search(int []arr, int n, int x){ // Searching x in arr[0.. n - 1] int i = 0; while (i <= n - 1) { // Checking if element is found if (arr[i] == x) return i; // Else jumping to abs(arr[i] - x) i += Math.Abs(arr[i] - x); } return -1;} // Driver codepublic static void Main (){ int []arr = {5, 4, 5, 6, 5, 4, 3, 2}; int n = arr.Length; int x = 4; Console.WriteLine(search(arr, n, x));}} // This code is contributed by vt_m.", "e": 30766, "s": 30028, "text": null }, { "code": "<?php// PHP program to search an// element in an array where// each element is obtained// by adding either +1 or -1// to previous element. // Return the index of the// element to be searched.function search($arr, $n, $x){ // Searching x in arr[0..n-1] $i = 0; while ($i <= $n-1) { // Checking if element // is found. if ($arr[$i] == $x) return $i; // Else jumping to // abs(arr[i]-x). $i += abs($arr[$i] - $x); } return -1;} // Driver Code $arr= array(5, 4, 5, 6, 5, 4, 3, 2); $n = sizeof($arr); $x = 4; echo search($arr, $n, $x) ; // This code is contributed by nitin mittal.?>", "e": 31449, "s": 30766, "text": null }, { "code": "<script> // JavaScript program to search an element// in an array where each element is// obtained by adding either +1 or// -1 to previous element. // Return the index of the// element to be searched.function search(arr, n, x){ // Searching x in arr[0..n-1] let i = 0; while (i <= n-1) { // Checking if element is found. if (arr[i] == x) return i; // Else jumping to abs(arr[i]-x). i += Math.abs(arr[i]-x); } return -1;} // Driver code let arr = [5, 4, 5, 6, 5, 4, 3, 2]; let n = arr.length; let x = 4; document.write(search(arr, n, x)); </script>", "e": 32076, "s": 31449, "text": null }, { "code": null, "e": 32085, "s": 32076, "text": "Output: " }, { "code": null, "e": 32087, "s": 32085, "text": "1" }, { "code": null, "e": 32512, "s": 32087, "text": "This article is contributed by Anuj Chauhan. 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. " }, { "code": null, "e": 32517, "s": 32512, "text": "vt_m" }, { "code": null, "e": 32530, "s": 32517, "text": "nitin mittal" }, { "code": null, "e": 32545, "s": 32530, "text": "chinmoy1997pal" }, { "code": null, "e": 32555, "s": 32545, "text": "Searching" }, { "code": null, "e": 32565, "s": 32555, "text": "Searching" }, { "code": null, "e": 32663, "s": 32565, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32711, "s": 32663, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 32755, "s": 32711, "text": "Program to find largest element in an array" }, { "code": null, "e": 32799, "s": 32755, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 32890, "s": 32799, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 32937, "s": 32890, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 32980, "s": 32937, "text": "Find the index of an array element in Java" }, { "code": null, "e": 33003, "s": 32980, "text": "Two Pointers Technique" }, { "code": null, "e": 33037, "s": 33003, "text": "Most frequent element in an array" }, { "code": null, "e": 33073, "s": 33037, "text": "Best First Search (Informed Search)" } ]
Bash program to check if the Number is a Prime or not - GeeksforGeeks
30 Sep, 2019 Given a number, the task is to find whether the given number is prime or not using Bash Scripting. Examples: Input: N = 43 Output: Prime Input: N = 35 Output: Not Prime Prime Numbers:A prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 ..... Approach:We run a loop from 2 to number/2 and check if there is any factor of the number. If we find any factor then the number is composite otherwise prime. Implementation: #storing the number to be checkednumber=43i=2 #flag variablef=0 #running a loop from 2 to number/2while test $i -le `expr $number / 2` do #checking if i is factor of numberif test `expr $number % $i` -eq 0 thenf=1fi #increment the loop variablei=`expr $i + 1`doneif test $f -eq 1 thenecho "Not Prime"elseecho "Prime"fi Output: Prime shubham_singh Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples
[ { "code": null, "e": 25741, "s": 25713, "text": "\n30 Sep, 2019" }, { "code": null, "e": 25840, "s": 25741, "text": "Given a number, the task is to find whether the given number is prime or not using Bash Scripting." }, { "code": null, "e": 25850, "s": 25840, "text": "Examples:" }, { "code": null, "e": 25912, "s": 25850, "text": "Input: N = 43\nOutput: Prime\n\nInput: N = 35\nOutput: Not Prime\n" }, { "code": null, "e": 26075, "s": 25912, "text": "Prime Numbers:A prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 ....." }, { "code": null, "e": 26233, "s": 26075, "text": "Approach:We run a loop from 2 to number/2 and check if there is any factor of the number. If we find any factor then the number is composite otherwise prime." }, { "code": null, "e": 26249, "s": 26233, "text": "Implementation:" }, { "code": "#storing the number to be checkednumber=43i=2 #flag variablef=0 #running a loop from 2 to number/2while test $i -le `expr $number / 2` do #checking if i is factor of numberif test `expr $number % $i` -eq 0 thenf=1fi #increment the loop variablei=`expr $i + 1`doneif test $f -eq 1 thenecho \"Not Prime\"elseecho \"Prime\"fi", "e": 26572, "s": 26249, "text": null }, { "code": null, "e": 26580, "s": 26572, "text": "Output:" }, { "code": null, "e": 26587, "s": 26580, "text": "Prime\n" }, { "code": null, "e": 26601, "s": 26587, "text": "shubham_singh" }, { "code": null, "e": 26614, "s": 26601, "text": "Shell Script" }, { "code": null, "e": 26625, "s": 26614, "text": "Linux-Unix" }, { "code": null, "e": 26723, "s": 26625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26761, "s": 26723, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26802, "s": 26761, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 26837, "s": 26802, "text": "tar command in Linux with examples" }, { "code": null, "e": 26873, "s": 26837, "text": "curl command in Linux with Examples" }, { "code": null, "e": 26911, "s": 26873, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 26944, "s": 26911, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 26980, "s": 26944, "text": "diff command in Linux with examples" }, { "code": null, "e": 27018, "s": 26980, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27054, "s": 27018, "text": "Tail command in Linux with examples" } ]
CSS | column-width Property - GeeksforGeeks
28 Apr, 2021 The columns-width property in CSS is used to define the width of the columns. The minimum number of columns are require to show the content across the element. It is a flexible property. If the browser cannot fit at least two-columns at given column-width then the two columns will put into a single column.Syntax: column-width: auto|length|initial|inherit; Property Values: auto: It is the default value. The browser determine the width of the columns.Syntax: column-width: auto; Example: html <!DOCTYPE html><html> <head> <title> CSS column-width Property </title> <style> .gfg { /* For Chrome, Safari, Opera browsers */ -webkit-column-width: auto; /* For Firefox browser */ -moz-column-width: auto; column-width: auto; } </style> </head> <body> <h2 > The column-width Property </h2> <div class = "gfg"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </body></html> Output: length: It is used to specify the width of the columns in terms of length. The length can be set in form of px, cm etc.Syntax: column-width: length; Example: html <!DOCTYPE html><html> <head> <title> CSS column-width Property </title> <style> .gfg { /* For Chrome, Safari, Opera browsers */ -webkit-column-width: 100px; /* For Firefox browser */ -moz-column-width: 100px; column-width: 100px; } </style> </head> <body> <h2 > The column-width Property </h2> <div class = "gfg"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </body></html> Output: initial: It is used to set the column-width property to its default value.Syntax: column-width: initial; Example: html <!DOCTYPE html><html> <head> <title> CSS column-width Property </title> <style> .gfg { /* For Chrome, Safari, Opera browsers */ -webkit-column-width: initial; /* For Firefox browser */ -moz-column-width: initial; column-width: initial; } </style> </head> <body> <h2 > The column-width Property </h2> <div class = "gfg"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </body></html> Output: inherit: It is used to set column-width property from its parent. Supported Browsers: The browser supported by column-width property are listed below: Google Chrome 50.0, 4.0-webkit Internet Explorer 10.0 Firefox 52.0, 2.0-moz- Opera 37.0, 15.0-webkit-, 11.1 Safari 9.0, 3.1-webkit arorakashish0911 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to create footer to stay at the bottom of a Web page? Remove elements from a JavaScript Array Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript Installation of Node.js on Linux
[ { "code": null, "e": 24897, "s": 24869, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25214, "s": 24897, "text": "The columns-width property in CSS is used to define the width of the columns. The minimum number of columns are require to show the content across the element. It is a flexible property. If the browser cannot fit at least two-columns at given column-width then the two columns will put into a single column.Syntax: " }, { "code": null, "e": 25258, "s": 25214, "text": "column-width: auto|length|initial|inherit; " }, { "code": null, "e": 25277, "s": 25258, "text": "Property Values: " }, { "code": null, "e": 25365, "s": 25277, "text": "auto: It is the default value. The browser determine the width of the columns.Syntax: " }, { "code": null, "e": 25385, "s": 25365, "text": "column-width: auto;" }, { "code": null, "e": 25396, "s": 25385, "text": "Example: " }, { "code": null, "e": 25401, "s": 25396, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS column-width Property </title> <style> .gfg { /* For Chrome, Safari, Opera browsers */ -webkit-column-width: auto; /* For Firefox browser */ -moz-column-width: auto; column-width: auto; } </style> </head> <body> <h2 > The column-width Property </h2> <div class = \"gfg\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </body></html> ", "e": 26347, "s": 25401, "text": null }, { "code": null, "e": 26357, "s": 26347, "text": "Output: " }, { "code": null, "e": 26486, "s": 26357, "text": "length: It is used to specify the width of the columns in terms of length. The length can be set in form of px, cm etc.Syntax: " }, { "code": null, "e": 26508, "s": 26486, "text": "column-width: length;" }, { "code": null, "e": 26519, "s": 26508, "text": "Example: " }, { "code": null, "e": 26524, "s": 26519, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS column-width Property </title> <style> .gfg { /* For Chrome, Safari, Opera browsers */ -webkit-column-width: 100px; /* For Firefox browser */ -moz-column-width: 100px; column-width: 100px; } </style> </head> <body> <h2 > The column-width Property </h2> <div class = \"gfg\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </body></html> ", "e": 27474, "s": 26524, "text": null }, { "code": null, "e": 27484, "s": 27474, "text": "Output: " }, { "code": null, "e": 27568, "s": 27484, "text": "initial: It is used to set the column-width property to its default value.Syntax: " }, { "code": null, "e": 27591, "s": 27568, "text": "column-width: initial;" }, { "code": null, "e": 27602, "s": 27591, "text": "Example: " }, { "code": null, "e": 27607, "s": 27602, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS column-width Property </title> <style> .gfg { /* For Chrome, Safari, Opera browsers */ -webkit-column-width: initial; /* For Firefox browser */ -moz-column-width: initial; column-width: initial; } </style> </head> <body> <h2 > The column-width Property </h2> <div class = \"gfg\"> The course is designed for students as well as working professionals to prepare for coding interviews. This course is going to have coding questions from school level to the level needed for product based companies like Amazon, Microsoft, Adobe, etc. </div> </body></html> ", "e": 28560, "s": 27607, "text": null }, { "code": null, "e": 28570, "s": 28560, "text": "Output: " }, { "code": null, "e": 28636, "s": 28570, "text": "inherit: It is used to set column-width property from its parent." }, { "code": null, "e": 28723, "s": 28636, "text": "Supported Browsers: The browser supported by column-width property are listed below: " }, { "code": null, "e": 28754, "s": 28723, "text": "Google Chrome 50.0, 4.0-webkit" }, { "code": null, "e": 28777, "s": 28754, "text": "Internet Explorer 10.0" }, { "code": null, "e": 28800, "s": 28777, "text": "Firefox 52.0, 2.0-moz-" }, { "code": null, "e": 28831, "s": 28800, "text": "Opera 37.0, 15.0-webkit-, 11.1" }, { "code": null, "e": 28854, "s": 28831, "text": "Safari 9.0, 3.1-webkit" }, { "code": null, "e": 28873, "s": 28856, "text": "arorakashish0911" }, { "code": null, "e": 28888, "s": 28873, "text": "CSS-Properties" }, { "code": null, "e": 28895, "s": 28888, "text": "Picked" }, { "code": null, "e": 28899, "s": 28895, "text": "CSS" }, { "code": null, "e": 28916, "s": 28899, "text": "Web Technologies" }, { "code": null, "e": 29014, "s": 28916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29076, "s": 29014, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29126, "s": 29076, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29174, "s": 29126, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29232, "s": 29174, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 29287, "s": 29232, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29345, "s": 29287, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 29385, "s": 29345, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29447, "s": 29385, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29492, "s": 29447, "text": "Convert a string to an integer in JavaScript" } ]
Check if it is possible to create a palindrome string from given N - GeeksforGeeks
31 Oct, 2018 Given a number N. The task is to create an alphabetical string in lower case from that number and tell whether the string is palindrome or not. a = 0, b = 1..... and so on. For eg: If the number is 61 the substring “gb” will be printed till 7 (6+1) characters i.e. “gbgbgbg” and check if palindrome or not. Note: No number will start with zero. Consider alphabets ‘ a to j ‘ only i.e. single digit numbers from 0 to 9. Examples: Input: N = 61Output: YESNumbers 6, 1 represent letters ‘g’, ‘b’ respectively. So the substring is ‘gb’ and the sum is 7(6+1). Thus the alphabetical string formed is ‘gbgbgbg’, and is a palindrome. Input: N = 1998Output: NONumbers 1, 9, 8 represent letters ‘b’, ‘j’ and ‘i’ respectively. So the substring is ‘bjji’ and sum is 27(1+9+9+8). Thus the alphabetical string formed is bjjibjjibjjibjjibjjibjjibjj’, and is not a palindrome. Approach: Obtain the substring corresponding to given number N and maintain its digit’s sum.Append the substring till its length becomes equal to the sum of digits of N.Check if the string obtained is Palindrome or not.If it is a Palindrome, print YES.Else, print NO. Obtain the substring corresponding to given number N and maintain its digit’s sum. Append the substring till its length becomes equal to the sum of digits of N. Check if the string obtained is Palindrome or not. If it is a Palindrome, print YES. Else, print NO. Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation of the// above approach#include<bits/stdc++.h>using namespace std; // Function to check if a string // is palindrome or notbool isPalindrome(string s){ // String that stores characters // of s in reverse order string s1 = ""; // Length of the string s int N = s.length(); for (int i = N - 1; i >= 0; i--) s1 += s[i]; if (s == s1) return true; return false;} bool createString(int N){ string str = ""; string s = to_string(N); // String used to form substring // using N string letters = "abcdefghij"; // Variable to store sum // of digits of N int sum = 0; string substr = ""; // Forming the substring // by traversing N for (int i = 0; i < s.length(); i++) { int digit = s[i] - '0'; substr += letters[digit]; sum += digit; } // Appending the substr to str till // it's length becomes equal to sum while (str.length() <= sum) { str += substr; } // Trimming the string str so that // it's length becomes equal to sum str = str.substr(0, sum); return isPalindrome(str);} // Driver codeint main(){ int N = 61; // Calling function isPalindrome to // check if str is Palindrome or not bool flag = createString(N); if (flag) cout << "YES"; else cout << "NO";} // This code is contributed by ihritik // Java implementation of the above approachimport java.io.*;import java.util.*; public class GFG { // Function to check if a string is palindrome or not static boolean isPalindrome(String s) { // String that stores characters // of s in reverse order String s1 = ""; // Length of the string s int N = s.length(); for (int i = N - 1; i >= 0; i--) s1 += s.charAt(i); if (s.equals(s1)) return true; return false; } static boolean createString(int N) { String str = ""; String s = "" + N; // String used to form substring using N String letters = "abcdefghij"; // Variable to store sum of digits of N int sum = 0; String substr = ""; // Forming the substring by traversing N for (int i = 0; i < s.length(); i++) { int digit = s.charAt(i) - '0'; substr += letters.charAt(digit); sum += digit; } // Appending the substr to str // till it's length becomes equal to sum while (str.length() <= sum) { str += substr; } // Trimming the string str so that // it's length becomes equal to sum str = str.substring(0, sum); return isPalindrome(str); } // Driver code public static void main(String args[]) { int N = 61; // Calling function isPalindrome to // check if str is Palindrome or not boolean flag = createString(N); if (flag) System.out.println("YES"); else System.out.println("NO"); }} # Python3 implementation of # the above approach # Function to check if a string # is palindrome or notdef isPalindrome(s): # String that stores characters # of s in reverse order s1 = "" # Length of the string s N = len(s) i = (N - 1) while(i >= 0): s1 += s[i] i = i - 1 if (s == s1): return True return False def createString(N): s2 = "" s = str(N) # String used to form # substring using N letters = "abcdefghij" # Variable to store sum # of digits of N sum = 0 substr = "" # Forming the substring # by traversing N for i in range(0, len(s)) : digit = int(s[i]) substr += letters[digit] sum += digit # Appending the substr to str till # it's length becomes equal to sum while (len(s2) <= sum): s2 += substr # Trimming the string str so that # it's length becomes equal to sum s2 = s2[:sum] return isPalindrome(s2) # Driver codeN = 61; # Calling function isPalindrome to # check if str is Palindrome or notflag = createString(N)if (flag): print("YES")else: print("NO") # This code is contributed by ihritik // C# implementation of the// above approachusing System; class GFG { // Function to check if a string // is palindrome or notstatic bool isPalindrome(String s){ // String that stores characters // of s in reverse order String s1 = ""; // Length of the string s int N = s.Length; for (int i = N - 1; i >= 0; i--) s1 += s[i]; if (s.Equals(s1)) return true; return false;} static bool createString(int N){ String str = ""; String s = "" + N; // String used to form substring // using N String letters = "abcdefghij"; // Variable to store sum // of digits of N int sum = 0; String substr = ""; // Forming the substring // by traversing N for (int i = 0; i < s.Length; i++) { int digit = s[i] - '0'; substr += letters[digit]; sum += digit; } // Appending the substr to str till // it's length becomes equal to sum while (str.Length <= sum) { str += substr; } // Trimming the string str so that // it's length becomes equal to sum str = str.Substring(0, sum); return isPalindrome(str);} // Driver codepublic static void Main(){ int N = 61; // Calling function isPalindrome to // check if str is Palindrome or not bool flag = createString(N); if (flag) Console.WriteLine("YES"); else Console.WriteLine("NO");}} // This code is contributed // by ihritik YES ihritik Arrays palindrome Strings Arrays Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Vigenère Cipher String class in Java | Set 1 sprintf() in C Print all subsequences of a string Convert character array to string in C++ Program to count occurrence of a given character in a string How to Append a Character to a String in C Naive algorithm for Pattern Searching
[ { "code": null, "e": 26073, "s": 26045, "text": "\n31 Oct, 2018" }, { "code": null, "e": 26246, "s": 26073, "text": "Given a number N. The task is to create an alphabetical string in lower case from that number and tell whether the string is palindrome or not. a = 0, b = 1..... and so on." }, { "code": null, "e": 26380, "s": 26246, "text": "For eg: If the number is 61 the substring “gb” will be printed till 7 (6+1) characters i.e. “gbgbgbg” and check if palindrome or not." }, { "code": null, "e": 26492, "s": 26380, "text": "Note: No number will start with zero. Consider alphabets ‘ a to j ‘ only i.e. single digit numbers from 0 to 9." }, { "code": null, "e": 26502, "s": 26492, "text": "Examples:" }, { "code": null, "e": 26699, "s": 26502, "text": "Input: N = 61Output: YESNumbers 6, 1 represent letters ‘g’, ‘b’ respectively. So the substring is ‘gb’ and the sum is 7(6+1). Thus the alphabetical string formed is ‘gbgbgbg’, and is a palindrome." }, { "code": null, "e": 26934, "s": 26699, "text": "Input: N = 1998Output: NONumbers 1, 9, 8 represent letters ‘b’, ‘j’ and ‘i’ respectively. So the substring is ‘bjji’ and sum is 27(1+9+9+8). Thus the alphabetical string formed is bjjibjjibjjibjjibjjibjjibjj’, and is not a palindrome." }, { "code": null, "e": 26944, "s": 26934, "text": "Approach:" }, { "code": null, "e": 27202, "s": 26944, "text": "Obtain the substring corresponding to given number N and maintain its digit’s sum.Append the substring till its length becomes equal to the sum of digits of N.Check if the string obtained is Palindrome or not.If it is a Palindrome, print YES.Else, print NO." }, { "code": null, "e": 27285, "s": 27202, "text": "Obtain the substring corresponding to given number N and maintain its digit’s sum." }, { "code": null, "e": 27363, "s": 27285, "text": "Append the substring till its length becomes equal to the sum of digits of N." }, { "code": null, "e": 27414, "s": 27363, "text": "Check if the string obtained is Palindrome or not." }, { "code": null, "e": 27448, "s": 27414, "text": "If it is a Palindrome, print YES." }, { "code": null, "e": 27464, "s": 27448, "text": "Else, print NO." }, { "code": null, "e": 27515, "s": 27464, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27519, "s": 27515, "text": "C++" }, { "code": null, "e": 27524, "s": 27519, "text": "Java" }, { "code": null, "e": 27532, "s": 27524, "text": "Python3" }, { "code": null, "e": 27535, "s": 27532, "text": "C#" }, { "code": "// C++ implementation of the// above approach#include<bits/stdc++.h>using namespace std; // Function to check if a string // is palindrome or notbool isPalindrome(string s){ // String that stores characters // of s in reverse order string s1 = \"\"; // Length of the string s int N = s.length(); for (int i = N - 1; i >= 0; i--) s1 += s[i]; if (s == s1) return true; return false;} bool createString(int N){ string str = \"\"; string s = to_string(N); // String used to form substring // using N string letters = \"abcdefghij\"; // Variable to store sum // of digits of N int sum = 0; string substr = \"\"; // Forming the substring // by traversing N for (int i = 0; i < s.length(); i++) { int digit = s[i] - '0'; substr += letters[digit]; sum += digit; } // Appending the substr to str till // it's length becomes equal to sum while (str.length() <= sum) { str += substr; } // Trimming the string str so that // it's length becomes equal to sum str = str.substr(0, sum); return isPalindrome(str);} // Driver codeint main(){ int N = 61; // Calling function isPalindrome to // check if str is Palindrome or not bool flag = createString(N); if (flag) cout << \"YES\"; else cout << \"NO\";} // This code is contributed by ihritik", "e": 28951, "s": 27535, "text": null }, { "code": "// Java implementation of the above approachimport java.io.*;import java.util.*; public class GFG { // Function to check if a string is palindrome or not static boolean isPalindrome(String s) { // String that stores characters // of s in reverse order String s1 = \"\"; // Length of the string s int N = s.length(); for (int i = N - 1; i >= 0; i--) s1 += s.charAt(i); if (s.equals(s1)) return true; return false; } static boolean createString(int N) { String str = \"\"; String s = \"\" + N; // String used to form substring using N String letters = \"abcdefghij\"; // Variable to store sum of digits of N int sum = 0; String substr = \"\"; // Forming the substring by traversing N for (int i = 0; i < s.length(); i++) { int digit = s.charAt(i) - '0'; substr += letters.charAt(digit); sum += digit; } // Appending the substr to str // till it's length becomes equal to sum while (str.length() <= sum) { str += substr; } // Trimming the string str so that // it's length becomes equal to sum str = str.substring(0, sum); return isPalindrome(str); } // Driver code public static void main(String args[]) { int N = 61; // Calling function isPalindrome to // check if str is Palindrome or not boolean flag = createString(N); if (flag) System.out.println(\"YES\"); else System.out.println(\"NO\"); }}", "e": 30606, "s": 28951, "text": null }, { "code": "# Python3 implementation of # the above approach # Function to check if a string # is palindrome or notdef isPalindrome(s): # String that stores characters # of s in reverse order s1 = \"\" # Length of the string s N = len(s) i = (N - 1) while(i >= 0): s1 += s[i] i = i - 1 if (s == s1): return True return False def createString(N): s2 = \"\" s = str(N) # String used to form # substring using N letters = \"abcdefghij\" # Variable to store sum # of digits of N sum = 0 substr = \"\" # Forming the substring # by traversing N for i in range(0, len(s)) : digit = int(s[i]) substr += letters[digit] sum += digit # Appending the substr to str till # it's length becomes equal to sum while (len(s2) <= sum): s2 += substr # Trimming the string str so that # it's length becomes equal to sum s2 = s2[:sum] return isPalindrome(s2) # Driver codeN = 61; # Calling function isPalindrome to # check if str is Palindrome or notflag = createString(N)if (flag): print(\"YES\")else: print(\"NO\") # This code is contributed by ihritik", "e": 31790, "s": 30606, "text": null }, { "code": "// C# implementation of the// above approachusing System; class GFG { // Function to check if a string // is palindrome or notstatic bool isPalindrome(String s){ // String that stores characters // of s in reverse order String s1 = \"\"; // Length of the string s int N = s.Length; for (int i = N - 1; i >= 0; i--) s1 += s[i]; if (s.Equals(s1)) return true; return false;} static bool createString(int N){ String str = \"\"; String s = \"\" + N; // String used to form substring // using N String letters = \"abcdefghij\"; // Variable to store sum // of digits of N int sum = 0; String substr = \"\"; // Forming the substring // by traversing N for (int i = 0; i < s.Length; i++) { int digit = s[i] - '0'; substr += letters[digit]; sum += digit; } // Appending the substr to str till // it's length becomes equal to sum while (str.Length <= sum) { str += substr; } // Trimming the string str so that // it's length becomes equal to sum str = str.Substring(0, sum); return isPalindrome(str);} // Driver codepublic static void Main(){ int N = 61; // Calling function isPalindrome to // check if str is Palindrome or not bool flag = createString(N); if (flag) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");}} // This code is contributed // by ihritik", "e": 33241, "s": 31790, "text": null }, { "code": null, "e": 33246, "s": 33241, "text": "YES\n" }, { "code": null, "e": 33254, "s": 33246, "text": "ihritik" }, { "code": null, "e": 33261, "s": 33254, "text": "Arrays" }, { "code": null, "e": 33272, "s": 33261, "text": "palindrome" }, { "code": null, "e": 33280, "s": 33272, "text": "Strings" }, { "code": null, "e": 33287, "s": 33280, "text": "Arrays" }, { "code": null, "e": 33295, "s": 33287, "text": "Strings" }, { "code": null, "e": 33306, "s": 33295, "text": "palindrome" }, { "code": null, "e": 33404, "s": 33306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33449, "s": 33404, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 33494, "s": 33449, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 33511, "s": 33494, "text": "Vigenère Cipher" }, { "code": null, "e": 33540, "s": 33511, "text": "String class in Java | Set 1" }, { "code": null, "e": 33555, "s": 33540, "text": "sprintf() in C" }, { "code": null, "e": 33590, "s": 33555, "text": "Print all subsequences of a string" }, { "code": null, "e": 33631, "s": 33590, "text": "Convert character array to string in C++" }, { "code": null, "e": 33692, "s": 33631, "text": "Program to count occurrence of a given character in a string" }, { "code": null, "e": 33735, "s": 33692, "text": "How to Append a Character to a String in C" } ]
How to get current function name in PHP? - GeeksforGeeks
11 Nov, 2018 The function name can be easily obtained by the __FUNCTION__ or the __METHOD__magic constant. Method 1 (Prints function name):__FUNCTION__ is used to resolve function name or method name (function in class). Example: <?phpclass Test { public function bar() { var_dump(__FUNCTION__); }} function foo() { var_dump(__FUNCTION__);} // Must output string(3) 'foo' foo(); $obj = new Test; // Must output string(3) 'bar'$obj->bar(); string(3) "foo" string(3) "bar" Method 2 (Prints function and class name):using __METHOD__. <?php class Test { public function foo() { var_dump(__METHOD__); }} function bar(){ var_dump(__METHOD__);} // Same As __FUNCTION__bar(); $obj = new Test; // Output the fully qualified method name "ClassName::MethodName"$obj->foo(); string(3) "bar" string(9) "Test::foo" Note: this code is tested with php7.1 PHP-function Picked Technical Scripter 2018 PHP Technical Scripter PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP Download file from URL using PHP How to get parameters from a URL string in PHP? How to declare a global variable in PHP? How to run JavaScript from PHP? How to fetch data from localserver database and display on HTML table using PHP ? Best way to initialize empty array in PHP
[ { "code": null, "e": 25963, "s": 25935, "text": "\n11 Nov, 2018" }, { "code": null, "e": 26057, "s": 25963, "text": "The function name can be easily obtained by the __FUNCTION__ or the __METHOD__magic constant." }, { "code": null, "e": 26171, "s": 26057, "text": "Method 1 (Prints function name):__FUNCTION__ is used to resolve function name or method name (function in class)." }, { "code": null, "e": 26180, "s": 26171, "text": "Example:" }, { "code": "<?phpclass Test { public function bar() { var_dump(__FUNCTION__); }} function foo() { var_dump(__FUNCTION__);} // Must output string(3) 'foo' foo(); $obj = new Test; // Must output string(3) 'bar'$obj->bar();", "e": 26411, "s": 26180, "text": null }, { "code": null, "e": 26444, "s": 26411, "text": "string(3) \"foo\"\nstring(3) \"bar\"\n" }, { "code": null, "e": 26504, "s": 26444, "text": "Method 2 (Prints function and class name):using __METHOD__." }, { "code": "<?php class Test { public function foo() { var_dump(__METHOD__); }} function bar(){ var_dump(__METHOD__);} // Same As __FUNCTION__bar(); $obj = new Test; // Output the fully qualified method name \"ClassName::MethodName\"$obj->foo();", "e": 26759, "s": 26504, "text": null }, { "code": null, "e": 26798, "s": 26759, "text": "string(3) \"bar\"\nstring(9) \"Test::foo\"\n" }, { "code": null, "e": 26836, "s": 26798, "text": "Note: this code is tested with php7.1" }, { "code": null, "e": 26849, "s": 26836, "text": "PHP-function" }, { "code": null, "e": 26856, "s": 26849, "text": "Picked" }, { "code": null, "e": 26880, "s": 26856, "text": "Technical Scripter 2018" }, { "code": null, "e": 26884, "s": 26880, "text": "PHP" }, { "code": null, "e": 26903, "s": 26884, "text": "Technical Scripter" }, { "code": null, "e": 26907, "s": 26903, "text": "PHP" }, { "code": null, "e": 27005, "s": 26907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27045, "s": 27005, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27090, "s": 27045, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27132, "s": 27090, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27184, "s": 27132, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 27217, "s": 27184, "text": "Download file from URL using PHP" }, { "code": null, "e": 27265, "s": 27217, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 27306, "s": 27265, "text": "How to declare a global variable in PHP?" }, { "code": null, "e": 27338, "s": 27306, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 27420, "s": 27338, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" } ]
How do you use NumPy, SciPy and SymPy to solve Systems of Linear Equations? | by Rukshan Pramoditha | Towards Data Science
In linear algebra, a system of linear equations is defined as a collection of two or more linear equations having the same set of variables. All equations in the system are considered simultaneously. Systems of linear equations are used in different sectors such as Manufacturing, Marketing, Business, Transportation, etc. The solving process of a system of linear equations will become more complicated when the number of equations and variables are increased. The solution must satisfy every equation in the system. In Python, NumPy (Numerical Python), SciPy (Scientific Python) and SymPy (Symbolic Python) libraries can be used to solve systems of linear equations. These libraries use the concept of vectorization which allow them to do matrix computations efficiently by avoiding many for loops. Not all linear systems have a unique solution. Some of them have no solution or infinitely many solutions. We will cover these 3 types of linear systems with NumPy, SciPy and SymPy implementation. The implementation can be done in a few different ways. We’ll also discuss these different ways where necessary. At the end of this article, you’ll be able to solve a linear system (if a unique solution exists) and identify linear systems with no solution or infinitely many solutions with powerful NumPy, SciPy and SymPy libraries. Basic knowledge of NumPy (array creation, identification of one-dimensional and 2-dimensional arrays, etc) is highly recommended. If you’re not familiar with them, don’t worry. To get the basic knowledge, you can read the following article written by me. towardsdatascience.com Let’s get started! Have look at the following image which contains a linear system of equations. There are 3 linear equations in this system. Each equation has the same set of variables called x, y and z. Solving this linear system means that finding values (if exists) for x, y and z that satisfy all the equations. The above system of linear equations can be represented as a special matrix called the augmented matrix which opens the path to solve linear systems by doing matrix calculations. There are two parts of this augmented matrix: Coefficient matrix — This is a rectangular array which contains only the coefficients of the variables. In our example, this is a 3 x 3 square matrix left of the vertical line in the above picture. The first column contains the coefficients of x for each of the equations, the second column contains the coefficients of y and so on. The number of rows equals the number of equations in the linear system. The number of columns equals the number of different variables in the linear system. In NumPy, this can be represented as a 2-dimensional array. This is often assigned to a variable named with an uppercase letter (such as A or B). import numpy as npA = np.array([[2, -3, 1], [1, -1, 2], [3, 1, -1]]) Augment — This is a column vector right to the vertical line in the above picture. It contains constants of the linear equations. In our example, this is a 3 x 1 column vector. In NumPy, this can be represented as a 1-dimensional array. This is often assigned to a variable named with a lowercase letter (such as b). import numpy as npb = np.array([-1, -3, 9]) Let’s solve the following linear system with NumPy. To solve this right away, we use the solve() function in the NumPy linalg subpackage. import numpy as npA = np.array([[2, -3, 1], [1, -1, 2], [3, 1, -1]])b = np.array([-1, -3, 9])np.linalg.solve(A, b) The output is: Wow! The above linear system has a unique solution: x = 2 y = 1 z = -2 Note: A similar type of implementation can be done with SciPy: from scipy import linalglinalg.solve(A, b) The direct implementation does not give a clear idea of how this works internally. Let’s derive the matrix equation. Let’s get the same solution using the matrix equation: np.dot(np.linalg.inv(A), b) To have a solution, the inverse of A should exist and the determinant of A should be non-zero: np.linalg.det(A) When a system of linear equations has no solution, such a system is called an inconsistent system. Let’s see what will happen when we try to solve the following linear system with NumPy: import numpy as npA = np.array([[1, -1, 4], [3, 0, 1], [-1, 1, -4]])b = np.array([-5, 0, 20])np.linalg.solve(A, b) The output is: The error message says that our coefficient matrix (A) is singular. In algebra terms, it is a non-invertible matrix whose determinant is zero. Let’s check it: np.linalg.det(A) The output is: The determinant is zero. Therefore, our coefficient matrix (A) is singular. Because of that, the above system of linear equations has no solution! Note: If you implement this with SciPy, a similar type of error message will be returned. When a system of linear equations has infinitely many solutions, such a system is called a dependent system. Let’s see what will happen when we try to solve the following linear system with NumPy: import numpy as npA = np.array([[-1, 1, 2], [1, 2, 1], [-2, -1, 1]])b = np.array([0, 6, -6])np.linalg.solve(A, b) The output is: This is the same as the previous case. Note: If you implement this with SciPy, a similar type of error message will be returned. Now, there is a question. How can we distinguish between linear systems with no solution and linear systems with infinitely many solutions? There is a method. We attempt to put the coefficient matrix into the reduced row-echelon form which has 1’s on its diagonal and 0’s everywhere else (identity matrix). If we succeed, the system has a unique solution. If we are unable to put the coefficient matrix into the identity matrix, either there is no solution or infinitely many solutions. In that case, we can distingush between linear systems with no solution and linear systems with infinitely many solutions by looking at the last row of the reduced matrix. We can use the SymPy Python package to get the reduced row-echelon form. First, we create the augmented matrix and then use the rref() method. Let’s try it out with a linear system with a unique solution: from sympy import *augmented_A = Matrix([[2, -3, 1, -1], [1, -1, 2, -3], [3, 1, -1, 9]])augmented_A.rref()[0] We succeeded! We got the reduced row-echelon form. The 4th column is the solution column. The solution is x=2, y=1 and z=-2 which agrees with the previous solution obtained using np.linalg.solve(). Let’s try it with a linear system with no solution: from sympy import *augmented_A = Matrix([[1, -1, 4, -5], [3, 0, 1, 0], [-1, 1, -4, 20]])augmented_A.rref()[0] In this time, we did not succeed. We didn’t gt the reduced row-echelon form. The 3rd row (equation) of this form is 0=1 which is impossible! Therefore, the linear system has no solution. The linear system is inconsistent. Finally, we try it with a linear system with infinitely many solutions: from sympy import *augmented_A = Matrix([[-1, 1, 2, 0], [1, 2, 1, 6], [-2, -1, 1, -6]])augmented_A.rref()[0] In this time also, we did not succeed. We didn’t gt the reduced row-echelon form. The 3rd row (equation) of this form is 0=0 which is always true! This implies the variable z can take any real number and x and y can be: z = any number x-z = 2 (x = 2+z) y+z = 2 (y = 2-z) By substituting any real number to z, we can get infinitely many solutions! The linear system is dependent. We’ve done the job. Now, you’re able to solve a linear system (if a unique solution exists) and distinguish between linear systems with no solution and linear systems with infinitely many solutions with powerful NumPy, SciPy and SymPy libraries. The general implementation is: First, try np.linalg.solve(). If you get a unique solution, you’ve done the job. If you get an error message (“Singular matrix”), the linear system either have no solution or infintily many solutions. Then, try to get the reduced row-echelon form using SymPy Python package as discussed above. By looking at the last row of he reduced form, you can decide the things! Also, note the following points too. The above-discussed methods can only be applied to linear systems. In other words, all the equations in the system should be linear. If a linear system has fewer equations than variables, the system must be dependent or inconsistent. It will never have a unique solution. Linear systems with more equations than variables may have no solution, unique solution or infinitely many solutions. 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 Antoine Dautry 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": 495, "s": 172, "text": "In linear algebra, a system of linear equations is defined as a collection of two or more linear equations having the same set of variables. All equations in the system are considered simultaneously. Systems of linear equations are used in different sectors such as Manufacturing, Marketing, Business, Transportation, etc." }, { "code": null, "e": 973, "s": 495, "text": "The solving process of a system of linear equations will become more complicated when the number of equations and variables are increased. The solution must satisfy every equation in the system. In Python, NumPy (Numerical Python), SciPy (Scientific Python) and SymPy (Symbolic Python) libraries can be used to solve systems of linear equations. These libraries use the concept of vectorization which allow them to do matrix computations efficiently by avoiding many for loops." }, { "code": null, "e": 1080, "s": 973, "text": "Not all linear systems have a unique solution. Some of them have no solution or infinitely many solutions." }, { "code": null, "e": 1503, "s": 1080, "text": "We will cover these 3 types of linear systems with NumPy, SciPy and SymPy implementation. The implementation can be done in a few different ways. We’ll also discuss these different ways where necessary. At the end of this article, you’ll be able to solve a linear system (if a unique solution exists) and identify linear systems with no solution or infinitely many solutions with powerful NumPy, SciPy and SymPy libraries." }, { "code": null, "e": 1758, "s": 1503, "text": "Basic knowledge of NumPy (array creation, identification of one-dimensional and 2-dimensional arrays, etc) is highly recommended. If you’re not familiar with them, don’t worry. To get the basic knowledge, you can read the following article written by me." }, { "code": null, "e": 1781, "s": 1758, "text": "towardsdatascience.com" }, { "code": null, "e": 1800, "s": 1781, "text": "Let’s get started!" }, { "code": null, "e": 1878, "s": 1800, "text": "Have look at the following image which contains a linear system of equations." }, { "code": null, "e": 2098, "s": 1878, "text": "There are 3 linear equations in this system. Each equation has the same set of variables called x, y and z. Solving this linear system means that finding values (if exists) for x, y and z that satisfy all the equations." }, { "code": null, "e": 2277, "s": 2098, "text": "The above system of linear equations can be represented as a special matrix called the augmented matrix which opens the path to solve linear systems by doing matrix calculations." }, { "code": null, "e": 2323, "s": 2277, "text": "There are two parts of this augmented matrix:" }, { "code": null, "e": 2959, "s": 2323, "text": "Coefficient matrix — This is a rectangular array which contains only the coefficients of the variables. In our example, this is a 3 x 3 square matrix left of the vertical line in the above picture. The first column contains the coefficients of x for each of the equations, the second column contains the coefficients of y and so on. The number of rows equals the number of equations in the linear system. The number of columns equals the number of different variables in the linear system. In NumPy, this can be represented as a 2-dimensional array. This is often assigned to a variable named with an uppercase letter (such as A or B)." }, { "code": null, "e": 3054, "s": 2959, "text": "import numpy as npA = np.array([[2, -3, 1], [1, -1, 2], [3, 1, -1]])" }, { "code": null, "e": 3371, "s": 3054, "text": "Augment — This is a column vector right to the vertical line in the above picture. It contains constants of the linear equations. In our example, this is a 3 x 1 column vector. In NumPy, this can be represented as a 1-dimensional array. This is often assigned to a variable named with a lowercase letter (such as b)." }, { "code": null, "e": 3415, "s": 3371, "text": "import numpy as npb = np.array([-1, -3, 9])" }, { "code": null, "e": 3467, "s": 3415, "text": "Let’s solve the following linear system with NumPy." }, { "code": null, "e": 3553, "s": 3467, "text": "To solve this right away, we use the solve() function in the NumPy linalg subpackage." }, { "code": null, "e": 3694, "s": 3553, "text": "import numpy as npA = np.array([[2, -3, 1], [1, -1, 2], [3, 1, -1]])b = np.array([-1, -3, 9])np.linalg.solve(A, b)" }, { "code": null, "e": 3709, "s": 3694, "text": "The output is:" }, { "code": null, "e": 3761, "s": 3709, "text": "Wow! The above linear system has a unique solution:" }, { "code": null, "e": 3767, "s": 3761, "text": "x = 2" }, { "code": null, "e": 3773, "s": 3767, "text": "y = 1" }, { "code": null, "e": 3780, "s": 3773, "text": "z = -2" }, { "code": null, "e": 3843, "s": 3780, "text": "Note: A similar type of implementation can be done with SciPy:" }, { "code": null, "e": 3886, "s": 3843, "text": "from scipy import linalglinalg.solve(A, b)" }, { "code": null, "e": 4003, "s": 3886, "text": "The direct implementation does not give a clear idea of how this works internally. Let’s derive the matrix equation." }, { "code": null, "e": 4058, "s": 4003, "text": "Let’s get the same solution using the matrix equation:" }, { "code": null, "e": 4086, "s": 4058, "text": "np.dot(np.linalg.inv(A), b)" }, { "code": null, "e": 4181, "s": 4086, "text": "To have a solution, the inverse of A should exist and the determinant of A should be non-zero:" }, { "code": null, "e": 4198, "s": 4181, "text": "np.linalg.det(A)" }, { "code": null, "e": 4385, "s": 4198, "text": "When a system of linear equations has no solution, such a system is called an inconsistent system. Let’s see what will happen when we try to solve the following linear system with NumPy:" }, { "code": null, "e": 4526, "s": 4385, "text": "import numpy as npA = np.array([[1, -1, 4], [3, 0, 1], [-1, 1, -4]])b = np.array([-5, 0, 20])np.linalg.solve(A, b)" }, { "code": null, "e": 4541, "s": 4526, "text": "The output is:" }, { "code": null, "e": 4700, "s": 4541, "text": "The error message says that our coefficient matrix (A) is singular. In algebra terms, it is a non-invertible matrix whose determinant is zero. Let’s check it:" }, { "code": null, "e": 4717, "s": 4700, "text": "np.linalg.det(A)" }, { "code": null, "e": 4732, "s": 4717, "text": "The output is:" }, { "code": null, "e": 4879, "s": 4732, "text": "The determinant is zero. Therefore, our coefficient matrix (A) is singular. Because of that, the above system of linear equations has no solution!" }, { "code": null, "e": 4969, "s": 4879, "text": "Note: If you implement this with SciPy, a similar type of error message will be returned." }, { "code": null, "e": 5166, "s": 4969, "text": "When a system of linear equations has infinitely many solutions, such a system is called a dependent system. Let’s see what will happen when we try to solve the following linear system with NumPy:" }, { "code": null, "e": 5306, "s": 5166, "text": "import numpy as npA = np.array([[-1, 1, 2], [1, 2, 1], [-2, -1, 1]])b = np.array([0, 6, -6])np.linalg.solve(A, b)" }, { "code": null, "e": 5321, "s": 5306, "text": "The output is:" }, { "code": null, "e": 5360, "s": 5321, "text": "This is the same as the previous case." }, { "code": null, "e": 5450, "s": 5360, "text": "Note: If you implement this with SciPy, a similar type of error message will be returned." }, { "code": null, "e": 5609, "s": 5450, "text": "Now, there is a question. How can we distinguish between linear systems with no solution and linear systems with infinitely many solutions? There is a method." }, { "code": null, "e": 6109, "s": 5609, "text": "We attempt to put the coefficient matrix into the reduced row-echelon form which has 1’s on its diagonal and 0’s everywhere else (identity matrix). If we succeed, the system has a unique solution. If we are unable to put the coefficient matrix into the identity matrix, either there is no solution or infinitely many solutions. In that case, we can distingush between linear systems with no solution and linear systems with infinitely many solutions by looking at the last row of the reduced matrix." }, { "code": null, "e": 6314, "s": 6109, "text": "We can use the SymPy Python package to get the reduced row-echelon form. First, we create the augmented matrix and then use the rref() method. Let’s try it out with a linear system with a unique solution:" }, { "code": null, "e": 6466, "s": 6314, "text": "from sympy import *augmented_A = Matrix([[2, -3, 1, -1], [1, -1, 2, -3], [3, 1, -1, 9]])augmented_A.rref()[0]" }, { "code": null, "e": 6664, "s": 6466, "text": "We succeeded! We got the reduced row-echelon form. The 4th column is the solution column. The solution is x=2, y=1 and z=-2 which agrees with the previous solution obtained using np.linalg.solve()." }, { "code": null, "e": 6716, "s": 6664, "text": "Let’s try it with a linear system with no solution:" }, { "code": null, "e": 6868, "s": 6716, "text": "from sympy import *augmented_A = Matrix([[1, -1, 4, -5], [3, 0, 1, 0], [-1, 1, -4, 20]])augmented_A.rref()[0]" }, { "code": null, "e": 7090, "s": 6868, "text": "In this time, we did not succeed. We didn’t gt the reduced row-echelon form. The 3rd row (equation) of this form is 0=1 which is impossible! Therefore, the linear system has no solution. The linear system is inconsistent." }, { "code": null, "e": 7162, "s": 7090, "text": "Finally, we try it with a linear system with infinitely many solutions:" }, { "code": null, "e": 7313, "s": 7162, "text": "from sympy import *augmented_A = Matrix([[-1, 1, 2, 0], [1, 2, 1, 6], [-2, -1, 1, -6]])augmented_A.rref()[0]" }, { "code": null, "e": 7533, "s": 7313, "text": "In this time also, we did not succeed. We didn’t gt the reduced row-echelon form. The 3rd row (equation) of this form is 0=0 which is always true! This implies the variable z can take any real number and x and y can be:" }, { "code": null, "e": 7548, "s": 7533, "text": "z = any number" }, { "code": null, "e": 7566, "s": 7548, "text": "x-z = 2 (x = 2+z)" }, { "code": null, "e": 7584, "s": 7566, "text": "y+z = 2 (y = 2-z)" }, { "code": null, "e": 7692, "s": 7584, "text": "By substituting any real number to z, we can get infinitely many solutions! The linear system is dependent." }, { "code": null, "e": 7938, "s": 7692, "text": "We’ve done the job. Now, you’re able to solve a linear system (if a unique solution exists) and distinguish between linear systems with no solution and linear systems with infinitely many solutions with powerful NumPy, SciPy and SymPy libraries." }, { "code": null, "e": 7969, "s": 7938, "text": "The general implementation is:" }, { "code": null, "e": 8337, "s": 7969, "text": "First, try np.linalg.solve(). If you get a unique solution, you’ve done the job. If you get an error message (“Singular matrix”), the linear system either have no solution or infintily many solutions. Then, try to get the reduced row-echelon form using SymPy Python package as discussed above. By looking at the last row of he reduced form, you can decide the things!" }, { "code": null, "e": 8374, "s": 8337, "text": "Also, note the following points too." }, { "code": null, "e": 8507, "s": 8374, "text": "The above-discussed methods can only be applied to linear systems. In other words, all the equations in the system should be linear." }, { "code": null, "e": 8646, "s": 8507, "text": "If a linear system has fewer equations than variables, the system must be dependent or inconsistent. It will never have a unique solution." }, { "code": null, "e": 8764, "s": 8646, "text": "Linear systems with more equations than variables may have no solution, unique solution or infinitely many solutions." }, { "code": null, "e": 8926, "s": 8764, "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": 8988, "s": 8926, "text": "Sign-up link: https://rukshanpramoditha.medium.com/membership" }, { "code": null, "e": 9090, "s": 8988, "text": "Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!" } ]
Setting up Amazon SageMaker Environment On Your Local Machine | by Sam Palani | Towards Data Science
Amazon SageMaker is beyond just managed Jupyter notebooks, it is a fully managed service that enables you to build, train, optimize and deploy machine learning models. A common misconception, specially when you are starting out with SageMaker is that, in order to use these services, you need a SageMaker Notebook Instance or SageMaker (Studio) Notebook. You can in fact kick off all these services directly from your local machine or even from your favorite IDE. Before we go further, let’s consider how we interact with Amazon SageMaker services. You have two APIs SageMaker Python SDK — This is a high level API in Python that abstracts the code to build, train and deploy machine learning models. Specifically it provides estimators for first class or built in algorithms as well as supported frameworks like TensorFlow, MXNET etc. In most cases you will use this to interact with your interactive machine learning tasks. AWS SDK — This is a low level API that is used to interact with all supported AWS services, not specific to SageMaker. The AWS SDK is available in most popular programming languages like Java, Javascript, Python (boto) etc. In most cases you will use this service-level APIs for things such creating resources for automations or interacting with other AWS services that are not supported by the SageMaker Python SDK. Cost is probably the first thing that comes up, but it is also the flexibility to use your own IDE plus the ability to work offline and kick off jobs on AWS cloud when you are ready. You write the code to build your model as you normally would but instead of a SageMake Notebook Instance (or a SageMaker Studio Notebook), you do this one your local machine running Jupyter or from your IDE. Then when you are ready, you kick off your training on SageMaker instances on AWS. Once the training is complete, the model is stored in AWS. You can then kick off a deployment or run a batch transformation job from your local machine. It is recommended that you set this up as a Python virtual environment. In our case we are using conda to manage our virtual environments , but you can also use virtualenv. Amazon SageMaker also uses conda to manage environments and packages. It is assumed that you already have conda setup, if not, head here conda create -n sagemaker python=3 You can use conda or pip to install the packages. We will stick to conda conda install -y pandas numpy matplotlib Install AWS SDK for Python (boto), awscli and SageMaker Python SDK. The SageMaker Python SDK is not available as conda package, so we will use pip here pip install boto3 awscli sagemaker If you are using the awscli for the first time, you must configure it. See here on how to configure the awscli By default the version 2 of the SageMaker Python SDK will be installed. Be sure to check for the changes in the version 2 of the SDK, specially the breaking changes here. conda install -c conda-forge jupyterlabpython -m ipykernel install --user --name sagemaker Start Jupyter by issuing an jupyter lab and choose the sagemaker kernel created above Next verify the versions in the notebook to make sure everything is as expected. You can now start building your model locally and kick off training on AWS when ready Import the necessary packages and specify the role. The key difference here is to specify the arn of the role directly instead of get_execution_role(). Since you are running this from your local machine using your AWS credentials as opposed to a notebook instance with an attached role, get_execution_role() will not work. Create the estimator and set hyperparameters as you would normally. In the example below, we are training an image classifier using the built in image classification algorithm. You also specify the type of SageMaker instance and number of instances you want to use for training Specify the training channels, again no changes here compared to how you would do this on a notebook instance Start the training job on SageMaker calling the fit method which kicks off the training job on SageMaker instances on AWS classifier.fit(inputs=data_channels, logs=True) You can check the status of your training jobs using list-training-jobs That’s it. Here we saw how you can setup a SageMaker environment locally and build machine learning models on your local machine using Jupyter. In addition to using Jupyter, you can also do the same from your IDE.
[ { "code": null, "e": 636, "s": 172, "text": "Amazon SageMaker is beyond just managed Jupyter notebooks, it is a fully managed service that enables you to build, train, optimize and deploy machine learning models. A common misconception, specially when you are starting out with SageMaker is that, in order to use these services, you need a SageMaker Notebook Instance or SageMaker (Studio) Notebook. You can in fact kick off all these services directly from your local machine or even from your favorite IDE." }, { "code": null, "e": 739, "s": 636, "text": "Before we go further, let’s consider how we interact with Amazon SageMaker services. You have two APIs" }, { "code": null, "e": 1098, "s": 739, "text": "SageMaker Python SDK — This is a high level API in Python that abstracts the code to build, train and deploy machine learning models. Specifically it provides estimators for first class or built in algorithms as well as supported frameworks like TensorFlow, MXNET etc. In most cases you will use this to interact with your interactive machine learning tasks." }, { "code": null, "e": 1515, "s": 1098, "text": "AWS SDK — This is a low level API that is used to interact with all supported AWS services, not specific to SageMaker. The AWS SDK is available in most popular programming languages like Java, Javascript, Python (boto) etc. In most cases you will use this service-level APIs for things such creating resources for automations or interacting with other AWS services that are not supported by the SageMaker Python SDK." }, { "code": null, "e": 1698, "s": 1515, "text": "Cost is probably the first thing that comes up, but it is also the flexibility to use your own IDE plus the ability to work offline and kick off jobs on AWS cloud when you are ready." }, { "code": null, "e": 2142, "s": 1698, "text": "You write the code to build your model as you normally would but instead of a SageMake Notebook Instance (or a SageMaker Studio Notebook), you do this one your local machine running Jupyter or from your IDE. Then when you are ready, you kick off your training on SageMaker instances on AWS. Once the training is complete, the model is stored in AWS. You can then kick off a deployment or run a batch transformation job from your local machine." }, { "code": null, "e": 2452, "s": 2142, "text": "It is recommended that you set this up as a Python virtual environment. In our case we are using conda to manage our virtual environments , but you can also use virtualenv. Amazon SageMaker also uses conda to manage environments and packages. It is assumed that you already have conda setup, if not, head here" }, { "code": null, "e": 2487, "s": 2452, "text": "conda create -n sagemaker python=3" }, { "code": null, "e": 2560, "s": 2487, "text": "You can use conda or pip to install the packages. We will stick to conda" }, { "code": null, "e": 2601, "s": 2560, "text": "conda install -y pandas numpy matplotlib" }, { "code": null, "e": 2753, "s": 2601, "text": "Install AWS SDK for Python (boto), awscli and SageMaker Python SDK. The SageMaker Python SDK is not available as conda package, so we will use pip here" }, { "code": null, "e": 2788, "s": 2753, "text": "pip install boto3 awscli sagemaker" }, { "code": null, "e": 2899, "s": 2788, "text": "If you are using the awscli for the first time, you must configure it. See here on how to configure the awscli" }, { "code": null, "e": 3070, "s": 2899, "text": "By default the version 2 of the SageMaker Python SDK will be installed. Be sure to check for the changes in the version 2 of the SDK, specially the breaking changes here." }, { "code": null, "e": 3161, "s": 3070, "text": "conda install -c conda-forge jupyterlabpython -m ipykernel install --user --name sagemaker" }, { "code": null, "e": 3247, "s": 3161, "text": "Start Jupyter by issuing an jupyter lab and choose the sagemaker kernel created above" }, { "code": null, "e": 3328, "s": 3247, "text": "Next verify the versions in the notebook to make sure everything is as expected." }, { "code": null, "e": 3414, "s": 3328, "text": "You can now start building your model locally and kick off training on AWS when ready" }, { "code": null, "e": 3737, "s": 3414, "text": "Import the necessary packages and specify the role. The key difference here is to specify the arn of the role directly instead of get_execution_role(). Since you are running this from your local machine using your AWS credentials as opposed to a notebook instance with an attached role, get_execution_role() will not work." }, { "code": null, "e": 4015, "s": 3737, "text": "Create the estimator and set hyperparameters as you would normally. In the example below, we are training an image classifier using the built in image classification algorithm. You also specify the type of SageMaker instance and number of instances you want to use for training" }, { "code": null, "e": 4125, "s": 4015, "text": "Specify the training channels, again no changes here compared to how you would do this on a notebook instance" }, { "code": null, "e": 4247, "s": 4125, "text": "Start the training job on SageMaker calling the fit method which kicks off the training job on SageMaker instances on AWS" }, { "code": null, "e": 4295, "s": 4247, "text": "classifier.fit(inputs=data_channels, logs=True)" }, { "code": null, "e": 4367, "s": 4295, "text": "You can check the status of your training jobs using list-training-jobs" } ]
Count Distinct Rectangles in N*N Chessboard - GeeksforGeeks
27 Apr, 2021 Given a N x N Chessboard. The task is to count distinct rectangles from the chessboard. For example, if the input is 8 then the output should be 36.Examples: Input: N = 4 Output: 10 Input: N = 6 Output: 21 Approach: Suppose N = 8 i.e. 8 x 8 chessboard is given, So different rectangles that can be formed are: 1 x 1, 1 x 2, 1 x 3, 1 x 4, 1 x 5, 1 x 6, 1 x 7, 1 x 8 = 8 2 x 2, 2 x 3, 2 x 4, 2 x 5, 2 x 6, 2 x 7, 2 x 8 = 7 3 x 3, 3 x 4, 3 x 5, 3 x 6, 2 x 7, 3 x 8 = 6 4 x 4, 4 x 5, 4 x 6, 4 x 7, 4 x 8 = 5 5 x 5, 5 x 6, 5 x 7, 5 x 8 = 4 6 x 6, 6 x 7, 6 x 8 = 3 7 x 7, 7 x 8 = 2 8 x 8 = 1 So total unique rectangles formed = 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36 which is the sum of the first 8 natural numbers. So in general, distinct rectangles that can be formed in N x N chessboard is: Sum of the first N natural numbers = N*(N+1)/2 = 8*(8+1)/2 = 36 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to count distinct rectangle in a chessboard#include <bits/stdc++.h>using namespace std; // Function to return the count// of distinct rectanglesint count(int N){ int a = 0; a = (N * (N + 1)) / 2; return a;} // Driver Codeint main(){ int N = 4; cout<<count(N);} // This code is contributed by nidhi16bcs2007 // Java program to count unique rectangles in a chessboardclass Rectangle { // Function to count distinct rectangles static int count(int N) { int a = 0; a = (N * (N + 1)) / 2; return a; } // Driver Code public static void main(String args[]) { int n = 4; System.out.print(count(n)); }} # Python code to count distinct rectangle in a chessboard # Function to return the count# of distinct rectanglesdef count(N): a = 0; a = (N * (N + 1)) / 2; return int(a); # Driver CodeN = 4;print(count(N)); # This code has been contributed by 29AjayKumar // C# program to count unique rectangles in a chessboardusing System; class Rectangle{ // Function to count distinct rectangles static int count(int N) { int a = 0; a = (N * (N + 1)) / 2; return a; } // Driver Code public static void Main() { int n = 4; Console.Write(count(n)); }} // This code is contributed by AnkitRai01 // Javascript program to count unique rectangles in a chessboard // Function to count distinct rectangles function count(N) { var a = 0; a = (N * (N + 1)) / 2; return a; } // Driver Code var n = 4; document.write(count(n)); // This code is contributed by bunnyram19. 10 nidhiva ankthon 29AjayKumar bunnyram19 Natural Numbers number-theory Mathematical QA - Placement Quizzes number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Fizz Buzz Implementation QA - Placement Quizzes | Mixtures and Alligation | Question 7 QA - Placement Quizzes | Permutation and Combination | Question 3 QA - Placement Quizzes | Work and Wages | Question 1 QA - Placement Quizzes | Permutation and Combination | Question 1 QA - Placement Quizzes | Numbers, LCM and HCF | Question 13
[ { "code": null, "e": 24326, "s": 24298, "text": "\n27 Apr, 2021" }, { "code": null, "e": 24486, "s": 24326, "text": "Given a N x N Chessboard. The task is to count distinct rectangles from the chessboard. For example, if the input is 8 then the output should be 36.Examples: " }, { "code": null, "e": 24536, "s": 24486, "text": "Input: N = 4 \nOutput: 10\n\nInput: N = 6\nOutput: 21" }, { "code": null, "e": 24644, "s": 24538, "text": "Approach: Suppose N = 8 i.e. 8 x 8 chessboard is given, So different rectangles that can be formed are: " }, { "code": null, "e": 25091, "s": 24644, "text": "1 x 1, 1 x 2, 1 x 3, 1 x 4, 1 x 5, 1 x 6, 1 x 7, 1 x 8 = 8\n 2 x 2, 2 x 3, 2 x 4, 2 x 5, 2 x 6, 2 x 7, 2 x 8 = 7 \n 3 x 3, 3 x 4, 3 x 5, 3 x 6, 2 x 7, 3 x 8 = 6 \n 4 x 4, 4 x 5, 4 x 6, 4 x 7, 4 x 8 = 5 \n 5 x 5, 5 x 6, 5 x 7, 5 x 8 = 4\n 6 x 6, 6 x 7, 6 x 8 = 3\n 7 x 7, 7 x 8 = 2\n 8 x 8 = 1" }, { "code": null, "e": 25291, "s": 25091, "text": "So total unique rectangles formed = 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36 which is the sum of the first 8 natural numbers. So in general, distinct rectangles that can be formed in N x N chessboard is: " }, { "code": null, "e": 25425, "s": 25291, "text": "Sum of the first N natural numbers = N*(N+1)/2\n = 8*(8+1)/2\n = 36" }, { "code": null, "e": 25478, "s": 25425, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25482, "s": 25478, "text": "C++" }, { "code": null, "e": 25487, "s": 25482, "text": "Java" }, { "code": null, "e": 25495, "s": 25487, "text": "Python3" }, { "code": null, "e": 25498, "s": 25495, "text": "C#" }, { "code": null, "e": 25509, "s": 25498, "text": "Javascript" }, { "code": "// C++ code to count distinct rectangle in a chessboard#include <bits/stdc++.h>using namespace std; // Function to return the count// of distinct rectanglesint count(int N){ int a = 0; a = (N * (N + 1)) / 2; return a;} // Driver Codeint main(){ int N = 4; cout<<count(N);} // This code is contributed by nidhi16bcs2007", "e": 25843, "s": 25509, "text": null }, { "code": "// Java program to count unique rectangles in a chessboardclass Rectangle { // Function to count distinct rectangles static int count(int N) { int a = 0; a = (N * (N + 1)) / 2; return a; } // Driver Code public static void main(String args[]) { int n = 4; System.out.print(count(n)); }}", "e": 26193, "s": 25843, "text": null }, { "code": " # Python code to count distinct rectangle in a chessboard # Function to return the count# of distinct rectanglesdef count(N): a = 0; a = (N * (N + 1)) / 2; return int(a); # Driver CodeN = 4;print(count(N)); # This code has been contributed by 29AjayKumar", "e": 26462, "s": 26193, "text": null }, { "code": "// C# program to count unique rectangles in a chessboardusing System; class Rectangle{ // Function to count distinct rectangles static int count(int N) { int a = 0; a = (N * (N + 1)) / 2; return a; } // Driver Code public static void Main() { int n = 4; Console.Write(count(n)); }} // This code is contributed by AnkitRai01", "e": 26849, "s": 26462, "text": null }, { "code": "// Javascript program to count unique rectangles in a chessboard // Function to count distinct rectangles function count(N) { var a = 0; a = (N * (N + 1)) / 2; return a; } // Driver Code var n = 4; document.write(count(n)); // This code is contributed by bunnyram19. ", "e": 27178, "s": 26849, "text": null }, { "code": null, "e": 27181, "s": 27178, "text": "10" }, { "code": null, "e": 27191, "s": 27183, "text": "nidhiva" }, { "code": null, "e": 27199, "s": 27191, "text": "ankthon" }, { "code": null, "e": 27211, "s": 27199, "text": "29AjayKumar" }, { "code": null, "e": 27222, "s": 27211, "text": "bunnyram19" }, { "code": null, "e": 27238, "s": 27222, "text": "Natural Numbers" }, { "code": null, "e": 27252, "s": 27238, "text": "number-theory" }, { "code": null, "e": 27265, "s": 27252, "text": "Mathematical" }, { "code": null, "e": 27288, "s": 27265, "text": "QA - Placement Quizzes" }, { "code": null, "e": 27302, "s": 27288, "text": "number-theory" }, { "code": null, "e": 27315, "s": 27302, "text": "Mathematical" }, { "code": null, "e": 27413, "s": 27315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27422, "s": 27413, "text": "Comments" }, { "code": null, "e": 27435, "s": 27422, "text": "Old Comments" }, { "code": null, "e": 27480, "s": 27435, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 27512, "s": 27480, "text": "Check if a number is Palindrome" }, { "code": null, "e": 27556, "s": 27512, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 27590, "s": 27556, "text": "Program to add two binary strings" }, { "code": null, "e": 27615, "s": 27590, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 27677, "s": 27615, "text": "QA - Placement Quizzes | Mixtures and Alligation | Question 7" }, { "code": null, "e": 27743, "s": 27677, "text": "QA - Placement Quizzes | Permutation and Combination | Question 3" }, { "code": null, "e": 27796, "s": 27743, "text": "QA - Placement Quizzes | Work and Wages | Question 1" }, { "code": null, "e": 27862, "s": 27796, "text": "QA - Placement Quizzes | Permutation and Combination | Question 1" } ]
Python File fileno() Method
Python file method fileno() returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system. Following is the syntax for fileno() method − fileObject.fileno(); NA NA This method returns the integer file descriptor. The following example shows the usage of fileno() method. #!/usr/bin/python # Open a file fo = open("foo.txt", "wb") print "Name of the file: ", fo.name fid = fo.fileno() print "File Descriptor: ", fid # Close opend file fo.close() When we run above program, it produces following result − Name of the file: foo.txt File Descriptor: 3 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2407, "s": 2244, "text": "Python file method fileno() returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system." }, { "code": null, "e": 2453, "s": 2407, "text": "Following is the syntax for fileno() method −" }, { "code": null, "e": 2476, "s": 2453, "text": "fileObject.fileno(); \n" }, { "code": null, "e": 2479, "s": 2476, "text": "NA" }, { "code": null, "e": 2482, "s": 2479, "text": "NA" }, { "code": null, "e": 2531, "s": 2482, "text": "This method returns the integer file descriptor." }, { "code": null, "e": 2589, "s": 2531, "text": "The following example shows the usage of fileno() method." }, { "code": null, "e": 2766, "s": 2589, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\n\nfid = fo.fileno()\nprint \"File Descriptor: \", fid\n\n# Close opend file\nfo.close()" }, { "code": null, "e": 2824, "s": 2766, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 2872, "s": 2824, "text": "Name of the file: foo.txt\nFile Descriptor: 3\n" }, { "code": null, "e": 2909, "s": 2872, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2925, "s": 2909, "text": " Malhar Lathkar" }, { "code": null, "e": 2958, "s": 2925, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2977, "s": 2958, "text": " Arnab Chakraborty" }, { "code": null, "e": 3012, "s": 2977, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3034, "s": 3012, "text": " In28Minutes Official" }, { "code": null, "e": 3068, "s": 3034, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3096, "s": 3068, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3131, "s": 3096, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3145, "s": 3131, "text": " Lets Kode It" }, { "code": null, "e": 3178, "s": 3145, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3195, "s": 3178, "text": " Abhilash Nelson" }, { "code": null, "e": 3202, "s": 3195, "text": " Print" }, { "code": null, "e": 3213, "s": 3202, "text": " Add Notes" } ]
Isupper() and Islower() and their application in C++
The functions isupper() and islower() in C++ are inbuilt functions present in “ctype.h” header file. It checks whether the given character or string is in uppercase or lowercase. This function is used to check whether the given string contains any uppercase letter or not and also if we have one character as an input then it checks whether the character is in uppercase or not. int isupper ( int arg) This function has return type as int as it returns non zero value when the string contains uppercase letter and 0 otherwise. It has one parameter which will contain the character to be checked. Input − string s = “HELLo” Output − It contains uppercase letter Input − string s = “hello” Output − It doesn’t contains uppercase letter The function given below will check the string whether it contains uppercase letter or not and if it contains uppercase letter then it will convert them to a lowercase. Live Demo #include <stdio.h> #include <ctype.h> int main (){ int i=0; char str[]="Test String.\n"; char c; while (str[i]){ c=str[i]; if (isupper(c)) c=tolower(c); putchar (c); i++; } return 0; } If we run the above code it will generate the following output − test string. This function is used to check whether the given string contains any lowercase letter or not and also if we have one character as an input then it checks whether the character is in lowercase or not. int islower( int arg) This function has return type as int as it returns non zero value when the string contains lowercase letter and 0 otherwise. It has one parameter which will contain the character to be checked. Input − string s = “HELLo” Output − It contains lowercase letter Input − string s = “hello” Output − It doesn’t contains lowercase letter The function given below will check the string whether it contains lowercase letter or not and if it contains lowercase letter then it will convert them to a uppercase. Live Demo #include <stdio.h> #include <ctype.h> int main (){ int i=0; char str[]="Test String.\n"; char c; while (str[i]) { c=str[i]; if (islower(c)) c=toupper(c); putchar (c); i++; } return 0; } If we run the above code it will generate the following output − TEST STRING.
[ { "code": null, "e": 1241, "s": 1062, "text": "The functions isupper() and islower() in C++ are inbuilt functions present in “ctype.h” header file. It checks whether the given character or string is in uppercase or lowercase." }, { "code": null, "e": 1441, "s": 1241, "text": "This function is used to check whether the given string contains any uppercase letter or not and also if we have one character as an input then it checks whether the character is in uppercase or not." }, { "code": null, "e": 1464, "s": 1441, "text": "int isupper ( int arg)" }, { "code": null, "e": 1658, "s": 1464, "text": "This function has return type as int as it returns non zero value when the string contains uppercase letter and 0 otherwise. It has one parameter which will contain the character to be checked." }, { "code": null, "e": 1685, "s": 1658, "text": "Input − string s = “HELLo”" }, { "code": null, "e": 1723, "s": 1685, "text": "Output − It contains uppercase letter" }, { "code": null, "e": 1750, "s": 1723, "text": "Input − string s = “hello”" }, { "code": null, "e": 1796, "s": 1750, "text": "Output − It doesn’t contains uppercase letter" }, { "code": null, "e": 1965, "s": 1796, "text": "The function given below will check the string whether it contains uppercase letter or not and if it contains uppercase letter then it will convert them to a lowercase." }, { "code": null, "e": 1976, "s": 1965, "text": " Live Demo" }, { "code": null, "e": 2209, "s": 1976, "text": "#include <stdio.h>\n#include <ctype.h>\nint main (){\n int i=0;\n char str[]=\"Test String.\\n\";\n char c;\n while (str[i]){\n c=str[i];\n if (isupper(c)) c=tolower(c);\n putchar (c);\n i++;\n }\n return 0;\n}" }, { "code": null, "e": 2274, "s": 2209, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2287, "s": 2274, "text": "test string." }, { "code": null, "e": 2487, "s": 2287, "text": "This function is used to check whether the given string contains any lowercase letter or not and also if we have one character as an input then it checks whether the character is in lowercase or not." }, { "code": null, "e": 2509, "s": 2487, "text": "int islower( int arg)" }, { "code": null, "e": 2703, "s": 2509, "text": "This function has return type as int as it returns non zero value when the string contains lowercase letter and 0 otherwise. It has one parameter which will contain the character to be checked." }, { "code": null, "e": 2730, "s": 2703, "text": "Input − string s = “HELLo”" }, { "code": null, "e": 2768, "s": 2730, "text": "Output − It contains lowercase letter" }, { "code": null, "e": 2795, "s": 2768, "text": "Input − string s = “hello”" }, { "code": null, "e": 2841, "s": 2795, "text": "Output − It doesn’t contains lowercase letter" }, { "code": null, "e": 3010, "s": 2841, "text": "The function given below will check the string whether it contains lowercase letter or not and if it contains lowercase letter then it will convert them to a uppercase." }, { "code": null, "e": 3021, "s": 3010, "text": " Live Demo" }, { "code": null, "e": 3255, "s": 3021, "text": "#include <stdio.h>\n#include <ctype.h>\nint main (){\n int i=0;\n char str[]=\"Test String.\\n\";\n char c;\n while (str[i]) {\n c=str[i];\n if (islower(c)) c=toupper(c);\n putchar (c);\n i++;\n }\n return 0;\n}" }, { "code": null, "e": 3321, "s": 3255, "text": "If we run the above code it will generate the following output − " }, { "code": null, "e": 3334, "s": 3321, "text": "TEST STRING." } ]
Implementation of Whale Optimization Algorithm - GeeksforGeeks
13 Dec, 2021 Previous article Whale optimization algorithm (WOA) talked about the inspiration of whale optimization, its mathematical modeling and algorithm. In this article we will implement a whale optimization algorithm (WOA) for two fitness functions 1) Rastrigin function 2) Sphere function The algorithm will run for a predefined number of maximum iterations and will try to find the minimum value of these fitness functions. Rastrigin function is a non-convex function and is often used as a performance test problem for optimization algorithms. Fig1: Rastrigin function for 2 variables For an optimization algorithm, rastrigin function is a very challenging one. Its complex behavior causes optimization algorithms to often be stuck at local minima. Having a lot of cosine oscillations on the plane introduces the complex behavior to this function. Sphere function is a standard function for evaluating the performance of an optimization algorithm. Fig 2: Sphere function for 2 variables Number of dimensions (d) = 3 Lower bound (minx) = -10.0 Upper bound (maxx) = 10.0 Number of particles (N) = 50 Maximum number of iterations (max_iter) = 100 spiral coefficient (b) = 1 Fitness function Problem parameters ( mentioned above) Population size (N) and Maximum number of iterations (max_iter) Algorithm Specific hyperparameter b The algorithm of the whale optimization and mathematical equations are already described in the previous article. Python3 # python implementation of whale optimization algorithm (WOA)# minimizing rastrigin and sphere function import randomimport math # cos() for Rastriginimport copy # array-copying convenienceimport sys # max float # -------fitness functions--------- # rastrigin functiondef fitness_rastrigin(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi * xi) - (10 * math.cos(2 * math.pi * xi)) + 10 return fitness_value # sphere functiondef fitness_sphere(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi * xi); return fitness_value; # ------------------------- # whale classclass whale: def __init__(self, fitness, dim, minx, maxx, seed): self.rnd = random.Random(seed) self.position = [0.0 for i in range(dim)] for i in range(dim): self.position[i] = ((maxx - minx) * self.rnd.random() + minx) self.fitness = fitness(self.position) # curr fitness # whale optimization algorithm(WOA)def woa(fitness, max_iter, n, dim, minx, maxx): rnd = random.Random(0) # create n random whales whalePopulation = [whale(fitness, dim, minx, maxx, i) for i in range(n)] # compute the value of best_position and best_fitness in the whale Population Xbest = [0.0 for i in range(dim)] Fbest = sys.float_info.max for i in range(n): # check each whale if whalePopulation[i].fitness < Fbest: Fbest = whalePopulation[i].fitness Xbest = copy.copy(whalePopulation[i].position) # main loop of woa Iter = 0 while Iter < max_iter: # after every 10 iterations # print iteration number and best fitness value so far if Iter % 10 == 0 and Iter > 1: print("Iter = " + str(Iter) + " best fitness = %.3f" % Fbest) # linearly decreased from 2 to 0 a = 2 * (1 - Iter / max_iter) a2=-1+Iter*((-1)/max_iter) for i in range(n): A = 2 * a * rnd.random() - a C = 2 * rnd.random() b = 1 l = (a2-1)*rnd.random()+1; p = rnd.random() D = [0.0 for i in range(dim)] D1 = [0.0 for i in range(dim)] Xnew = [0.0 for i in range(dim)] Xrand = [0.0 for i in range(dim)] if p < 0.5: if abs(A) > 1: for j in range(dim): D[j] = abs(C * Xbest[j] - whalePopulation[i].position[j]) Xnew[j] = Xbest[j] - A * D[j] else: p = random.randint(0, n - 1) while (p == i): p = random.randint(0, n - 1) Xrand = whalePopulation[p].position for j in range(dim): D[j] = abs(C * Xrand[j] - whalePopulation[i].position[j]) Xnew[j] = Xrand[j] - A * D[j] else: for j in range(dim): D1[j] = abs(Xbest[j] - whalePopulation[i].position[j]) Xnew[j] = D1[j] * math.exp(b * l) * math.cos(2 * math.pi * l) + Xbest[j] for j in range(dim): whalePopulation[i].position[j] = Xnew[j] for i in range(n): # if Xnew < minx OR Xnew > maxx # then clip it for j in range(dim): whalePopulation[i].position[j] = max(whalePopulation[i].position[j], minx) whalePopulation[i].position[j] = min(whalePopulation[i].position[j], maxx) whalePopulation[i].fitness = fitness(whalePopulation[i].position) if (whalePopulation[i].fitness < Fbest): Xbest = copy.copy(whalePopulation[i].position) Fbest = whalePopulation[i].fitness Iter += 1 # end-while # returning the best solution return Xbest # ---------------------------- # Driver code for rastrigin function print("\nBegin whale optimization algorithm on rastrigin function\n")dim = 3fitness = fitness_rastrigin print("Goal is to minimize Rastrigin's function in " + str(dim) + " variables")print("Function has known min = 0.0 at (", end="")for i in range(dim - 1): print("0, ", end="")print("0)") num_whales = 50max_iter = 100 print("Setting num_whales = " + str(num_whales))print("Setting max_iter = " + str(max_iter))print("\nStarting WOA algorithm\n") best_position = woa(fitness, max_iter, num_whales, dim, -10.0, 10.0) print("\nWOA completed\n")print("\nBest solution found:")print(["%.6f" % best_position[k] for k in range(dim)])err = fitness(best_position)print("fitness of best solution = %.6f" % err) print("\nEnd WOA for rastrigin\n") print()print() # Driver code for Sphere functionprint("\nBegin whale optimization algorithm on sphere function\n")dim = 3fitness = fitness_sphere print("Goal is to minimize sphere function in " + str(dim) + " variables")print("Function has known min = 0.0 at (", end="")for i in range(dim - 1): print("0, ", end="")print("0)") num_whales = 50max_iter = 100 print("Setting num_whales = " + str(num_whales))print("Setting max_iter = " + str(max_iter))print("\nStarting WOA algorithm\n") best_position = woa(fitness, max_iter, num_whales, dim, -10.0, 10.0) print("\nWOA completed\n")print("\nBest solution found:")print(["%.6f" % best_position[k] for k in range(dim)])err = fitness(best_position)print("fitness of best solution = %.6f" % err) print("\nEnd WOA for sphere\n") Begin whale optimization algorithm on rastrigin function Goal is to minimize Rastrigin's function in 3 variables Function has known min = 0.0 at (0, 0, 0) Setting num_whales = 50 Setting max_iter = 100 Starting WOA algorithm Iter = 10 best fitness = 0.018 Iter = 20 best fitness = 0.000 Iter = 30 best fitness = 0.000 Iter = 40 best fitness = 0.000 Iter = 50 best fitness = 0.000 Iter = 60 best fitness = 0.000 Iter = 70 best fitness = 0.000 Iter = 80 best fitness = 0.000 Iter = 90 best fitness = 0.000 WOA completed Best solution found: ['0.000000', '-0.000000', '-0.000000'] fitness of best solution = 0.000000 End WOA for rastrigin Begin whale optimization algorithm on sphere function Goal is to minimize sphere function in 3 variables Function has known min = 0.0 at (0, 0, 0) Setting num_whales = 50 Setting max_iter = 100 Starting WOA algorithm Iter = 10 best fitness = 0.130 Iter = 20 best fitness = 0.000 Iter = 30 best fitness = 0.000 Iter = 40 best fitness = 0.000 Iter = 50 best fitness = 0.000 Iter = 60 best fitness = 0.000 Iter = 70 best fitness = 0.000 Iter = 80 best fitness = 0.000 Iter = 90 best fitness = 0.000 WOA completed Best solution found: ['0.000000', '0.000000', '-0.000000'] fitness of best solution = 0.000000 End WOA for sphere Research paper: https://www.sciencedirect.com/science/article/pii/S0965997816300163 Author’s original implementation (in MATLAB): https://www.mathworks.com/matlabcentral/fileexchange/55667-the-whale-optimization-algorithm surindertarika1234 ddeevviissaavviittaa Artificial Intelligence Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 23953, "s": 23925, "text": "\n13 Dec, 2021" }, { "code": null, "e": 24376, "s": 23953, "text": "Previous article Whale optimization algorithm (WOA) talked about the inspiration of whale optimization, its mathematical modeling and algorithm. In this article we will implement a whale optimization algorithm (WOA) for two fitness functions 1) Rastrigin function 2) Sphere function The algorithm will run for a predefined number of maximum iterations and will try to find the minimum value of these fitness functions." }, { "code": null, "e": 24497, "s": 24376, "text": "Rastrigin function is a non-convex function and is often used as a performance test problem for optimization algorithms." }, { "code": null, "e": 24538, "s": 24497, "text": "Fig1: Rastrigin function for 2 variables" }, { "code": null, "e": 24801, "s": 24538, "text": "For an optimization algorithm, rastrigin function is a very challenging one. Its complex behavior causes optimization algorithms to often be stuck at local minima. Having a lot of cosine oscillations on the plane introduces the complex behavior to this function." }, { "code": null, "e": 24901, "s": 24801, "text": "Sphere function is a standard function for evaluating the performance of an optimization algorithm." }, { "code": null, "e": 24940, "s": 24901, "text": "Fig 2: Sphere function for 2 variables" }, { "code": null, "e": 24969, "s": 24940, "text": "Number of dimensions (d) = 3" }, { "code": null, "e": 24996, "s": 24969, "text": "Lower bound (minx) = -10.0" }, { "code": null, "e": 25022, "s": 24996, "text": "Upper bound (maxx) = 10.0" }, { "code": null, "e": 25051, "s": 25022, "text": "Number of particles (N) = 50" }, { "code": null, "e": 25097, "s": 25051, "text": "Maximum number of iterations (max_iter) = 100" }, { "code": null, "e": 25124, "s": 25097, "text": "spiral coefficient (b) = 1" }, { "code": null, "e": 25141, "s": 25124, "text": "Fitness function" }, { "code": null, "e": 25179, "s": 25141, "text": "Problem parameters ( mentioned above)" }, { "code": null, "e": 25244, "s": 25179, "text": "Population size (N) and Maximum number of iterations (max_iter)" }, { "code": null, "e": 25280, "s": 25244, "text": "Algorithm Specific hyperparameter b" }, { "code": null, "e": 25395, "s": 25280, "text": "The algorithm of the whale optimization and mathematical equations are already described in the previous article. " }, { "code": null, "e": 25403, "s": 25395, "text": "Python3" }, { "code": "# python implementation of whale optimization algorithm (WOA)# minimizing rastrigin and sphere function import randomimport math # cos() for Rastriginimport copy # array-copying convenienceimport sys # max float # -------fitness functions--------- # rastrigin functiondef fitness_rastrigin(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi * xi) - (10 * math.cos(2 * math.pi * xi)) + 10 return fitness_value # sphere functiondef fitness_sphere(position): fitness_value = 0.0 for i in range(len(position)): xi = position[i] fitness_value += (xi * xi); return fitness_value; # ------------------------- # whale classclass whale: def __init__(self, fitness, dim, minx, maxx, seed): self.rnd = random.Random(seed) self.position = [0.0 for i in range(dim)] for i in range(dim): self.position[i] = ((maxx - minx) * self.rnd.random() + minx) self.fitness = fitness(self.position) # curr fitness # whale optimization algorithm(WOA)def woa(fitness, max_iter, n, dim, minx, maxx): rnd = random.Random(0) # create n random whales whalePopulation = [whale(fitness, dim, minx, maxx, i) for i in range(n)] # compute the value of best_position and best_fitness in the whale Population Xbest = [0.0 for i in range(dim)] Fbest = sys.float_info.max for i in range(n): # check each whale if whalePopulation[i].fitness < Fbest: Fbest = whalePopulation[i].fitness Xbest = copy.copy(whalePopulation[i].position) # main loop of woa Iter = 0 while Iter < max_iter: # after every 10 iterations # print iteration number and best fitness value so far if Iter % 10 == 0 and Iter > 1: print(\"Iter = \" + str(Iter) + \" best fitness = %.3f\" % Fbest) # linearly decreased from 2 to 0 a = 2 * (1 - Iter / max_iter) a2=-1+Iter*((-1)/max_iter) for i in range(n): A = 2 * a * rnd.random() - a C = 2 * rnd.random() b = 1 l = (a2-1)*rnd.random()+1; p = rnd.random() D = [0.0 for i in range(dim)] D1 = [0.0 for i in range(dim)] Xnew = [0.0 for i in range(dim)] Xrand = [0.0 for i in range(dim)] if p < 0.5: if abs(A) > 1: for j in range(dim): D[j] = abs(C * Xbest[j] - whalePopulation[i].position[j]) Xnew[j] = Xbest[j] - A * D[j] else: p = random.randint(0, n - 1) while (p == i): p = random.randint(0, n - 1) Xrand = whalePopulation[p].position for j in range(dim): D[j] = abs(C * Xrand[j] - whalePopulation[i].position[j]) Xnew[j] = Xrand[j] - A * D[j] else: for j in range(dim): D1[j] = abs(Xbest[j] - whalePopulation[i].position[j]) Xnew[j] = D1[j] * math.exp(b * l) * math.cos(2 * math.pi * l) + Xbest[j] for j in range(dim): whalePopulation[i].position[j] = Xnew[j] for i in range(n): # if Xnew < minx OR Xnew > maxx # then clip it for j in range(dim): whalePopulation[i].position[j] = max(whalePopulation[i].position[j], minx) whalePopulation[i].position[j] = min(whalePopulation[i].position[j], maxx) whalePopulation[i].fitness = fitness(whalePopulation[i].position) if (whalePopulation[i].fitness < Fbest): Xbest = copy.copy(whalePopulation[i].position) Fbest = whalePopulation[i].fitness Iter += 1 # end-while # returning the best solution return Xbest # ---------------------------- # Driver code for rastrigin function print(\"\\nBegin whale optimization algorithm on rastrigin function\\n\")dim = 3fitness = fitness_rastrigin print(\"Goal is to minimize Rastrigin's function in \" + str(dim) + \" variables\")print(\"Function has known min = 0.0 at (\", end=\"\")for i in range(dim - 1): print(\"0, \", end=\"\")print(\"0)\") num_whales = 50max_iter = 100 print(\"Setting num_whales = \" + str(num_whales))print(\"Setting max_iter = \" + str(max_iter))print(\"\\nStarting WOA algorithm\\n\") best_position = woa(fitness, max_iter, num_whales, dim, -10.0, 10.0) print(\"\\nWOA completed\\n\")print(\"\\nBest solution found:\")print([\"%.6f\" % best_position[k] for k in range(dim)])err = fitness(best_position)print(\"fitness of best solution = %.6f\" % err) print(\"\\nEnd WOA for rastrigin\\n\") print()print() # Driver code for Sphere functionprint(\"\\nBegin whale optimization algorithm on sphere function\\n\")dim = 3fitness = fitness_sphere print(\"Goal is to minimize sphere function in \" + str(dim) + \" variables\")print(\"Function has known min = 0.0 at (\", end=\"\")for i in range(dim - 1): print(\"0, \", end=\"\")print(\"0)\") num_whales = 50max_iter = 100 print(\"Setting num_whales = \" + str(num_whales))print(\"Setting max_iter = \" + str(max_iter))print(\"\\nStarting WOA algorithm\\n\") best_position = woa(fitness, max_iter, num_whales, dim, -10.0, 10.0) print(\"\\nWOA completed\\n\")print(\"\\nBest solution found:\")print([\"%.6f\" % best_position[k] for k in range(dim)])err = fitness(best_position)print(\"fitness of best solution = %.6f\" % err) print(\"\\nEnd WOA for sphere\\n\")", "e": 30884, "s": 25403, "text": null }, { "code": null, "e": 32168, "s": 30884, "text": "Begin whale optimization algorithm on rastrigin function\n\nGoal is to minimize Rastrigin's function in 3 variables\nFunction has known min = 0.0 at (0, 0, 0)\nSetting num_whales = 50\nSetting max_iter = 100\n\nStarting WOA algorithm\n\nIter = 10 best fitness = 0.018\nIter = 20 best fitness = 0.000\nIter = 30 best fitness = 0.000\nIter = 40 best fitness = 0.000\nIter = 50 best fitness = 0.000\nIter = 60 best fitness = 0.000\nIter = 70 best fitness = 0.000\nIter = 80 best fitness = 0.000\nIter = 90 best fitness = 0.000\n\nWOA completed\n\n\nBest solution found:\n['0.000000', '-0.000000', '-0.000000']\nfitness of best solution = 0.000000\n\nEnd WOA for rastrigin\n\n\n\n\nBegin whale optimization algorithm on sphere function\n\nGoal is to minimize sphere function in 3 variables\nFunction has known min = 0.0 at (0, 0, 0)\nSetting num_whales = 50\nSetting max_iter = 100\n\nStarting WOA algorithm\n\nIter = 10 best fitness = 0.130\nIter = 20 best fitness = 0.000\nIter = 30 best fitness = 0.000\nIter = 40 best fitness = 0.000\nIter = 50 best fitness = 0.000\nIter = 60 best fitness = 0.000\nIter = 70 best fitness = 0.000\nIter = 80 best fitness = 0.000\nIter = 90 best fitness = 0.000\n\nWOA completed\n\n\nBest solution found:\n['0.000000', '0.000000', '-0.000000']\nfitness of best solution = 0.000000\n\nEnd WOA for sphere" }, { "code": null, "e": 32252, "s": 32168, "text": "Research paper: https://www.sciencedirect.com/science/article/pii/S0965997816300163" }, { "code": null, "e": 32390, "s": 32252, "text": "Author’s original implementation (in MATLAB): https://www.mathworks.com/matlabcentral/fileexchange/55667-the-whale-optimization-algorithm" }, { "code": null, "e": 32409, "s": 32390, "text": "surindertarika1234" }, { "code": null, "e": 32430, "s": 32409, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 32454, "s": 32430, "text": "Artificial Intelligence" }, { "code": null, "e": 32471, "s": 32454, "text": "Machine Learning" }, { "code": null, "e": 32478, "s": 32471, "text": "Python" }, { "code": null, "e": 32495, "s": 32478, "text": "Machine Learning" }, { "code": null, "e": 32593, "s": 32495, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32602, "s": 32593, "text": "Comments" }, { "code": null, "e": 32615, "s": 32602, "text": "Old Comments" }, { "code": null, "e": 32671, "s": 32615, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 32713, "s": 32671, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 32746, "s": 32713, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 32774, "s": 32746, "text": "Types of Environments in AI" }, { "code": null, "e": 32813, "s": 32774, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 32841, "s": 32813, "text": "Read JSON file using Python" }, { "code": null, "e": 32891, "s": 32841, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 32913, "s": 32891, "text": "Python map() function" } ]
How to create a product card with CSS?
To create a product card with CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .productCard { box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); max-width: 300px; margin: auto; text-align: center; font-family: arial; background-color: rgb(190, 224, 224); } .productDetails { color: rgb(26, 0, 51); font-weight: bold; font-size: 18px; } button { border: none; outline: 0; display: inline-block; padding: 8px; color: white; background-color: rgb(23, 31, 102); text-align: center; cursor: pointer; width: 100%; font-size: 18px; } button:hover, a:hover { opacity: 0.7; } </style> </head> <body> <h2 style="text-align:center">Product Card Example</h2> <div class="productCard"> <img src="https://images.pexels.com/photos/1152077/pexels-photo-1152077.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" style="width:100%"/> <h1>Leather Bag</h1> <p class="productDetails">Exotic Quality</p> <p>Price 50$</p> <p><button>Buy Now</button></p> </div> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1122, "s": 1062, "text": "To create a product card with CSS, the code is as follows −" }, { "code": null, "e": 1133, "s": 1122, "text": " Live Demo" }, { "code": null, "e": 2266, "s": 1133, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .productCard {\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);\n max-width: 300px;\n margin: auto;\n text-align: center;\n font-family: arial;\n background-color: rgb(190, 224, 224);\n }\n .productDetails {\n color: rgb(26, 0, 51);\n font-weight: bold;\n font-size: 18px;\n }\n button {\n border: none;\n outline: 0;\n display: inline-block;\n padding: 8px;\n color: white;\n background-color: rgb(23, 31, 102);\n text-align: center;\n cursor: pointer;\n width: 100%;\n font-size: 18px;\n }\n button:hover, a:hover {\n opacity: 0.7;\n }\n</style>\n</head>\n<body>\n<h2 style=\"text-align:center\">Product Card Example</h2>\n<div class=\"productCard\">\n<img src=\"https://images.pexels.com/photos/1152077/pexels-photo-1152077.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940\"\nstyle=\"width:100%\"/>\n<h1>Leather Bag</h1>\n<p class=\"productDetails\">Exotic Quality</p>\n<p>Price 50$</p>\n<p><button>Buy Now</button></p>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2317, "s": 2266, "text": "The above code will produce the following output −" } ]
How to Train A Custom Object Detection Model with YOLO v5 | by Jacob Solawetz | Towards Data Science
We will cover the following material and you can jump in wherever you are in the process of creating your object detection model: An Overview of Object Detection About the YOLO v5 Model Collecting Our Training Images Annotating Our Training Images Install YOLO v5 dependencies Download Custom YOLO v5 Object Detection Data Define YOLO v5 Model Configuration and Architecture Train a custom YOLO v5 Detector Evaluate YOLO v5 performance Run YOLO v5 Inference on test images Export Saved YOLO v5 Weights for Future Inference Colab Notebook with YOLOv5 Training Code (I recommend having this open concurrently) Accompanying YOLOv5 YouTube Video if you would like a video walkthrough. Public Blood Cell Detection Dataset Object detection is one of the most popular computer vision models due to its versatility. As I wrote in a previous article breaking down mAP: Object detection models seek to identify the presence of relevant objects in images and classify those objects into relevant classes. For example, in medical images, we want to be able to count the number of red blood cells (RBC), white blood cells (WBC), and platelets in the bloodstream. In order to do this automatically, we need to train an object detection model to recognize each one of those objects and classify them correctly. Our object detector model will separate the bounding box regression from object classifications in different areas of a connected network. YOLOv5 is a recent release of the YOLO family of models. YOLO was initially introduced as the first object detection model that combined bounding box prediction and object classification into a single end to end differentiable network. It was written and is maintained in a framework called Darknet. YOLOv5 is the first of the YOLO models to be written in the PyTorch framework and it is much more lightweight and easy to use. That said, YOLOv5 did not make major architectural changes to the network in YOLOv4 and does not outperform YOLOv4 on a common benchmark, the COCO dataset. I recommend YOLOv5 to you here because I believe it is much easier to get started with and offers you much greater development speed when moving into deployment. If you want to dive deeper into the YOLO models, please see the following posts: YOLOv5 Updates — Note YOLOv5 has improved in the short period of time since I originally wrote this article — I recommend reading about them here. Comparing YOLOv4 and YOLOv5 (good for comparing performance on creating a custom model detector) Explaining YOLOv4 (explaining model architecture — since not much other than framework changed in YOLOv5) How to Train YOLOv4 (you should use this if you are willing to invest the time and you are seeking to do academic research or seeking to build the most accurate realtime detection model that you can.) In order to get your object detector off the ground, you need to first collect training images. You want to think carefully about the task you are trying to achieve and think ahead of time about the aspects of the task your model may find difficult. I recommend narrowing the domain that your model must handle as much as possible to improve your final model’s accuracy. In this tutorial’s case, we have limited the scope of our object detector to only detect cells in the bloodstream. This is a narrow domain that is obtainable with current technologies. To start, I recommend: narrowing your task to only identify 10 or less classes and collecting 50–100 images. try to make sure that the number of objects in each class is evenly distributed. choose objects that are distinguishable. A dataset of mostly cars and only a few jeeps for example will be difficult for your model to master. And of course, if you just want to learn the new technology, you can choose a number of free object detection datasets. Choose BCCD if you want to follow along directly in the tutorial. To train our object detector, we need to supervise its learning with bounding box annotations. We draw a box around each object that we want the detector to see and label each box with the object class that we would like the detector to predict. There are many labeling tools (CVAT, LabelImg, VoTT) and large scale solutions (Scale, AWS Ground Truth, . To get started with a free labeling tool here are two useful guides: CVAT for Computer Vision Annotation LabelImg for Computer Vision Annotation As you are drawing your bound boxes, be sure to follow best practices: Label all the way around the object in question Label occluded objects entirely Avoid too much space around the object in question Ok! Now that we have prepared a dataset we are ready to head into the YOLOv5 training code. Hold on to your dataset, we will soon import it. Open Concurrently: Colab Notebook To Train YOLOv5. In Google Colab, you will receive a free GPU. Be sure to File → save a copy in your drive. Then you will be able to edit the code. To start off with YOLOv5 we first clone the YOLOv5 repository and install dependencies. This will set up our programming environment to be ready to running object detection training and inference commands. !git clone https://github.com/ultralytics/yolov5 # clone repo!pip install -U -r yolov5/requirements.txt # install dependencies%cd /content/yolov5 Then, we can take a look at our training environment provided to us for free from Google Colab. import torchfrom IPython.display import Image # for displaying imagesfrom utils.google_utils import gdrive_download # for downloading models/datasetsprint('torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU')) It is likely that you will receive a Tesla P100 GPU from Google Colab. Here is what I received: torch 1.5.0+cu101 _CudaDeviceProperties(name='Tesla P100-PCIE-16GB', major=6, minor=0, total_memory=16280MB, multi_processor_count=56) The GPU will allow us to accelerate training time. Colab is also nice in that it come preinstalled with torch and cuda. If you are attempting this tutorial on local, there may be additional steps to take to set up YOLOv5. In this tutorial we will download custom object detection data in YOLOv5 format from Roboflow. You can follow along with the public blood cell dataset or upload your own dataset. Once you have labeled data, to get move your data into Roboflow, create a free account and then you can drag your dataset in in any format: (VOC XML, COCO JSON, TensorFlow Object Detection CSV, etc). Once uploaded you can choose preprocessing and augmentation steps: Then, click Generate and Download and you will be able to choose YOLOv5 PyTorch format. When prompted, be sure to select “Show Code Snippet.” This will output a download curl script so you can easily port your data into Colab in the proper format. curl -L "https://public.roboflow.ai/ds/YOUR-LINK-HERE" > roboflow.zip; unzip roboflow.zip; rm roboflow.zip Downloading in Colab... The export creates a YOLOv5 .yaml file called data.yaml specifying the location of a YOLOv5 images folder, a YOLOv5 labels folder, and information on our custom classes. Next we write a model configuration file for our custom object detector. For this tutorial, we chose the smallest, fastest base model of YOLOv5. You have the option to pick from other YOLOv5 models including: YOLOv5s YOLOv5m YOLOv5l YOLOv5x You can also edit the structure of the network in this step, though rarely will you need to do this. Here is the YOLOv5 model configuration file, which we term custom_yolov5s.yaml: nc: 3depth_multiple: 0.33width_multiple: 0.50anchors: - [10,13, 16,30, 33,23] - [30,61, 62,45, 59,119] - [116,90, 156,198, 373,326]backbone: [[-1, 1, Focus, [64, 3]], [-1, 1, Conv, [128, 3, 2]], [-1, 3, Bottleneck, [128]], [-1, 1, Conv, [256, 3, 2]], [-1, 9, BottleneckCSP, [256]], [-1, 1, Conv, [512, 3, 2]], [-1, 9, BottleneckCSP, [512]], [-1, 1, Conv, [1024, 3, 2]], [-1, 1, SPP, [1024, [5, 9, 13]]], [-1, 6, BottleneckCSP, [1024]], ]head: [[-1, 3, BottleneckCSP, [1024, False]], [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], [-2, 1, nn.Upsample, [None, 2, "nearest"]], [[-1, 6], 1, Concat, [1]], [-1, 1, Conv, [512, 1, 1]], [-1, 3, BottleneckCSP, [512, False]], [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], [-2, 1, nn.Upsample, [None, 2, "nearest"]], [[-1, 4], 1, Concat, [1]], [-1, 1, Conv, [256, 1, 1]], [-1, 3, BottleneckCSP, [256, False]], [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]],[[], 1, Detect, [nc, anchors]], ] With our data.yaml and custom_yolov5s.yaml files ready to go we are ready to train! To kick off training we running the training command with the following options: img: define input image size batch: determine batch size epochs: define the number of training epochs. (Note: often, 3000+ are common here!) data: set the path to our yaml file cfg: specify our model configuration weights: specify a custom path to weights. (Note: you can download weights from the Ultralytics Google Drive folder) name: result names nosave: only save the final checkpoint cache: cache images for faster training And run the training command: During training, you want to be watching the mAP@0.5 to see how your detector is learning to detect on your validation set, higher is better! — see this post on breaking down mAP. Now that we have completed training, we can evaluate how well the training procedure performed by looking at the validation metrics. The training script will drop tensorboard logs in runs. We visualize those here: And if you can’t visualize Tensorboard for whatever reason the results can also be plotted with utils.plot_results and saving a result.png. I stopped training a little early here. You want to take the trained model weights at the point where the validation mAP reaches its highest. Now we take our trained model and make inference on test images. After training has completed model weights will save in weights/. For inference we invoke those weights along with a conf specifying model confidence (higher confidence required makes less predictions), and a inference source. source can accept a directory of images, individual images, video files, and also a device's webcam port. For source, I have moved our test/*jpg to test_infer/. !python detect.py --weights weights/last_yolov5s_custom.pt --img 416 --conf 0.4 --source ../test_infer The inference time is extremely fast. On our Tesla P100, the YOLOv5s is hitting 7ms per image. This bodes well for deploying to a smaller GPU like a Jetson Nano (which costs only $100). Finally, we visualize our detectors inferences on test images. Now that our custom YOLOv5 object detector has been verified, we might want to take the weights out of Colab for use on a live computer vision task. To do so we import a Google Drive module and send them out. from google.colab import drivedrive.mount('/content/gdrive')%cp /content/yolov5/weights/last_yolov5s_custom.pt /content/gdrive/My\ Drive We hoped you enjoyed training your custom YOLO v5 object detector! YOLO v5 is lightweight and extremely easy to use. YOLO v5 trains quickly, inferences quickly, and performs well. Let’s get it out there! Next Steps: Stay tuned for future tutorials and how to deploy your new model to production.
[ { "code": null, "e": 302, "s": 172, "text": "We will cover the following material and you can jump in wherever you are in the process of creating your object detection model:" }, { "code": null, "e": 334, "s": 302, "text": "An Overview of Object Detection" }, { "code": null, "e": 358, "s": 334, "text": "About the YOLO v5 Model" }, { "code": null, "e": 389, "s": 358, "text": "Collecting Our Training Images" }, { "code": null, "e": 420, "s": 389, "text": "Annotating Our Training Images" }, { "code": null, "e": 449, "s": 420, "text": "Install YOLO v5 dependencies" }, { "code": null, "e": 495, "s": 449, "text": "Download Custom YOLO v5 Object Detection Data" }, { "code": null, "e": 547, "s": 495, "text": "Define YOLO v5 Model Configuration and Architecture" }, { "code": null, "e": 579, "s": 547, "text": "Train a custom YOLO v5 Detector" }, { "code": null, "e": 608, "s": 579, "text": "Evaluate YOLO v5 performance" }, { "code": null, "e": 645, "s": 608, "text": "Run YOLO v5 Inference on test images" }, { "code": null, "e": 695, "s": 645, "text": "Export Saved YOLO v5 Weights for Future Inference" }, { "code": null, "e": 780, "s": 695, "text": "Colab Notebook with YOLOv5 Training Code (I recommend having this open concurrently)" }, { "code": null, "e": 853, "s": 780, "text": "Accompanying YOLOv5 YouTube Video if you would like a video walkthrough." }, { "code": null, "e": 889, "s": 853, "text": "Public Blood Cell Detection Dataset" }, { "code": null, "e": 1032, "s": 889, "text": "Object detection is one of the most popular computer vision models due to its versatility. As I wrote in a previous article breaking down mAP:" }, { "code": null, "e": 1468, "s": 1032, "text": "Object detection models seek to identify the presence of relevant objects in images and classify those objects into relevant classes. For example, in medical images, we want to be able to count the number of red blood cells (RBC), white blood cells (WBC), and platelets in the bloodstream. In order to do this automatically, we need to train an object detection model to recognize each one of those objects and classify them correctly." }, { "code": null, "e": 1607, "s": 1468, "text": "Our object detector model will separate the bounding box regression from object classifications in different areas of a connected network." }, { "code": null, "e": 2190, "s": 1607, "text": "YOLOv5 is a recent release of the YOLO family of models. YOLO was initially introduced as the first object detection model that combined bounding box prediction and object classification into a single end to end differentiable network. It was written and is maintained in a framework called Darknet. YOLOv5 is the first of the YOLO models to be written in the PyTorch framework and it is much more lightweight and easy to use. That said, YOLOv5 did not make major architectural changes to the network in YOLOv4 and does not outperform YOLOv4 on a common benchmark, the COCO dataset." }, { "code": null, "e": 2352, "s": 2190, "text": "I recommend YOLOv5 to you here because I believe it is much easier to get started with and offers you much greater development speed when moving into deployment." }, { "code": null, "e": 2433, "s": 2352, "text": "If you want to dive deeper into the YOLO models, please see the following posts:" }, { "code": null, "e": 2580, "s": 2433, "text": "YOLOv5 Updates — Note YOLOv5 has improved in the short period of time since I originally wrote this article — I recommend reading about them here." }, { "code": null, "e": 2677, "s": 2580, "text": "Comparing YOLOv4 and YOLOv5 (good for comparing performance on creating a custom model detector)" }, { "code": null, "e": 2783, "s": 2677, "text": "Explaining YOLOv4 (explaining model architecture — since not much other than framework changed in YOLOv5)" }, { "code": null, "e": 2984, "s": 2783, "text": "How to Train YOLOv4 (you should use this if you are willing to invest the time and you are seeking to do academic research or seeking to build the most accurate realtime detection model that you can.)" }, { "code": null, "e": 3355, "s": 2984, "text": "In order to get your object detector off the ground, you need to first collect training images. You want to think carefully about the task you are trying to achieve and think ahead of time about the aspects of the task your model may find difficult. I recommend narrowing the domain that your model must handle as much as possible to improve your final model’s accuracy." }, { "code": null, "e": 3540, "s": 3355, "text": "In this tutorial’s case, we have limited the scope of our object detector to only detect cells in the bloodstream. This is a narrow domain that is obtainable with current technologies." }, { "code": null, "e": 3563, "s": 3540, "text": "To start, I recommend:" }, { "code": null, "e": 3649, "s": 3563, "text": "narrowing your task to only identify 10 or less classes and collecting 50–100 images." }, { "code": null, "e": 3730, "s": 3649, "text": "try to make sure that the number of objects in each class is evenly distributed." }, { "code": null, "e": 3873, "s": 3730, "text": "choose objects that are distinguishable. A dataset of mostly cars and only a few jeeps for example will be difficult for your model to master." }, { "code": null, "e": 4059, "s": 3873, "text": "And of course, if you just want to learn the new technology, you can choose a number of free object detection datasets. Choose BCCD if you want to follow along directly in the tutorial." }, { "code": null, "e": 4305, "s": 4059, "text": "To train our object detector, we need to supervise its learning with bounding box annotations. We draw a box around each object that we want the detector to see and label each box with the object class that we would like the detector to predict." }, { "code": null, "e": 4481, "s": 4305, "text": "There are many labeling tools (CVAT, LabelImg, VoTT) and large scale solutions (Scale, AWS Ground Truth, . To get started with a free labeling tool here are two useful guides:" }, { "code": null, "e": 4517, "s": 4481, "text": "CVAT for Computer Vision Annotation" }, { "code": null, "e": 4557, "s": 4517, "text": "LabelImg for Computer Vision Annotation" }, { "code": null, "e": 4628, "s": 4557, "text": "As you are drawing your bound boxes, be sure to follow best practices:" }, { "code": null, "e": 4676, "s": 4628, "text": "Label all the way around the object in question" }, { "code": null, "e": 4708, "s": 4676, "text": "Label occluded objects entirely" }, { "code": null, "e": 4759, "s": 4708, "text": "Avoid too much space around the object in question" }, { "code": null, "e": 4900, "s": 4759, "text": "Ok! Now that we have prepared a dataset we are ready to head into the YOLOv5 training code. Hold on to your dataset, we will soon import it." }, { "code": null, "e": 4951, "s": 4900, "text": "Open Concurrently: Colab Notebook To Train YOLOv5." }, { "code": null, "e": 5082, "s": 4951, "text": "In Google Colab, you will receive a free GPU. Be sure to File → save a copy in your drive. Then you will be able to edit the code." }, { "code": null, "e": 5288, "s": 5082, "text": "To start off with YOLOv5 we first clone the YOLOv5 repository and install dependencies. This will set up our programming environment to be ready to running object detection training and inference commands." }, { "code": null, "e": 5436, "s": 5288, "text": "!git clone https://github.com/ultralytics/yolov5 # clone repo!pip install -U -r yolov5/requirements.txt # install dependencies%cd /content/yolov5" }, { "code": null, "e": 5532, "s": 5436, "text": "Then, we can take a look at our training environment provided to us for free from Google Colab." }, { "code": null, "e": 5803, "s": 5532, "text": "import torchfrom IPython.display import Image # for displaying imagesfrom utils.google_utils import gdrive_download # for downloading models/datasetsprint('torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU'))" }, { "code": null, "e": 5899, "s": 5803, "text": "It is likely that you will receive a Tesla P100 GPU from Google Colab. Here is what I received:" }, { "code": null, "e": 6034, "s": 5899, "text": "torch 1.5.0+cu101 _CudaDeviceProperties(name='Tesla P100-PCIE-16GB', major=6, minor=0, total_memory=16280MB, multi_processor_count=56)" }, { "code": null, "e": 6256, "s": 6034, "text": "The GPU will allow us to accelerate training time. Colab is also nice in that it come preinstalled with torch and cuda. If you are attempting this tutorial on local, there may be additional steps to take to set up YOLOv5." }, { "code": null, "e": 6435, "s": 6256, "text": "In this tutorial we will download custom object detection data in YOLOv5 format from Roboflow. You can follow along with the public blood cell dataset or upload your own dataset." }, { "code": null, "e": 6635, "s": 6435, "text": "Once you have labeled data, to get move your data into Roboflow, create a free account and then you can drag your dataset in in any format: (VOC XML, COCO JSON, TensorFlow Object Detection CSV, etc)." }, { "code": null, "e": 6702, "s": 6635, "text": "Once uploaded you can choose preprocessing and augmentation steps:" }, { "code": null, "e": 6790, "s": 6702, "text": "Then, click Generate and Download and you will be able to choose YOLOv5 PyTorch format." }, { "code": null, "e": 6950, "s": 6790, "text": "When prompted, be sure to select “Show Code Snippet.” This will output a download curl script so you can easily port your data into Colab in the proper format." }, { "code": null, "e": 7057, "s": 6950, "text": "curl -L \"https://public.roboflow.ai/ds/YOUR-LINK-HERE\" > roboflow.zip; unzip roboflow.zip; rm roboflow.zip" }, { "code": null, "e": 7081, "s": 7057, "text": "Downloading in Colab..." }, { "code": null, "e": 7251, "s": 7081, "text": "The export creates a YOLOv5 .yaml file called data.yaml specifying the location of a YOLOv5 images folder, a YOLOv5 labels folder, and information on our custom classes." }, { "code": null, "e": 7460, "s": 7251, "text": "Next we write a model configuration file for our custom object detector. For this tutorial, we chose the smallest, fastest base model of YOLOv5. You have the option to pick from other YOLOv5 models including:" }, { "code": null, "e": 7468, "s": 7460, "text": "YOLOv5s" }, { "code": null, "e": 7476, "s": 7468, "text": "YOLOv5m" }, { "code": null, "e": 7484, "s": 7476, "text": "YOLOv5l" }, { "code": null, "e": 7492, "s": 7484, "text": "YOLOv5x" }, { "code": null, "e": 7673, "s": 7492, "text": "You can also edit the structure of the network in this step, though rarely will you need to do this. Here is the YOLOv5 model configuration file, which we term custom_yolov5s.yaml:" }, { "code": null, "e": 8650, "s": 7673, "text": "nc: 3depth_multiple: 0.33width_multiple: 0.50anchors: - [10,13, 16,30, 33,23] - [30,61, 62,45, 59,119] - [116,90, 156,198, 373,326]backbone: [[-1, 1, Focus, [64, 3]], [-1, 1, Conv, [128, 3, 2]], [-1, 3, Bottleneck, [128]], [-1, 1, Conv, [256, 3, 2]], [-1, 9, BottleneckCSP, [256]], [-1, 1, Conv, [512, 3, 2]], [-1, 9, BottleneckCSP, [512]], [-1, 1, Conv, [1024, 3, 2]], [-1, 1, SPP, [1024, [5, 9, 13]]], [-1, 6, BottleneckCSP, [1024]], ]head: [[-1, 3, BottleneckCSP, [1024, False]], [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], [-2, 1, nn.Upsample, [None, 2, \"nearest\"]], [[-1, 6], 1, Concat, [1]], [-1, 1, Conv, [512, 1, 1]], [-1, 3, BottleneckCSP, [512, False]], [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], [-2, 1, nn.Upsample, [None, 2, \"nearest\"]], [[-1, 4], 1, Concat, [1]], [-1, 1, Conv, [256, 1, 1]], [-1, 3, BottleneckCSP, [256, False]], [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]],[[], 1, Detect, [nc, anchors]], ]" }, { "code": null, "e": 8734, "s": 8650, "text": "With our data.yaml and custom_yolov5s.yaml files ready to go we are ready to train!" }, { "code": null, "e": 8815, "s": 8734, "text": "To kick off training we running the training command with the following options:" }, { "code": null, "e": 8844, "s": 8815, "text": "img: define input image size" }, { "code": null, "e": 8872, "s": 8844, "text": "batch: determine batch size" }, { "code": null, "e": 8956, "s": 8872, "text": "epochs: define the number of training epochs. (Note: often, 3000+ are common here!)" }, { "code": null, "e": 8992, "s": 8956, "text": "data: set the path to our yaml file" }, { "code": null, "e": 9029, "s": 8992, "text": "cfg: specify our model configuration" }, { "code": null, "e": 9146, "s": 9029, "text": "weights: specify a custom path to weights. (Note: you can download weights from the Ultralytics Google Drive folder)" }, { "code": null, "e": 9165, "s": 9146, "text": "name: result names" }, { "code": null, "e": 9204, "s": 9165, "text": "nosave: only save the final checkpoint" }, { "code": null, "e": 9244, "s": 9204, "text": "cache: cache images for faster training" }, { "code": null, "e": 9274, "s": 9244, "text": "And run the training command:" }, { "code": null, "e": 9454, "s": 9274, "text": "During training, you want to be watching the mAP@0.5 to see how your detector is learning to detect on your validation set, higher is better! — see this post on breaking down mAP." }, { "code": null, "e": 9668, "s": 9454, "text": "Now that we have completed training, we can evaluate how well the training procedure performed by looking at the validation metrics. The training script will drop tensorboard logs in runs. We visualize those here:" }, { "code": null, "e": 9808, "s": 9668, "text": "And if you can’t visualize Tensorboard for whatever reason the results can also be plotted with utils.plot_results and saving a result.png." }, { "code": null, "e": 9950, "s": 9808, "text": "I stopped training a little early here. You want to take the trained model weights at the point where the validation mAP reaches its highest." }, { "code": null, "e": 10403, "s": 9950, "text": "Now we take our trained model and make inference on test images. After training has completed model weights will save in weights/. For inference we invoke those weights along with a conf specifying model confidence (higher confidence required makes less predictions), and a inference source. source can accept a directory of images, individual images, video files, and also a device's webcam port. For source, I have moved our test/*jpg to test_infer/." }, { "code": null, "e": 10506, "s": 10403, "text": "!python detect.py --weights weights/last_yolov5s_custom.pt --img 416 --conf 0.4 --source ../test_infer" }, { "code": null, "e": 10692, "s": 10506, "text": "The inference time is extremely fast. On our Tesla P100, the YOLOv5s is hitting 7ms per image. This bodes well for deploying to a smaller GPU like a Jetson Nano (which costs only $100)." }, { "code": null, "e": 10755, "s": 10692, "text": "Finally, we visualize our detectors inferences on test images." }, { "code": null, "e": 10964, "s": 10755, "text": "Now that our custom YOLOv5 object detector has been verified, we might want to take the weights out of Colab for use on a live computer vision task. To do so we import a Google Drive module and send them out." }, { "code": null, "e": 11101, "s": 10964, "text": "from google.colab import drivedrive.mount('/content/gdrive')%cp /content/yolov5/weights/last_yolov5s_custom.pt /content/gdrive/My\\ Drive" }, { "code": null, "e": 11168, "s": 11101, "text": "We hoped you enjoyed training your custom YOLO v5 object detector!" }, { "code": null, "e": 11281, "s": 11168, "text": "YOLO v5 is lightweight and extremely easy to use. YOLO v5 trains quickly, inferences quickly, and performs well." }, { "code": null, "e": 11305, "s": 11281, "text": "Let’s get it out there!" } ]
Count unique sublists within list in Python
A Python list can also contain sublist. A sublist itself is a list nested within a bigger list. In this article we will see how to count the number of unique sublists within a given list. Counter is a subclass of Dictionary and used to keep track of elements and their count. It is also considered as an unordered collection where elements are stored as Dict keys and their count as dict value. So in the below example we directly take a list which has sublists. Live Demo from collections import Counter # Given List Alist = [['Mon'],['Tue','Wed'],['Tue','Wed']] print(Counter(str(elem) for elem in Alist)) Running the above code gives us the following result − Counter({"['Tue', 'Wed']": 2, "['Mon']": 1}) We can also iterate through the elements of the list and setting it as tuple and then keep adding 1 for each occurrence of the same element. Finally print the new list showing the sublist as key and their count as values. Live Demo # Given List Alist = [['Mon'],['Tue','Wed'],['Tue','Wed'], ['Tue','Wed']] # Initialize list NewList = {} # Use Append through Iteration for elem in Alist: NewList.setdefault(tuple(elem), list()).append(1) for k, v in NewList.items(): NewList[k] = sum(v) # Print Result print(NewList) Running the above code gives us the following result − {('Mon',): 1, ('Tue', 'Wed'): 3}
[ { "code": null, "e": 1250, "s": 1062, "text": "A Python list can also contain sublist. A sublist itself is a list nested within a bigger list. In this article we will see how to count the number of unique sublists within a given list." }, { "code": null, "e": 1525, "s": 1250, "text": "Counter is a subclass of Dictionary and used to keep track of elements and their count. It is also considered as an unordered collection where elements are stored as Dict keys and their count as dict value. So in the below example we directly take a list which has sublists." }, { "code": null, "e": 1536, "s": 1525, "text": " Live Demo" }, { "code": null, "e": 1671, "s": 1536, "text": "from collections import Counter\n# Given List\nAlist = [['Mon'],['Tue','Wed'],['Tue','Wed']]\nprint(Counter(str(elem) for elem in Alist))" }, { "code": null, "e": 1726, "s": 1671, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1771, "s": 1726, "text": "Counter({\"['Tue', 'Wed']\": 2, \"['Mon']\": 1})" }, { "code": null, "e": 1993, "s": 1771, "text": "We can also iterate through the elements of the list and setting it as tuple and then keep adding 1 for each occurrence of the same element. Finally print the new list showing the sublist as key and their count as values." }, { "code": null, "e": 2004, "s": 1993, "text": " Live Demo" }, { "code": null, "e": 2297, "s": 2004, "text": "# Given List\nAlist = [['Mon'],['Tue','Wed'],['Tue','Wed'], ['Tue','Wed']]\n\n# Initialize list\nNewList = {}\n\n# Use Append through Iteration\nfor elem in Alist:\n NewList.setdefault(tuple(elem), list()).append(1)\nfor k, v in NewList.items():\n NewList[k] = sum(v)\n\n# Print Result\nprint(NewList)" }, { "code": null, "e": 2352, "s": 2297, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2385, "s": 2352, "text": "{('Mon',): 1, ('Tue', 'Wed'): 3}" } ]
Check Whether a number is Duck Number or not - GeeksforGeeks
13 Apr, 2021 A Duck number is a positive number which has zeroes present in it, For example 3210, 8050896, 70709 are all Duck numbers. Please note that a numbers with only leading 0s is not considered as Duck Number. For example, numbers like 035 or 0012 are not considered as Duck Numbers. A number like 01203 is considered as Duck because there is a non-leading 0 present in it. Examples : Input : 707069 Output : It is a duck number. Explanation: 707069 does not contains zeros at the beginning. Input : 02364 Output : It is not a duck number. Explanation: in 02364 there is a zero at the beginning of the number. C++ Java Python C# Javascript // C++ Program to check whether// a number is Duck Number or not.#include <iostream>using namespace std; // Function to check whether// given number is duck number or not.bool check_duck(string num){ // Ignore leading 0s int i = 0, n = num.length(); while (i < n && num[i] == '0') i++; // Check remaining digits while (i < n) { if (num[i] == '0') return true; i++; } return false;} // Driver Methodint main(void){ string num = "1023"; if (check_duck(num)) cout << "It is a duck number\n"; else cout << "It is not a duck number\n"; return 0;} // Java Program to check whether a// number is Duck Number or not. import java.io.*;class GFG { // Function to check whether // the given number is duck number or not. static boolean check_duck(String num) { // Ignore leading 0s int i = 0, n = num.length(); while (i < n && num.charAt(i) == '0') i++; // Check remaining digits while (i < n) { if (num.charAt(i) == '0') return true; i++; } return false; } // Driver Method public static void main(String args[]) throws IOException { String num = "1023"; if (check_duck(num)) System.out.println("It is a duck number"); else System.out.println("It is not a duck number"); }} # Python program to check whether a number is Duck Number or not. # Function to check whether# the given number is duck number or not.def check_duck(num) : # Length of the number(number of digits) n = len(num) # Ignore leading 0s i = 0 while (i < n and num[i] == '0') : i = i + 1 # Check remaining digits while (i < n) : if (num[i] == "0") : return True i = i + 1 return False # Driver Methodnum1 = "1023"if(check_duck(num1)) : print "It is a duck number"else : print "It is not a duck number" # Write Python3 code here // C# Program to check whether a// number is Duck Number or not.using System; class GFG { // Function to check whether // the given number is duck // number or not. static bool check_duck( String num) { // Ignore leading 0s int i = 0, n = num.Length; while (i < n && num[i] == '0') i++; // Check remaining digits while (i < n) { if (num[i] == '0') return true; i++; } return false; } // Driver Method public static void Main() { String num1 = "1023"; // checking number1 if( check_duck(num1)) Console.Write("It is a " + "duck number"); else Console.Write("It is not " + "a duck number"); }} // This code is contributed by// nitin mittal. <script> // Javascript program to check whether// a number is Duck Number or not. // Function to check whether// given number is duck number or not.function check_duck(num){ // Ignore leading 0s let i = 0, n = num.length; while (i < n && num[i] == '0') i++; // Check remaining digits while (i < n) { if (num[i] == '0') return true; i++; } return false;} // Driver codelet num = "1023"; if (check_duck(num)) document.write("It is a duck number");else document.write("It is not a duck number"); // This code is contributed by rishavmahato348 </script> Output : It is a duck number. This article is contributed by Nikita Tiwari. 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. nitin mittal Sam007 keshvi2298 rishavmahato348 Mathematical School Programming Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find sum of elements in a given array Euclidean algorithms (Basic and Extended) The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24871, "s": 24843, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25239, "s": 24871, "text": "A Duck number is a positive number which has zeroes present in it, For example 3210, 8050896, 70709 are all Duck numbers. Please note that a numbers with only leading 0s is not considered as Duck Number. For example, numbers like 035 or 0012 are not considered as Duck Numbers. A number like 01203 is considered as Duck because there is a non-leading 0 present in it." }, { "code": null, "e": 25250, "s": 25239, "text": "Examples :" }, { "code": null, "e": 25357, "s": 25250, "text": "Input : 707069 Output : It is a duck number. Explanation: 707069 does not contains zeros at the beginning." }, { "code": null, "e": 25475, "s": 25357, "text": "Input : 02364 Output : It is not a duck number. Explanation: in 02364 there is a zero at the beginning of the number." }, { "code": null, "e": 25479, "s": 25475, "text": "C++" }, { "code": null, "e": 25484, "s": 25479, "text": "Java" }, { "code": null, "e": 25491, "s": 25484, "text": "Python" }, { "code": null, "e": 25494, "s": 25491, "text": "C#" }, { "code": null, "e": 25505, "s": 25494, "text": "Javascript" }, { "code": "// C++ Program to check whether// a number is Duck Number or not.#include <iostream>using namespace std; // Function to check whether// given number is duck number or not.bool check_duck(string num){ // Ignore leading 0s int i = 0, n = num.length(); while (i < n && num[i] == '0') i++; // Check remaining digits while (i < n) { if (num[i] == '0') return true; i++; } return false;} // Driver Methodint main(void){ string num = \"1023\"; if (check_duck(num)) cout << \"It is a duck number\\n\"; else cout << \"It is not a duck number\\n\"; return 0;}", "e": 26129, "s": 25505, "text": null }, { "code": "// Java Program to check whether a// number is Duck Number or not. import java.io.*;class GFG { // Function to check whether // the given number is duck number or not. static boolean check_duck(String num) { // Ignore leading 0s int i = 0, n = num.length(); while (i < n && num.charAt(i) == '0') i++; // Check remaining digits while (i < n) { if (num.charAt(i) == '0') return true; i++; } return false; } // Driver Method public static void main(String args[]) throws IOException { String num = \"1023\"; if (check_duck(num)) System.out.println(\"It is a duck number\"); else System.out.println(\"It is not a duck number\"); }}", "e": 26922, "s": 26129, "text": null }, { "code": "# Python program to check whether a number is Duck Number or not. # Function to check whether# the given number is duck number or not.def check_duck(num) : # Length of the number(number of digits) n = len(num) # Ignore leading 0s i = 0 while (i < n and num[i] == '0') : i = i + 1 # Check remaining digits while (i < n) : if (num[i] == \"0\") : return True i = i + 1 return False # Driver Methodnum1 = \"1023\"if(check_duck(num1)) : print \"It is a duck number\"else : print \"It is not a duck number\" # Write Python3 code here", "e": 27516, "s": 26922, "text": null }, { "code": "// C# Program to check whether a// number is Duck Number or not.using System; class GFG { // Function to check whether // the given number is duck // number or not. static bool check_duck( String num) { // Ignore leading 0s int i = 0, n = num.Length; while (i < n && num[i] == '0') i++; // Check remaining digits while (i < n) { if (num[i] == '0') return true; i++; } return false; } // Driver Method public static void Main() { String num1 = \"1023\"; // checking number1 if( check_duck(num1)) Console.Write(\"It is a \" + \"duck number\"); else Console.Write(\"It is not \" + \"a duck number\"); }} // This code is contributed by// nitin mittal.", "e": 28411, "s": 27516, "text": null }, { "code": "<script> // Javascript program to check whether// a number is Duck Number or not. // Function to check whether// given number is duck number or not.function check_duck(num){ // Ignore leading 0s let i = 0, n = num.length; while (i < n && num[i] == '0') i++; // Check remaining digits while (i < n) { if (num[i] == '0') return true; i++; } return false;} // Driver codelet num = \"1023\"; if (check_duck(num)) document.write(\"It is a duck number\");else document.write(\"It is not a duck number\"); // This code is contributed by rishavmahato348 </script>", "e": 29046, "s": 28411, "text": null }, { "code": null, "e": 29056, "s": 29046, "text": "Output : " }, { "code": null, "e": 29077, "s": 29056, "text": "It is a duck number." }, { "code": null, "e": 29499, "s": 29077, "text": "This article is contributed by Nikita Tiwari. 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": 29512, "s": 29499, "text": "nitin mittal" }, { "code": null, "e": 29519, "s": 29512, "text": "Sam007" }, { "code": null, "e": 29530, "s": 29519, "text": "keshvi2298" }, { "code": null, "e": 29546, "s": 29530, "text": "rishavmahato348" }, { "code": null, "e": 29559, "s": 29546, "text": "Mathematical" }, { "code": null, "e": 29578, "s": 29559, "text": "School Programming" }, { "code": null, "e": 29586, "s": 29578, "text": "Strings" }, { "code": null, "e": 29594, "s": 29586, "text": "Strings" }, { "code": null, "e": 29607, "s": 29594, "text": "Mathematical" }, { "code": null, "e": 29705, "s": 29607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29754, "s": 29705, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29796, "s": 29754, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 29839, "s": 29796, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 29892, "s": 29839, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 29924, "s": 29892, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 29942, "s": 29924, "text": "Python Dictionary" }, { "code": null, "e": 29958, "s": 29942, "text": "Arrays in C/C++" }, { "code": null, "e": 29977, "s": 29958, "text": "Inheritance in C++" }, { "code": null, "e": 30002, "s": 29977, "text": "Reverse a string in Java" } ]
Odd Even Problem | Practice | GeeksforGeeks
Given a string S of lowercase english characters, find out whether the summation of X and Y is even or odd, where X is the count of characters which occupy even positions in english alphabets and have positive even frequency, and Y is the count of characters which occupy odd positions in english alphabets and have positive odd frequency. Note: Positive means greater than zero. Example 1: Input: S = "abbbcc" Output: "ODD" Explanation: X = 0 and Y = 1 so (X + Y) is ODD. 'a' occupies 1st place(odd) in english alphabets and its frequency is odd(1), 'b' occupies 2nd place(even) but its frequency is odd(3) so it doesn't get counted and 'c' occupies 3rd place(odd) but its frequency is even(2) so it also doesn't get counted. Example 2: Input: S = "nobitaa" Output: "EVEN" Explanation: X = 0 and Y = 2 so (X + Y) is EVEN. Your Task: You dont need to read input or print anything. Complete the function evenOdd() which takes S as input parameter and returns "EVEN" if X + Y is even, "ODD" otherwise. Expected Time Complexity: O(|S|) Expected Auxiliary Space: O(1) Constraints: 1 ≤ |S| ≤ 1000 0 bishaldevacc3 months ago JAVA SOLUTION: 0.2 / 3.7 static String oddEven(String S) { // code here int X=0,Y=0; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<S.length();i++){ int c=(int)S.charAt(i); map.put(c,map.getOrDefault(c,0)+1); } for(int i=0;i<S.length();i++){ int c=(int)S.charAt(i); if(c%2==0){ if(map.get(c)%2==0){ map.replace(c,-1); X++; } } else{ if(map.get(c)%2!=0){ map.replace(c,-1); Y++; } } } if((X+Y)%2==0){ return "EVEN"; } return "ODD"; } +2 avinav26113 months ago Easy C++ Solution 0 ansarizia93354 months ago JAVA 0.1 sec static String oddEven(String s) { int alphabet[]=new int[26]; for(int i=0;i<26;i++) {alphabet[i]=0;} int n=s.length(); for(int i=0;i<n;i++) { alphabet[(int)s.charAt(i)-97]++; } int x=0,y=0; for(int i=0;i<26;i++) { if(alphabet[i]!=0) { if(((97+i)&1)==0 && (alphabet[i]&1)==0) x++; else if(((97+i)&1)==1 && (alphabet[i]&1)==1) y++; } } return (((x+y)&1)==0?"EVEN":"ODD"); } 0 badgujarsachin836 months ago string oddEven(string S) { // code here int even=0; int odd=0; unordered_map<int,int> mp; for(int i=0;i<S.size();i++){ mp[S[i]]++; } for(auto it:mp){ if(it.second%2==0 && (it.first-'a'+1)%2==0){ even++; } if(it.second%2!=0 && (it.first-'a'+1)%2!=0){ odd++; } } if((even+odd)%2==0){ return "EVEN"; }else{ return "ODD"; } } -2 imranwahid6 months ago Easy C++ solutions -1 Shobhit Yadav11 months ago Shobhit Yadav EASY JAVA SOLN Map<character,integer> m=new HashMap<>(); for(int i=0;i<s.length();i++) {="" char="" c="S.charAt(i);" if(m.containskey(c))="" {="" m.put(c,m.get(c)+1);="" }="" else="" m.put(c,1);="" }="" int="" x="0;" int="" y="0;" for(map.entry<character,integer=""> ma : m.entrySet()){ if((ma.getKey()-'a')%2==0){ if(ma.getValue()%2!=0){ X++; } }else{ if(ma.getValue()%2==0){ Y++; } } } if((X+Y)%2==0){ return "EVEN"; }else{ return "ODD"; } 0 Sakshi Agarwal1 year ago Sakshi Agarwal string oddEven(string S) { // code here unordered_map<char,int>m; for(int i=0;i<s.size();i++){ m[s[i]]++;="" }="" int="" x="0,y" =="" 0;="" for(auto="" it:m){="" if(((it.first-'a')%2!="0)" &&="" it.second%2="=0)" x++;="" else="" if(((it.first-'a')%2="=0)" &&="" it.second%2!="0)" y++;="" }="" return="" (x+y)%2!="0" ?="" "odd"="" :="" "even";="" }<="" code=""> 0 Vipul Roy1 year ago Vipul Roy string oddEven(string s) { int n=s.length(),x=0,y=0; int c[123]={0}; for(int i=0;i<n;i++){ c[s[i]]+="1;" }="" for(int="" i="0;i&lt;n;i++){" if(s[i]%2="=0&amp;&amp;c[s[i]]%2==0){" x++;="" c[s[i]]+="1;" }="" else="" if(s[i]%2="=1&amp;&amp;c[s[i]]%2==1){" y++;="" c[s[i]]+="1;" }="" }="" if((x+y)%2="=0)" return="" "even";="" else="" return="" "odd";="" }="" };=""> 0 abhikarsh gupta1 year ago abhikarsh gupta C++ using hashing. The description is kind of confusing at first but need to read twice to get the gist of it. Even indexed alphabet should have even frequency in string, and vice versa, if condition is true, increment count of that type by 1. Approach :-1. map freq for each element.2. we are aware of index position of each alphabet. a is odd., b is even, so, we iterate over each element of map and see if its index is even or odd.3. if even index, check if frequency is even. if both even, increment count of even by 1, same for odd.4. check if sum of even and odd count is even or odd. string oddEven(string S) { // code here unordered_map<char,int> mp; for(auto it : S) mp[it]++; int even = 0, odd = 0, sum = 0; for(auto it : mp) { if((it.first - 'a' + 1) % 2 == 0) { if(it.second % 2 == 0) even++; } else { if(it.second % 2) odd++; } } sum = odd + even; return (sum % 2) ? "ODD" : "EVEN"; } 0 Tejas Jhamnani This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 618, "s": 238, "text": "Given a string S of lowercase english characters, find out whether the summation of X and Y is even or odd, where X is the count of characters which occupy even positions in english alphabets and have positive even frequency, and Y is the count of characters which occupy odd positions in english alphabets and have positive odd frequency.\nNote: Positive means greater than zero." }, { "code": null, "e": 629, "s": 618, "text": "Example 1:" }, { "code": null, "e": 972, "s": 629, "text": "Input: S = \"abbbcc\"\nOutput: \"ODD\"\nExplanation: X = 0 and Y = 1 so (X + Y) is \nODD. 'a' occupies 1st place(odd) in english \nalphabets and its frequency is odd(1), 'b' \noccupies 2nd place(even) but its frequency \nis odd(3) so it doesn't get counted and 'c' \noccupies 3rd place(odd) but its frequency \nis even(2) so it also doesn't get counted.\n" }, { "code": null, "e": 983, "s": 972, "text": "Example 2:" }, { "code": null, "e": 1069, "s": 983, "text": "Input: S = \"nobitaa\"\nOutput: \"EVEN\"\nExplanation: X = 0 and Y = 2 so (X + Y) is\nEVEN.\n" }, { "code": null, "e": 1250, "s": 1069, "text": "Your Task: \nYou dont need to read input or print anything. Complete the function evenOdd() which takes S as input parameter and returns \"EVEN\" if X + Y is even, \"ODD\" otherwise." }, { "code": null, "e": 1315, "s": 1250, "text": "Expected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1) " }, { "code": null, "e": 1343, "s": 1315, "text": "Constraints:\n1 ≤ |S| ≤ 1000" }, { "code": null, "e": 1345, "s": 1343, "text": "0" }, { "code": null, "e": 1370, "s": 1345, "text": "bishaldevacc3 months ago" }, { "code": null, "e": 1395, "s": 1370, "text": "JAVA SOLUTION: 0.2 / 3.7" }, { "code": null, "e": 2088, "s": 1397, "text": " static String oddEven(String S) { // code here int X=0,Y=0; Map<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<S.length();i++){ int c=(int)S.charAt(i); map.put(c,map.getOrDefault(c,0)+1); } for(int i=0;i<S.length();i++){ int c=(int)S.charAt(i); if(c%2==0){ if(map.get(c)%2==0){ map.replace(c,-1); X++; } } else{ if(map.get(c)%2!=0){ map.replace(c,-1); Y++; } } } if((X+Y)%2==0){ return \"EVEN\"; } return \"ODD\"; }" }, { "code": null, "e": 2091, "s": 2088, "text": "+2" }, { "code": null, "e": 2114, "s": 2091, "text": "avinav26113 months ago" }, { "code": null, "e": 2132, "s": 2114, "text": "Easy C++ Solution" }, { "code": null, "e": 2136, "s": 2134, "text": "0" }, { "code": null, "e": 2162, "s": 2136, "text": "ansarizia93354 months ago" }, { "code": null, "e": 2175, "s": 2162, "text": "JAVA 0.1 sec" }, { "code": null, "e": 2688, "s": 2175, "text": " static String oddEven(String s) { int alphabet[]=new int[26]; for(int i=0;i<26;i++) {alphabet[i]=0;} int n=s.length(); for(int i=0;i<n;i++) { alphabet[(int)s.charAt(i)-97]++; } int x=0,y=0; for(int i=0;i<26;i++) { if(alphabet[i]!=0) { if(((97+i)&1)==0 && (alphabet[i]&1)==0) x++; else if(((97+i)&1)==1 && (alphabet[i]&1)==1) y++; } } return (((x+y)&1)==0?\"EVEN\":\"ODD\"); }" }, { "code": null, "e": 2690, "s": 2688, "text": "0" }, { "code": null, "e": 2719, "s": 2690, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 3267, "s": 2719, "text": "string oddEven(string S) {\n // code here\n int even=0;\n int odd=0;\n unordered_map<int,int> mp;\n for(int i=0;i<S.size();i++){\n mp[S[i]]++;\n }\n for(auto it:mp){\n if(it.second%2==0 && (it.first-'a'+1)%2==0){\n even++;\n }\n if(it.second%2!=0 && (it.first-'a'+1)%2!=0){\n odd++;\n }\n }\n if((even+odd)%2==0){\n return \"EVEN\";\n }else{\n return \"ODD\";\n }\n }" }, { "code": null, "e": 3270, "s": 3267, "text": "-2" }, { "code": null, "e": 3293, "s": 3270, "text": "imranwahid6 months ago" }, { "code": null, "e": 3312, "s": 3293, "text": "Easy C++ solutions" }, { "code": null, "e": 3315, "s": 3312, "text": "-1" }, { "code": null, "e": 3342, "s": 3315, "text": "Shobhit Yadav11 months ago" }, { "code": null, "e": 3356, "s": 3342, "text": "Shobhit Yadav" }, { "code": null, "e": 3371, "s": 3356, "text": "EASY JAVA SOLN" }, { "code": null, "e": 3985, "s": 3371, "text": " Map<character,integer> m=new HashMap<>(); for(int i=0;i<s.length();i++) {=\"\" char=\"\" c=\"S.charAt(i);\" if(m.containskey(c))=\"\" {=\"\" m.put(c,m.get(c)+1);=\"\" }=\"\" else=\"\" m.put(c,1);=\"\" }=\"\" int=\"\" x=\"0;\" int=\"\" y=\"0;\" for(map.entry<character,integer=\"\"> ma : m.entrySet()){ if((ma.getKey()-'a')%2==0){ if(ma.getValue()%2!=0){ X++; } }else{ if(ma.getValue()%2==0){ Y++; } } } if((X+Y)%2==0){ return \"EVEN\"; }else{ return \"ODD\"; }" }, { "code": null, "e": 3987, "s": 3985, "text": "0" }, { "code": null, "e": 4012, "s": 3987, "text": "Sakshi Agarwal1 year ago" }, { "code": null, "e": 4027, "s": 4012, "text": "Sakshi Agarwal" }, { "code": null, "e": 4409, "s": 4027, "text": "string oddEven(string S) { // code here unordered_map<char,int>m; for(int i=0;i<s.size();i++){ m[s[i]]++;=\"\" }=\"\" int=\"\" x=\"0,y\" ==\"\" 0;=\"\" for(auto=\"\" it:m){=\"\" if(((it.first-'a')%2!=\"0)\" &&=\"\" it.second%2=\"=0)\" x++;=\"\" else=\"\" if(((it.first-'a')%2=\"=0)\" &&=\"\" it.second%2!=\"0)\" y++;=\"\" }=\"\" return=\"\" (x+y)%2!=\"0\" ?=\"\" \"odd\"=\"\" :=\"\" \"even\";=\"\" }<=\"\" code=\"\">" }, { "code": null, "e": 4411, "s": 4409, "text": "0" }, { "code": null, "e": 4431, "s": 4411, "text": "Vipul Roy1 year ago" }, { "code": null, "e": 4441, "s": 4431, "text": "Vipul Roy" }, { "code": null, "e": 4825, "s": 4441, "text": "string oddEven(string s) { int n=s.length(),x=0,y=0; int c[123]={0}; for(int i=0;i<n;i++){ c[s[i]]+=\"1;\" }=\"\" for(int=\"\" i=\"0;i&lt;n;i++){\" if(s[i]%2=\"=0&amp;&amp;c[s[i]]%2==0){\" x++;=\"\" c[s[i]]+=\"1;\" }=\"\" else=\"\" if(s[i]%2=\"=1&amp;&amp;c[s[i]]%2==1){\" y++;=\"\" c[s[i]]+=\"1;\" }=\"\" }=\"\" if((x+y)%2=\"=0)\" return=\"\" \"even\";=\"\" else=\"\" return=\"\" \"odd\";=\"\" }=\"\" };=\"\">" }, { "code": null, "e": 4827, "s": 4825, "text": "0" }, { "code": null, "e": 4853, "s": 4827, "text": "abhikarsh gupta1 year ago" }, { "code": null, "e": 4869, "s": 4853, "text": "abhikarsh gupta" }, { "code": null, "e": 5114, "s": 4869, "text": "C++ using hashing. The description is kind of confusing at first but need to read twice to get the gist of it. Even indexed alphabet should have even frequency in string, and vice versa, if condition is true, increment count of that type by 1." }, { "code": null, "e": 5462, "s": 5114, "text": "Approach :-1. map freq for each element.2. we are aware of index position of each alphabet. a is odd., b is even, so, we iterate over each element of map and see if its index is even or odd.3. if even index, check if frequency is even. if both even, increment count of even by 1, same for odd.4. check if sum of even and odd count is even or odd." }, { "code": null, "e": 5984, "s": 5462, "text": "string oddEven(string S) { // code here unordered_map<char,int> mp; for(auto it : S) mp[it]++; int even = 0, odd = 0, sum = 0; for(auto it : mp) { if((it.first - 'a' + 1) % 2 == 0) { if(it.second % 2 == 0) even++; } else { if(it.second % 2) odd++; } } sum = odd + even; return (sum % 2) ? \"ODD\" : \"EVEN\"; }" }, { "code": null, "e": 5986, "s": 5984, "text": "0" }, { "code": null, "e": 6001, "s": 5986, "text": "Tejas Jhamnani" }, { "code": null, "e": 6027, "s": 6001, "text": "This comment was deleted." }, { "code": null, "e": 6173, "s": 6027, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6209, "s": 6173, "text": " Login to access your submissions. " }, { "code": null, "e": 6219, "s": 6209, "text": "\nProblem\n" }, { "code": null, "e": 6229, "s": 6219, "text": "\nContest\n" }, { "code": null, "e": 6292, "s": 6229, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6440, "s": 6292, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6648, "s": 6440, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6754, "s": 6648, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to take a screenshot of the window using Python?(Tkinter)
Python has a rich library of modules and functions that allows us to build and develop featured applications. Tkinter is a well-known Python library that is used for creating GUIbased applications. If we want to develop an application that takes a screenshot of the window, then we can definitely use Tkinter to build the GUI of the application. The following stages of the application will help to know how our application works, Required Libraries – Pillow (PIL) for Image Processing, Time Module in Python for Randomizing the Filename and epochs processing. Required Libraries – Pillow (PIL) for Image Processing, Time Module in Python for Randomizing the Filename and epochs processing. Create a Label widget in the window and add a Button to take the screenshot. Create a Label widget in the window and add a Button to take the screenshot. Define a function, screenshot(), that will take the screenshot of the window and save the file in a local directory. Define a function, screenshot(), that will take the screenshot of the window and save the file in a local directory. In order to keep the Tkinter window away from taking screenshots as well as in the image, we can use withdraw() function to withdraw the image. In order to keep the Tkinter window away from taking screenshots as well as in the image, we can use withdraw() function to withdraw the image. # Import the required libraries from tkinter import * import time from PIL import ImageTk, Image import pyautogui as pg # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Define a function for taking screenshot def screenshot(): random = int(time.time()) filename = "C:/Users/Sairam/Documents/" \ + str(random) + ".jpg" ss = pg.screenshot(filename) ss.show() win.deiconify() def hide_window(): # hiding the tkinter window while taking the screenshot win.withdraw() win.after(1000, screenshot) # Add a Label widget Label(win, text="Click the Button to Take the Screenshot", font=('Times New Roman', 18, 'bold')).pack(pady=10) # Create a Button to take the screenshots button = Button(win, text="Take Screenshot", font=('Aerial 11 bold'), background="#aa7bb1", foreground="white", command=hide_window) button.pack(pady=20) win.mainloop() Running the above code will display a window that contains a button and a Label text. When we click the button, it will take a screenshot of the window and save it in a local directory.
[ { "code": null, "e": 1493, "s": 1062, "text": "Python has a rich library of modules and functions that allows us to build and develop featured applications. Tkinter is a well-known Python library that is used for creating GUIbased applications. If we want to develop an application that takes a screenshot of the window, then we can definitely use Tkinter to build the GUI of the application. The following stages of the application will help to know how our application works," }, { "code": null, "e": 1623, "s": 1493, "text": "Required Libraries – Pillow (PIL) for Image Processing, Time Module in Python for Randomizing the Filename and epochs processing." }, { "code": null, "e": 1753, "s": 1623, "text": "Required Libraries – Pillow (PIL) for Image Processing, Time Module in Python for Randomizing the Filename and epochs processing." }, { "code": null, "e": 1830, "s": 1753, "text": "Create a Label widget in the window and add a Button to take the screenshot." }, { "code": null, "e": 1907, "s": 1830, "text": "Create a Label widget in the window and add a Button to take the screenshot." }, { "code": null, "e": 2024, "s": 1907, "text": "Define a function, screenshot(), that will take the screenshot of the window and save the file in a local directory." }, { "code": null, "e": 2141, "s": 2024, "text": "Define a function, screenshot(), that will take the screenshot of the window and save the file in a local directory." }, { "code": null, "e": 2285, "s": 2141, "text": "In order to keep the Tkinter window away from taking screenshots as well as in the image, we can use withdraw() function to withdraw the image." }, { "code": null, "e": 2429, "s": 2285, "text": "In order to keep the Tkinter window away from taking screenshots as well as in the image, we can use withdraw() function to withdraw the image." }, { "code": null, "e": 3362, "s": 2429, "text": "# Import the required libraries\nfrom tkinter import *\nimport time\nfrom PIL import ImageTk, Image\nimport pyautogui as pg\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Define a function for taking screenshot\ndef screenshot():\n random = int(time.time())\n filename = \"C:/Users/Sairam/Documents/\" \\ + str(random) + \".jpg\"\n ss = pg.screenshot(filename)\n ss.show()\n win.deiconify()\n\ndef hide_window():\n # hiding the tkinter window while taking the screenshot\n win.withdraw()\n win.after(1000, screenshot)\n\n# Add a Label widget\n Label(win, text=\"Click the Button to Take the Screenshot\", font=('Times New Roman', 18, 'bold')).pack(pady=10)\n\n# Create a Button to take the screenshots\nbutton = Button(win, text=\"Take Screenshot\", font=('Aerial 11 bold'), background=\"#aa7bb1\", foreground=\"white\", command=hide_window)\nbutton.pack(pady=20)\n\nwin.mainloop()" }, { "code": null, "e": 3448, "s": 3362, "text": "Running the above code will display a window that contains a button and a Label text." }, { "code": null, "e": 3548, "s": 3448, "text": "When we click the button, it will take a screenshot of the window and save it in a local directory." } ]
!!! DOGS VS CATS IMAGE CLASSIFIER !!! | by Ashis Kumar Panda | Towards Data Science
I’ve been going through fast.ai for a couple of months . I got to admit that there were lots of stuffs and awesome techniques that I learned in the process. I’ll make sure to update all those in my Blog . All thanks to Jeremy Howard and Rachel Thomas for their efforts to democratize AI. Thanks to the awesome fast.ai community for all the quick help . This below picture depicts my journey till now which makes it an interesting one. To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:- Dog Vs Cat Image ClassificationDog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2 Dog Vs Cat Image Classification Dog Breed Image Classification Multi-label Image Classification Time Series Analysis using Neural Network NLP- Sentiment Analysis on IMDB Movie Dataset Basic of Movie Recommendation System Collaborative Filtering from Scratch Collaborative Filtering using Neural Network Writing Philosophy like Nietzsche Performance of Different Neural Network on Cifar-10 dataset ML Model to detect the biggest object in an image Part-1 ML Model to detect the biggest object in an image Part-2 So Brace yourselves and focus on Part 1 Lesson 2 of Fastai course. This blog post deals with Dogs vs Cats Classification Model. It has been taught by Jeremy Howard in Part 1 Lesson 2 of FastAI Course. Import all the libraries as below that will be used in this Model. !pip install fastai==0.7.0!pip install torchtext==0.2.3!pip3 install http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl !pip3 install torchvisionimport fastaifrom matplotlib import pyplot as plt# Put these at the top of every notebook, to get automatic reloading # and inline plotting%reload_ext autoreload%autoreload 2%matplotlib inline# This file contains all the main external libs we'll use# from fastai.imports import *from fastai.transforms import *from fastai.conv_learner import *from fastai.model import *from fastai.dataset import *from fastai.sgdr import *from fastai.plots import * Check for whether GPU has been enabled using the following commands:- The output to the above commands should return True. Before delving forward, I would like to mention couple of Linux Command that might come handy . Use these commands prefixed by ‘!’ mark . !ls is a command to list files present in current directory.!pwd stands for Print work directory . Will print the path of working directory!cd stands for change directory. !ls is a command to list files present in current directory. !pwd stands for Print work directory . Will print the path of working directory !cd stands for change directory. The above three commands helps to navigate between directories. The images of dogs and cats has been downloaded using the following command. << !wget http://files.fast.ai/data/dogscats.zip>> The structure of the folder should be as follows:- Set the path to where the data is stored PATH = "data/dogscats/"sz=224 Check whether the files has been downloaded using the following command :- The f ’ above stands for f-Strings .Its a new way to format Strings in Python. To know more about f-strings, please check this awesome link by realpython.com. The Classification task will make use of pre-trained model . A pre-trained model is one which has been trained on similar type of data by someone else. So instead of training the model from scratch , a model will be used that has been trained on ImageNet. ImageNet is a dataset consisting of 1.2 million images and 1000 classes. ResNet34 is the version of the Model that will be used . Its a Special type of Convolutional Neural Network. ResNet34 won the 2015 ImageNet Competition. The details of ResNet will be discussed in the upcoming blog post . The following lines of Code shows how to train the model using fastai. The architecture resnet34 which is used has been saved in arch variable . The data is saved in data variable as it looks for the data in the PATH specified earlier . The tfms is a part of data augmentation which will be dealt later in detail. The pre-trained method creates the new Neural Network from the arch model(resnet34). The fit method trains the model using the learning rate and the number of epochs specified. And an accuracy of 0.9895 has been obtained. GRADIENT DESCENT Let me explain the above image. Initially the parameters that has been chosen were random. The loss was high at this point of time . High Loss indicates that during training, the difference between the ‘outcome / predicted value’ and the ‘ target value/ labels ’ is more. Hence an approach should be followed using which this difference should be made least . Convergence or reaching to the local minima means the loss is minimum at this point and hence the difference between the outcome and target value /labels is the least. This process is known as Gradient Descent. LEARNING RATE:- The Learning rate(LR) in the fit function above is one of the most important parameters and should be carefully chosen so as to make the model reach an optimal solution in a fast and efficient way. It basically says how to quickly reach the optimal point in the function .If LR is low the process is slow and if its too high then there is a great chance that it might overshoot the minima. So the LR has to be carefully chosen , so as to make sure the convergence (reaching the local minima) happens in a efficient manner . The image below describes the above concept. How to Choose the Best Learning Rate ? !!! Don’t worry , Jeremy Howard has your back. Jeremy has mentioned a wonderful way of finding the Learning rate and its known as LEARNING RATE FINDER. Please check the code below. Using lr_find() the optimal learning rate can be obtained. As the Learning rate vs iteration graph shows, the LR is being increased after each minibatch and it increases exponentially . In the 2nd plot i.e Loss vs Learning rate , its observed that the Loss decreases for a while as the Learning rate increases and when Learning rate is at 0.1 the loss is at its minimum , post which it starts to rise again (which means the LR is so high that it has overshoot the minima and the loss gets worse). To choose the best learning rate, here are the following steps:- Determine the lowest point in the Loss vs Learning rate graph above (i.e at 0.1)Take a step back by magnitude 1 (i.e at 0.01) and choose that as a Learning Rate. Determine the lowest point in the Loss vs Learning rate graph above (i.e at 0.1) Take a step back by magnitude 1 (i.e at 0.01) and choose that as a Learning Rate. Concept behind Going back by magnitude 1 :- Although at this point the Loss is at minimum but the Learning rate chosen at this point is too high and continuing with this learning rate, won’t yield in convergence. Please check the image below for explanation. NOTE :- Learning rate finder is one of the most important hyperparameter and if adjusted /chosen properly will yield the best results. IMPROVING THE MODEL One way to improve the model is by giving it more data . Hence we use data augmentation . Wait , But Why Data Augmentation? Our model generally has a couple of million of parameters and when trained for more number epoch there is a great probability , it might start overfitting . Overfitting means the model is over learning the specific details of the images in the training dataset and it might not generalize well on the validation dataset or test dataset . In other words , Overfitting is said to happen when the accuracy of the validation dataset is less than the accuracy of the training dataset(or the loss calculated on the training dataset is much less than the loss calculated on the validation dataset). So Overfitting can be avoided by providing more data to the model , hence data augmentation is used. Note:-Data Augmentation is not creating new data , but allows the Convolution Neural Network to learn how to recognize dogs or cats from a very different angle . For data augmentation we pass transforms_side_on to aug_tfms in tfms_from_model() function. transforms_side_on will give different versions of image by flipping it horizontally. It makes the NN to see the images , as if it has been taken from side angle, rotate them by small amounts and slightly vary their contrasts , brightness and slightly zoom in a bit , move around a bit. The variations can be seen in the image below. For data augmentation to take place write the following code tfms = tfms_from_model(resnet34, sz, aug_tfms=transforms_side_on, max_zoom=1.1)data = ImageClassifierData.from_paths(PATH, tfms=tfms) Although there is room created for data augmentation , yet the data augmentation wont work, because initially it has been set as precompute=True . Let me explain in detail the following code and its relation with above made statement:- data = ImageClassifierData.from_paths(PATH, tfms=tfms)learn = ConvLearner.pretrained(arch, data, precompute=True)learn.fit(1e-2, 1) When declaring the architecture using ConvLearner.pretrained(...) , the precompute is set as True which says to implement the activations from the pretrained network. A pretrained network is one which has already learnt to recognize certain things. For our Dog vs Cat study , the pretrained network used, has already learned to classify 1000 classes on 1.2 million images in ImageNet Dataset. So take the penultimate layer (as this is the layer which has all the required information necessary to figure out what the image is ) and save these activations. Save these activations for each of the image and these are known as precomputed activations. Now when creating a new classifier , take advantage of these precomputed activation and quickly train a model based on those activations. Hence to implement this set precompute=True . Note:- When precompute=True , data augmentation doesn’t work as it is currently using a particular version of the augmented cat or in other words even though a different version of cat is being showed each time , the activation for a particular version of cat has been has been precomputed. It takes a minute or two to precompute the activations when it runs for the first time. When trained using precomputed activations , the accuracy is 98.8%:- To put data augmentation to work , set precompute=False and check for the accuracy. In the code below cycle_len is an important parameter and will be dealt in detail later in this post. The accuracy has increased a bit to 99.1% and the good news is that , it is not overfitting and the training loss has decreased further . To further improve the model lets focus on:- SGDR(STOCHASTIC GRADIENT DESCENT WITH RESTARTS) SGDR says as we get closer and closer to the minima ,lets decrease the learning rate . The idea of decreasing the learning rate as we train (i.e with more number of iterations) is known as Learning Rate Annealing . There is Step Wise and Cosine Annealing . In this Course Jeremy Howard uses Cosine Annealing. In Cosine Annealing , we train using a higher learning rate when not near minima .When getting close to local minima , switch to a low learning rate and do few iterations on top of this. The above diagram shows a simple loss function . In real , the datasets are represented in a very high dimensional space and there is lot of fairly flat points and these aren’t local minima. Suppose our surface looks like the below diagram:- Started at the red point no 1 and reached the global minima as shown by red point no 2 but here it doesn’t generalize very well . If this solution is used, in case of slightly different dataset , it will not lead to a good result. On the other hand red point no 3 , will generalize very well in case of slightly different dataset. Our Standard Learning rate annealing approach will go downhill to one spot and in high dimension there is a great chance of being stuck in a spiky zone , where it will not generalize better , hence not a good solution . Instead a Learning rate scheduler can be deployed which will reset and do a cosine annealing and jump again so that it will jump from point 2 to point 3 and so on , until it reaches a point where the generalization is really good. Each time the Learning rate is reset it will again increase the Learning rate which will lead to leaving the nasty spiky part of the surface and eventually jumps to a nice smooth bowl which will generalize better. This above process is known as SGDR(Stochastic Gradient Descent with Restarts). The best part of this SGDR is once a “nice smooth curve like surface” is reached , it wont restart anymore . It actually hangs out in this nice part of the space and then keeps getting better at finding the reasonably good spot . Please check the diagram below. Using SGDR along with Learning rate finder will give us better results . From learning rate finder try to visually pick up a good learning rate or else in SGDR it wont jump up to a nice smooth like surface . The reset of the learning rate happens with the help of cycle_len parameter . It basically means reset the learning rate after every 1 epoch. The below image shows how the reset happens:- Note:- Resetting of learning rate happens after every single epoch as cycle_len=1 and Learning rate keeps changing after every single mini batch. The y axis is the learning rate where 0.010 is the learning rate we get from learning rate finder. So SGDR will shuffle the learning rate between 0 and 0.010. It is advised to keep saving the model at intermediate steps. To do so use the following commands:- learn.save('224_lastlayer')learn.load('224_lastlayer') The model is saved in the models folder within the dogscats folder as shown below:- All the precomputed activations are saved in the tmp folder . So in case of weird errors , may be due to half completed precomputed activations or in some other way , go ahead and delete the tmp folder and check if the error has gone away. This is the fastai way of turning it off and on again . Note:- Precomputed activation are without any training. These are what pretrained models created with the weights we downloaded. What else can we do to make the model better? So far the pretrained activations has been downloaded and directly used . The pretrained activations or the precomputed weights in the CNN kernels are left untouched (i.e no retraining of precomputed weights has been done yet). The pretrained model already knows how to find at early stages edges, curves, gradients and then repeating patterns and eventually the main features. Until now, only new layers were being added on the top and models learned how to mix and match the pretrained features. If a model trained on Imagenet is extended to case like “Satellite images classification” where the features are completely different , most of the layers are needed to be retrained as the features are completely different. Hence a new concept is needed to be explored named as :- FINE TUNING AND DIFFERENTIAL LEARNING RATE To learn a different set of features or to tell the learner that the convolution filters are needed to be changed , simply unfreeze all the layers .A frozen layer is one whose weights are not trained or updated. !!! Okay Okay Elsa ,I’ll let it go and unfreeze the layers !!! 😍 😍 Unfreezing the layers will make the layer weights open to training or updating. But the initial layers need little or any training as compared to the later layers . This holds universally true because the work of initial layers is to learn edges and curves while the later layers learns about the important features. Hence the learning rate is set different for different set of layers. This concept is known as Differential Learning Rate . learn.unfreeze()lr=np.array([1e-4,1e-3,1e-2]) After making the required changes , train the model as shown below . Earlier cycle_len=1 and number_of_cycles=3 parameters were discussed . Just a refresher again, cycle_len=1 is the number of epoch and number_of_cycles=3 means the learner will do 3 cycles each of 1 epoch. Now a new parameter has been introduced named as cycle_mult=2. This cycle_mult parameter multiplies the length of each cycle after each cycle . Here the multiplication factor is 2. Hence (1+2*1 +2*2 )epoch=7 epoch. What this translates to is if the cycle length is too short , it starts going down to find a reasonably good spot and then pops out and again goes down and pops out . It never actually gets to find a good spot , that is both a good minima as well as good at generalizing . Its a matter of chance . Its not exploring the surface. So to explore the surface more set cycle_mult=2. Now the graph looks like more exploring:- As observed, till now the accuracy has increased till 99.0% and the losses have drastically decreased a lot . There is one last way to make the model better . Its known as TEST TIME AUGMENTATION (TTA) On Validation /Test dataset , all of the inputs are required to be a square . This helps the GPU in fast processing . It won’t process fast if the input images in validation dataset are of different dimensions . To make this consistent it squares out the picture in the middle. As in this following example:- If the picture above is squared out in the center , it will be tough for the model to predict if its a dog or cat as its only the body that gets into the validation dataset. For this (Test Time Augmentation) TTA is being used. It will take four data augmentation at random as well as the unaugmented original center cropped image. Then it takes the average of all the prediction on all these images .That’s our final prediction. Note:- Applicable to test and validation data set only. As seen above, the accuracy after applying TTA is 99.35% . To get a summary of our classifier , plot a confusion matrix. Confusion matrix is used in classification to know how many were correctly or incorrectly predicted as shown in the image below. Interpretation of the Confusion Matrix:- The confusion matrix speaks about how good our classifier is . As seen above, the dark blue regions has been classified correctly . 996 cat pictures has been classified as cats and 993 dog pictures has been classified as dogs correctly. 7 dog pictures has been classified as cats and 4 cat pictures has been classified as dogs. Hence our Classifier is doing a pretty good job. Hope you find this post helpful . In my future blog post we will go deep . Because of lots of important concepts covered, You might feel like this now. !! Hang on , More such interesting stuff coming soon . Until then Goodbye 😉!! P.S. — In case you are interested checkout the code here . A B C- Always be clapping . 👏 👏👏👏👏😃😃😃😃😃😃😃😃😃👏 👏👏👏👏 👏 Edit 1:- TFW Jeremy Howard approves of your post . 😃😃😃😃😃😃 To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:- Dog Vs Cat Image ClassificationDog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2 Dog Vs Cat Image Classification Dog Breed Image Classification Multi-label Image Classification Time Series Analysis using Neural Network NLP- Sentiment Analysis on IMDB Movie Dataset Basic of Movie Recommendation System Collaborative Filtering from Scratch Collaborative Filtering using Neural Network Writing Philosophy like Nietzsche Performance of Different Neural Network on Cifar-10 dataset ML Model to detect the biggest object in an image Part-1 ML Model to detect the biggest object in an image Part-2
[ { "code": null, "e": 525, "s": 172, "text": "I’ve been going through fast.ai for a couple of months . I got to admit that there were lots of stuffs and awesome techniques that I learned in the process. I’ll make sure to update all those in my Blog . All thanks to Jeremy Howard and Rachel Thomas for their efforts to democratize AI. Thanks to the awesome fast.ai community for all the quick help ." }, { "code": null, "e": 607, "s": 525, "text": "This below picture depicts my journey till now which makes it an interesting one." }, { "code": null, "e": 727, "s": 607, "text": "To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:-" }, { "code": null, "e": 1227, "s": 727, "text": "Dog Vs Cat Image ClassificationDog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2" }, { "code": null, "e": 1259, "s": 1227, "text": "Dog Vs Cat Image Classification" }, { "code": null, "e": 1290, "s": 1259, "text": "Dog Breed Image Classification" }, { "code": null, "e": 1323, "s": 1290, "text": "Multi-label Image Classification" }, { "code": null, "e": 1365, "s": 1323, "text": "Time Series Analysis using Neural Network" }, { "code": null, "e": 1411, "s": 1365, "text": "NLP- Sentiment Analysis on IMDB Movie Dataset" }, { "code": null, "e": 1448, "s": 1411, "text": "Basic of Movie Recommendation System" }, { "code": null, "e": 1485, "s": 1448, "text": "Collaborative Filtering from Scratch" }, { "code": null, "e": 1530, "s": 1485, "text": "Collaborative Filtering using Neural Network" }, { "code": null, "e": 1564, "s": 1530, "text": "Writing Philosophy like Nietzsche" }, { "code": null, "e": 1624, "s": 1564, "text": "Performance of Different Neural Network on Cifar-10 dataset" }, { "code": null, "e": 1681, "s": 1624, "text": "ML Model to detect the biggest object in an image Part-1" }, { "code": null, "e": 1738, "s": 1681, "text": "ML Model to detect the biggest object in an image Part-2" }, { "code": null, "e": 1805, "s": 1738, "text": "So Brace yourselves and focus on Part 1 Lesson 2 of Fastai course." }, { "code": null, "e": 1939, "s": 1805, "text": "This blog post deals with Dogs vs Cats Classification Model. It has been taught by Jeremy Howard in Part 1 Lesson 2 of FastAI Course." }, { "code": null, "e": 2006, "s": 1939, "text": "Import all the libraries as below that will be used in this Model." }, { "code": null, "e": 2632, "s": 2006, "text": "!pip install fastai==0.7.0!pip install torchtext==0.2.3!pip3 install http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl !pip3 install torchvisionimport fastaifrom matplotlib import pyplot as plt# Put these at the top of every notebook, to get automatic reloading # and inline plotting%reload_ext autoreload%autoreload 2%matplotlib inline# This file contains all the main external libs we'll use# from fastai.imports import *from fastai.transforms import *from fastai.conv_learner import *from fastai.model import *from fastai.dataset import *from fastai.sgdr import *from fastai.plots import *" }, { "code": null, "e": 2702, "s": 2632, "text": "Check for whether GPU has been enabled using the following commands:-" }, { "code": null, "e": 2755, "s": 2702, "text": "The output to the above commands should return True." }, { "code": null, "e": 2851, "s": 2755, "text": "Before delving forward, I would like to mention couple of Linux Command that might come handy ." }, { "code": null, "e": 2893, "s": 2851, "text": "Use these commands prefixed by ‘!’ mark ." }, { "code": null, "e": 3065, "s": 2893, "text": "!ls is a command to list files present in current directory.!pwd stands for Print work directory . Will print the path of working directory!cd stands for change directory." }, { "code": null, "e": 3126, "s": 3065, "text": "!ls is a command to list files present in current directory." }, { "code": null, "e": 3206, "s": 3126, "text": "!pwd stands for Print work directory . Will print the path of working directory" }, { "code": null, "e": 3239, "s": 3206, "text": "!cd stands for change directory." }, { "code": null, "e": 3303, "s": 3239, "text": "The above three commands helps to navigate between directories." }, { "code": null, "e": 3380, "s": 3303, "text": "The images of dogs and cats has been downloaded using the following command." }, { "code": null, "e": 3430, "s": 3380, "text": "<< !wget http://files.fast.ai/data/dogscats.zip>>" }, { "code": null, "e": 3481, "s": 3430, "text": "The structure of the folder should be as follows:-" }, { "code": null, "e": 3522, "s": 3481, "text": "Set the path to where the data is stored" }, { "code": null, "e": 3552, "s": 3522, "text": "PATH = \"data/dogscats/\"sz=224" }, { "code": null, "e": 3627, "s": 3552, "text": "Check whether the files has been downloaded using the following command :-" }, { "code": null, "e": 3786, "s": 3627, "text": "The f ’ above stands for f-Strings .Its a new way to format Strings in Python. To know more about f-strings, please check this awesome link by realpython.com." }, { "code": null, "e": 4336, "s": 3786, "text": "The Classification task will make use of pre-trained model . A pre-trained model is one which has been trained on similar type of data by someone else. So instead of training the model from scratch , a model will be used that has been trained on ImageNet. ImageNet is a dataset consisting of 1.2 million images and 1000 classes. ResNet34 is the version of the Model that will be used . Its a Special type of Convolutional Neural Network. ResNet34 won the 2015 ImageNet Competition. The details of ResNet will be discussed in the upcoming blog post ." }, { "code": null, "e": 4407, "s": 4336, "text": "The following lines of Code shows how to train the model using fastai." }, { "code": null, "e": 4650, "s": 4407, "text": "The architecture resnet34 which is used has been saved in arch variable . The data is saved in data variable as it looks for the data in the PATH specified earlier . The tfms is a part of data augmentation which will be dealt later in detail." }, { "code": null, "e": 4872, "s": 4650, "text": "The pre-trained method creates the new Neural Network from the arch model(resnet34). The fit method trains the model using the learning rate and the number of epochs specified. And an accuracy of 0.9895 has been obtained." }, { "code": null, "e": 4889, "s": 4872, "text": "GRADIENT DESCENT" }, { "code": null, "e": 5460, "s": 4889, "text": "Let me explain the above image. Initially the parameters that has been chosen were random. The loss was high at this point of time . High Loss indicates that during training, the difference between the ‘outcome / predicted value’ and the ‘ target value/ labels ’ is more. Hence an approach should be followed using which this difference should be made least . Convergence or reaching to the local minima means the loss is minimum at this point and hence the difference between the outcome and target value /labels is the least. This process is known as Gradient Descent." }, { "code": null, "e": 5476, "s": 5460, "text": "LEARNING RATE:-" }, { "code": null, "e": 6045, "s": 5476, "text": "The Learning rate(LR) in the fit function above is one of the most important parameters and should be carefully chosen so as to make the model reach an optimal solution in a fast and efficient way. It basically says how to quickly reach the optimal point in the function .If LR is low the process is slow and if its too high then there is a great chance that it might overshoot the minima. So the LR has to be carefully chosen , so as to make sure the convergence (reaching the local minima) happens in a efficient manner . The image below describes the above concept." }, { "code": null, "e": 6084, "s": 6045, "text": "How to Choose the Best Learning Rate ?" }, { "code": null, "e": 6214, "s": 6084, "text": "!!! Don’t worry , Jeremy Howard has your back. Jeremy has mentioned a wonderful way of finding the Learning rate and its known as" }, { "code": null, "e": 6236, "s": 6214, "text": "LEARNING RATE FINDER." }, { "code": null, "e": 6265, "s": 6236, "text": "Please check the code below." }, { "code": null, "e": 6762, "s": 6265, "text": "Using lr_find() the optimal learning rate can be obtained. As the Learning rate vs iteration graph shows, the LR is being increased after each minibatch and it increases exponentially . In the 2nd plot i.e Loss vs Learning rate , its observed that the Loss decreases for a while as the Learning rate increases and when Learning rate is at 0.1 the loss is at its minimum , post which it starts to rise again (which means the LR is so high that it has overshoot the minima and the loss gets worse)." }, { "code": null, "e": 6827, "s": 6762, "text": "To choose the best learning rate, here are the following steps:-" }, { "code": null, "e": 6989, "s": 6827, "text": "Determine the lowest point in the Loss vs Learning rate graph above (i.e at 0.1)Take a step back by magnitude 1 (i.e at 0.01) and choose that as a Learning Rate." }, { "code": null, "e": 7070, "s": 6989, "text": "Determine the lowest point in the Loss vs Learning rate graph above (i.e at 0.1)" }, { "code": null, "e": 7152, "s": 7070, "text": "Take a step back by magnitude 1 (i.e at 0.01) and choose that as a Learning Rate." }, { "code": null, "e": 7196, "s": 7152, "text": "Concept behind Going back by magnitude 1 :-" }, { "code": null, "e": 7411, "s": 7196, "text": "Although at this point the Loss is at minimum but the Learning rate chosen at this point is too high and continuing with this learning rate, won’t yield in convergence. Please check the image below for explanation." }, { "code": null, "e": 7546, "s": 7411, "text": "NOTE :- Learning rate finder is one of the most important hyperparameter and if adjusted /chosen properly will yield the best results." }, { "code": null, "e": 7566, "s": 7546, "text": "IMPROVING THE MODEL" }, { "code": null, "e": 7690, "s": 7566, "text": "One way to improve the model is by giving it more data . Hence we use data augmentation . Wait , But Why Data Augmentation?" }, { "code": null, "e": 8383, "s": 7690, "text": "Our model generally has a couple of million of parameters and when trained for more number epoch there is a great probability , it might start overfitting . Overfitting means the model is over learning the specific details of the images in the training dataset and it might not generalize well on the validation dataset or test dataset . In other words , Overfitting is said to happen when the accuracy of the validation dataset is less than the accuracy of the training dataset(or the loss calculated on the training dataset is much less than the loss calculated on the validation dataset). So Overfitting can be avoided by providing more data to the model , hence data augmentation is used." }, { "code": null, "e": 8545, "s": 8383, "text": "Note:-Data Augmentation is not creating new data , but allows the Convolution Neural Network to learn how to recognize dogs or cats from a very different angle ." }, { "code": null, "e": 8971, "s": 8545, "text": "For data augmentation we pass transforms_side_on to aug_tfms in tfms_from_model() function. transforms_side_on will give different versions of image by flipping it horizontally. It makes the NN to see the images , as if it has been taken from side angle, rotate them by small amounts and slightly vary their contrasts , brightness and slightly zoom in a bit , move around a bit. The variations can be seen in the image below." }, { "code": null, "e": 9032, "s": 8971, "text": "For data augmentation to take place write the following code" }, { "code": null, "e": 9166, "s": 9032, "text": "tfms = tfms_from_model(resnet34, sz, aug_tfms=transforms_side_on, max_zoom=1.1)data = ImageClassifierData.from_paths(PATH, tfms=tfms)" }, { "code": null, "e": 9313, "s": 9166, "text": "Although there is room created for data augmentation , yet the data augmentation wont work, because initially it has been set as precompute=True ." }, { "code": null, "e": 9402, "s": 9313, "text": "Let me explain in detail the following code and its relation with above made statement:-" }, { "code": null, "e": 9534, "s": 9402, "text": "data = ImageClassifierData.from_paths(PATH, tfms=tfms)learn = ConvLearner.pretrained(arch, data, precompute=True)learn.fit(1e-2, 1)" }, { "code": null, "e": 10367, "s": 9534, "text": "When declaring the architecture using ConvLearner.pretrained(...) , the precompute is set as True which says to implement the activations from the pretrained network. A pretrained network is one which has already learnt to recognize certain things. For our Dog vs Cat study , the pretrained network used, has already learned to classify 1000 classes on 1.2 million images in ImageNet Dataset. So take the penultimate layer (as this is the layer which has all the required information necessary to figure out what the image is ) and save these activations. Save these activations for each of the image and these are known as precomputed activations. Now when creating a new classifier , take advantage of these precomputed activation and quickly train a model based on those activations. Hence to implement this set precompute=True ." }, { "code": null, "e": 10746, "s": 10367, "text": "Note:- When precompute=True , data augmentation doesn’t work as it is currently using a particular version of the augmented cat or in other words even though a different version of cat is being showed each time , the activation for a particular version of cat has been has been precomputed. It takes a minute or two to precompute the activations when it runs for the first time." }, { "code": null, "e": 10815, "s": 10746, "text": "When trained using precomputed activations , the accuracy is 98.8%:-" }, { "code": null, "e": 11001, "s": 10815, "text": "To put data augmentation to work , set precompute=False and check for the accuracy. In the code below cycle_len is an important parameter and will be dealt in detail later in this post." }, { "code": null, "e": 11184, "s": 11001, "text": "The accuracy has increased a bit to 99.1% and the good news is that , it is not overfitting and the training loss has decreased further . To further improve the model lets focus on:-" }, { "code": null, "e": 11232, "s": 11184, "text": "SGDR(STOCHASTIC GRADIENT DESCENT WITH RESTARTS)" }, { "code": null, "e": 11541, "s": 11232, "text": "SGDR says as we get closer and closer to the minima ,lets decrease the learning rate . The idea of decreasing the learning rate as we train (i.e with more number of iterations) is known as Learning Rate Annealing . There is Step Wise and Cosine Annealing . In this Course Jeremy Howard uses Cosine Annealing." }, { "code": null, "e": 11728, "s": 11541, "text": "In Cosine Annealing , we train using a higher learning rate when not near minima .When getting close to local minima , switch to a low learning rate and do few iterations on top of this." }, { "code": null, "e": 11970, "s": 11728, "text": "The above diagram shows a simple loss function . In real , the datasets are represented in a very high dimensional space and there is lot of fairly flat points and these aren’t local minima. Suppose our surface looks like the below diagram:-" }, { "code": null, "e": 12752, "s": 11970, "text": "Started at the red point no 1 and reached the global minima as shown by red point no 2 but here it doesn’t generalize very well . If this solution is used, in case of slightly different dataset , it will not lead to a good result. On the other hand red point no 3 , will generalize very well in case of slightly different dataset. Our Standard Learning rate annealing approach will go downhill to one spot and in high dimension there is a great chance of being stuck in a spiky zone , where it will not generalize better , hence not a good solution . Instead a Learning rate scheduler can be deployed which will reset and do a cosine annealing and jump again so that it will jump from point 2 to point 3 and so on , until it reaches a point where the generalization is really good." }, { "code": null, "e": 12966, "s": 12752, "text": "Each time the Learning rate is reset it will again increase the Learning rate which will lead to leaving the nasty spiky part of the surface and eventually jumps to a nice smooth bowl which will generalize better." }, { "code": null, "e": 13308, "s": 12966, "text": "This above process is known as SGDR(Stochastic Gradient Descent with Restarts). The best part of this SGDR is once a “nice smooth curve like surface” is reached , it wont restart anymore . It actually hangs out in this nice part of the space and then keeps getting better at finding the reasonably good spot . Please check the diagram below." }, { "code": null, "e": 13704, "s": 13308, "text": "Using SGDR along with Learning rate finder will give us better results . From learning rate finder try to visually pick up a good learning rate or else in SGDR it wont jump up to a nice smooth like surface . The reset of the learning rate happens with the help of cycle_len parameter . It basically means reset the learning rate after every 1 epoch. The below image shows how the reset happens:-" }, { "code": null, "e": 14009, "s": 13704, "text": "Note:- Resetting of learning rate happens after every single epoch as cycle_len=1 and Learning rate keeps changing after every single mini batch. The y axis is the learning rate where 0.010 is the learning rate we get from learning rate finder. So SGDR will shuffle the learning rate between 0 and 0.010." }, { "code": null, "e": 14109, "s": 14009, "text": "It is advised to keep saving the model at intermediate steps. To do so use the following commands:-" }, { "code": null, "e": 14164, "s": 14109, "text": "learn.save('224_lastlayer')learn.load('224_lastlayer')" }, { "code": null, "e": 14248, "s": 14164, "text": "The model is saved in the models folder within the dogscats folder as shown below:-" }, { "code": null, "e": 14544, "s": 14248, "text": "All the precomputed activations are saved in the tmp folder . So in case of weird errors , may be due to half completed precomputed activations or in some other way , go ahead and delete the tmp folder and check if the error has gone away. This is the fastai way of turning it off and on again ." }, { "code": null, "e": 14673, "s": 14544, "text": "Note:- Precomputed activation are without any training. These are what pretrained models created with the weights we downloaded." }, { "code": null, "e": 14719, "s": 14673, "text": "What else can we do to make the model better?" }, { "code": null, "e": 15498, "s": 14719, "text": "So far the pretrained activations has been downloaded and directly used . The pretrained activations or the precomputed weights in the CNN kernels are left untouched (i.e no retraining of precomputed weights has been done yet). The pretrained model already knows how to find at early stages edges, curves, gradients and then repeating patterns and eventually the main features. Until now, only new layers were being added on the top and models learned how to mix and match the pretrained features. If a model trained on Imagenet is extended to case like “Satellite images classification” where the features are completely different , most of the layers are needed to be retrained as the features are completely different. Hence a new concept is needed to be explored named as :-" }, { "code": null, "e": 15541, "s": 15498, "text": "FINE TUNING AND DIFFERENTIAL LEARNING RATE" }, { "code": null, "e": 15753, "s": 15541, "text": "To learn a different set of features or to tell the learner that the convolution filters are needed to be changed , simply unfreeze all the layers .A frozen layer is one whose weights are not trained or updated." }, { "code": null, "e": 15820, "s": 15753, "text": "!!! Okay Okay Elsa ,I’ll let it go and unfreeze the layers !!! 😍 😍" }, { "code": null, "e": 16261, "s": 15820, "text": "Unfreezing the layers will make the layer weights open to training or updating. But the initial layers need little or any training as compared to the later layers . This holds universally true because the work of initial layers is to learn edges and curves while the later layers learns about the important features. Hence the learning rate is set different for different set of layers. This concept is known as Differential Learning Rate ." }, { "code": null, "e": 16307, "s": 16261, "text": "learn.unfreeze()lr=np.array([1e-4,1e-3,1e-2])" }, { "code": null, "e": 16376, "s": 16307, "text": "After making the required changes , train the model as shown below ." }, { "code": null, "e": 17216, "s": 16376, "text": "Earlier cycle_len=1 and number_of_cycles=3 parameters were discussed . Just a refresher again, cycle_len=1 is the number of epoch and number_of_cycles=3 means the learner will do 3 cycles each of 1 epoch. Now a new parameter has been introduced named as cycle_mult=2. This cycle_mult parameter multiplies the length of each cycle after each cycle . Here the multiplication factor is 2. Hence (1+2*1 +2*2 )epoch=7 epoch. What this translates to is if the cycle length is too short , it starts going down to find a reasonably good spot and then pops out and again goes down and pops out . It never actually gets to find a good spot , that is both a good minima as well as good at generalizing . Its a matter of chance . Its not exploring the surface. So to explore the surface more set cycle_mult=2. Now the graph looks like more exploring:-" }, { "code": null, "e": 17388, "s": 17216, "text": "As observed, till now the accuracy has increased till 99.0% and the losses have drastically decreased a lot . There is one last way to make the model better . Its known as" }, { "code": null, "e": 17417, "s": 17388, "text": "TEST TIME AUGMENTATION (TTA)" }, { "code": null, "e": 17726, "s": 17417, "text": "On Validation /Test dataset , all of the inputs are required to be a square . This helps the GPU in fast processing . It won’t process fast if the input images in validation dataset are of different dimensions . To make this consistent it squares out the picture in the middle. As in this following example:-" }, { "code": null, "e": 18155, "s": 17726, "text": "If the picture above is squared out in the center , it will be tough for the model to predict if its a dog or cat as its only the body that gets into the validation dataset. For this (Test Time Augmentation) TTA is being used. It will take four data augmentation at random as well as the unaugmented original center cropped image. Then it takes the average of all the prediction on all these images .That’s our final prediction." }, { "code": null, "e": 18211, "s": 18155, "text": "Note:- Applicable to test and validation data set only." }, { "code": null, "e": 18270, "s": 18211, "text": "As seen above, the accuracy after applying TTA is 99.35% ." }, { "code": null, "e": 18461, "s": 18270, "text": "To get a summary of our classifier , plot a confusion matrix. Confusion matrix is used in classification to know how many were correctly or incorrectly predicted as shown in the image below." }, { "code": null, "e": 18502, "s": 18461, "text": "Interpretation of the Confusion Matrix:-" }, { "code": null, "e": 18879, "s": 18502, "text": "The confusion matrix speaks about how good our classifier is . As seen above, the dark blue regions has been classified correctly . 996 cat pictures has been classified as cats and 993 dog pictures has been classified as dogs correctly. 7 dog pictures has been classified as cats and 4 cat pictures has been classified as dogs. Hence our Classifier is doing a pretty good job." }, { "code": null, "e": 19031, "s": 18879, "text": "Hope you find this post helpful . In my future blog post we will go deep . Because of lots of important concepts covered, You might feel like this now." }, { "code": null, "e": 19109, "s": 19031, "text": "!! Hang on , More such interesting stuff coming soon . Until then Goodbye 😉!!" }, { "code": null, "e": 19168, "s": 19109, "text": "P.S. — In case you are interested checkout the code here ." }, { "code": null, "e": 19220, "s": 19168, "text": "A B C- Always be clapping . 👏 👏👏👏👏😃😃😃😃😃😃😃😃😃👏 👏👏👏👏 👏" }, { "code": null, "e": 19278, "s": 19220, "text": "Edit 1:- TFW Jeremy Howard approves of your post . 😃😃😃😃😃😃" }, { "code": null, "e": 19398, "s": 19278, "text": "To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:-" }, { "code": null, "e": 19898, "s": 19398, "text": "Dog Vs Cat Image ClassificationDog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2" }, { "code": null, "e": 19930, "s": 19898, "text": "Dog Vs Cat Image Classification" }, { "code": null, "e": 19961, "s": 19930, "text": "Dog Breed Image Classification" }, { "code": null, "e": 19994, "s": 19961, "text": "Multi-label Image Classification" }, { "code": null, "e": 20036, "s": 19994, "text": "Time Series Analysis using Neural Network" }, { "code": null, "e": 20082, "s": 20036, "text": "NLP- Sentiment Analysis on IMDB Movie Dataset" }, { "code": null, "e": 20119, "s": 20082, "text": "Basic of Movie Recommendation System" }, { "code": null, "e": 20156, "s": 20119, "text": "Collaborative Filtering from Scratch" }, { "code": null, "e": 20201, "s": 20156, "text": "Collaborative Filtering using Neural Network" }, { "code": null, "e": 20235, "s": 20201, "text": "Writing Philosophy like Nietzsche" }, { "code": null, "e": 20295, "s": 20235, "text": "Performance of Different Neural Network on Cifar-10 dataset" }, { "code": null, "e": 20352, "s": 20295, "text": "ML Model to detect the biggest object in an image Part-1" } ]
A Beginner’s Guide to Rasa NLU for Intent Classification and Named-entity Recognition | by Ng Wai Foong | Towards Data Science
The purpose of this article is to explore the new way to use Rasa NLU for intent classification and named-entity recognition. Since version 1.0.0, both Rasa NLU and Rasa Core have been merged into a single framework. As a results, there are some minor changes to the training process and the functionality available. First and foremost, Rasa is an open source machine learning framework to automate text-and voice-based conversation. In other words, you can use Rasa to build create contextual and layered conversations akin to an intelligent chatbot. In this tutorial, we will be focusing on the natural-language understanding part of the framework to capture user’s intention. As of October 2020, Rasa has officially released version 2.0 (Rasa Open Source). The data training format has changed significantly from version 1. Check my latest article on Chatbots and What’s New in Rasa 2.0 for more information on it. There are 5 sections in this tutorial: Setup and installationData preparation and formatTraining and testingRunning NLU ServerConclusion Setup and installation Data preparation and format Training and testing Running NLU Server Conclusion I am using Python 3.6.7 installed in a virtual environment of a Windows operating system. It is recommended to install it in a clean virtual environment as the there are quite a number of python modules to be installed. For simplicity, we will just install a standard pipeline that can be used for all languages. In the official documentation, the team recommends using spaCy pipeline but we will be using the supervised_embeddings pipeline which is based on Tensorflow. Activate the virtual environment and run the following command: pip install rasa It may take a while for the modules installation and upgrade. Once it is completed, point to to a directory of your choice and run the following command: rasa init --no-prompt You will be able to see training process for both nlu and core using the default data. The following files will be created: __init__.py: An empty file that helps python find your actions.actions.py: Code for your custom actionsconfig.yml: Configuration of your NLU and Core modelscredentials.yml: Details for connecting to other servicesdata/nlu.md: Your NLU training datadata/stories.md: Your storiesdomain.yml: Your assistant’s domainendpoints.yml: Details for connecting to endpoint channelsmodels/<timestamp>.tar.gz: Your initial model. Timestamp is in the format of YYYYMMDD-hhmmss. NLU-only models will have nlu prefix at the front. __init__.py: An empty file that helps python find your actions. actions.py: Code for your custom actions config.yml: Configuration of your NLU and Core models credentials.yml: Details for connecting to other services data/nlu.md: Your NLU training data data/stories.md: Your stories domain.yml: Your assistant’s domain endpoints.yml: Details for connecting to endpoint channels models/<timestamp>.tar.gz: Your initial model. Timestamp is in the format of YYYYMMDD-hhmmss. NLU-only models will have nlu prefix at the front. In fact, you have already trained a complete model that can be used for intent classification. Let’s move on to the next section to learn more about the training data format. If you would like to train it using your own custom data, you can prepare it in either markdown or json format. I will be using markdown in this tutorial since it is the easiest. Kindly refer to the following link for more information on all the available training data format. Open up data/nlu.md data and start to modify the content according to your own use case. You can specify intent with ## intent:name_of_intent followed by a list of questions for the intent (space between each intent): ## intent:goodbye- bye- goodbye- see you around- see you later- talk to you later## intent:ask_identity- who are you- what is your name- how should i address you- may i know your name- are you a bot You can specify the entity inside each of the question as follow [value](name of entity): ## intent:ask_shop_open- does the shop open on [monday](weekday)- does the shop open on [wednesday](weekday)- does the shop open on [friday](weekday) In this case, weekday is the name of the entity and monday is the value. You need to provide a lot of examples in order to capture the entity. Please be noted that upper case and lower case affects the accuracy. Monday is not the same as monday. Hence, it is advisable to train all in lower case and parse input data to lower case during evaluation. If you have a long list of values for a single entity, it is advisable to include a lookup table instead of filling in all of them as example sentences. There are two ways to do it. The first one is to include them in-line: ## lookup:weekday- monday- tuesday- wednesday- thursday- friday The second is to list it in a text file and include the path in-line. Let’s try it with a new entity called countries: ## lookup:countriespath/to/countries.txt In the countries.txt, you can specify each of the element in a new line as follow: singaporemalaysiavietnamindonesiathailand Just like weekday entity, you have to provide a few examples for it to generalize. ## intent:inform_country_of_origin- i am from [malaysia](countries)- i am from [vietnam](countries)- i came from [thailand](countries) Rasa also provides a way to identify synonym and map it back to a single value. The first method is to add it inline like [synonym1](entity:value): ## intent:ask_eaten- what did you have for [breakfast](meal)- what did you have for [break fast](meal:breakfast)- what did you have for [breakfat](meal:breakfast) The second method is as follow: ## synonym:breakfast- brekfast- brokefast What makes synonym differs from lookup table is that synonym will map the value of the entity to a single value (breakfast in this example). In other words, synonym is great for catching spelling mistakes and acronym while lookup table is great for generalizing the examples. There is also a feature called regex that support regular expressions. ## intent:inform_zipcode- my zipcode is [12345](zipcode)- my zipcode is [33456](zipcode)- my zipcode is [94056](zipcode)## regex:zipcode- [0-9]{5} I have attached a sample text file for your reference: Markdown is arguably the safest choice for beginner to create the data. However, there can be cased where the training data is automated or came from other source such as LUIS data format, WIT data format, Dialogflow data format and json. Rasa also provides a way for you to convert the data format. Check out the following link to know more about it. Make sure that the virtual environment is activated and run the following command (it converts md to json): rasa data convert nlu --data data/nlu.md --out data/nlu.json -f json --data is the path to the file or directory containing Rasa NLU data.--out is the name of the file to save training data in Rasa format.-f is the output format the training data should be converted into. Accepts either json or md. --data is the path to the file or directory containing Rasa NLU data. --out is the name of the file to save training data in Rasa format. -f is the output format the training data should be converted into. Accepts either json or md. Once you have all the required data, move it to the data folder and remove any existing . let’s move on to the next section. To train the nlu model, you can just run the following command: rasa train nlu As stated in the official documentation, it will look for NLU training data files in the data folder and saves a trained model in the model folder. Remember to remove any unnecessary data files from the data folder. The name of the model will be prefixed with nlu- to indicate that this is a nlu-only model. Having said that, you can specify the path using the --data parameter. The full list of parameters can be found here. You can test the model by running an interactive shell mode via the following command: rasa shell nlu If you have multiple nlu models and would like to test a specific model, use the following command instead. rasa shell -m models/nlu-20190515-144445.tar.gz Check the following link to find out more about the additional parameters. You can input your text and press enter. The shell will return a json indicating the intent and confidence. Rasa also provides a way for you to start a nlu server which you can call via HTTP API. Run the following command (modify the name of the model accordingly): rasa run --enable-api -m models/nlu-20190515-144445.tar.gz You should see the following output: Starting Rasa Core server on http://localhost:5005 You can modify some settings by specifying the parameters together in the command. Check out the following link to find out more. For cors parameters, it accepts a list of URL. It allows Cross-Origin Resources Sharing that tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. You can use “*” to whitelist all the domains. rasa run --enable-api -m models/nlu-20190515-144445.tar.gz --cors "*" At the time of this writing, there seems to be no way to stop or interrupt the server. I did tried Ctrl+C but it only works from time to time. If you encounter such issue, the only way is to kill the process. Simply click close the command prompt and re-run it. Once the server is running, you can test the result using curl. Open up a new command prompt and run the following line: curl localhost:5005/model/parse -d '{"text":"hello"}' You should be able to obtain a json result indicating the intent and confidence level as follow: {"intent":{"name":"greet","confidence":0.9770460725},"entities":[],"intent_ranking":[{"name":"greet","confidence":0.9770460725},{"name":"mood_unhappy","confidence":0.0257926807},{"name":"ask_identity","confidence":0.0009481288},{"name":"mood_great","confidence":0.0},{"name":"inform_identity","confidence":0.0},{"name":"goodbye","confidence":0.0}],"text":"hello"} Rasa also comes with its own HTTP API that can be useful if you intent to call it via AJAX. Kindly refer the the full list here. In this tutorial, we will be concentrating on just one API call that is used to predict the intent and entities of the message posted to the end point. You can simply send a POST call to the following URL: http://localhost:5005/model/parse The following is an example via AJAX POST call: The latest framework removed the ability to call multiple model in a single server. In the previous framework, we can specify our own model as parameter to indicate which model to be used for classification. Now, it is officially one model per server. That’s it, folks! Let’s recap that we have learnt on how to use Rasa NLU to train our own model for intent classification and entity extractions. The next step is to fine-tune and conduct further training to optimize the current model. You can choose to check out Rasa Core as well if you intend to have a full-fledge chatbot framework that reply based on stories. On the other hand, using just NLU provides you with greater flexibility if you are already using other framework for your chatbot. If you are interested in setting up a chatbot in messaging platform, check out the following link. Thanks for reading and have a nice day!
[ { "code": null, "e": 851, "s": 172, "text": "The purpose of this article is to explore the new way to use Rasa NLU for intent classification and named-entity recognition. Since version 1.0.0, both Rasa NLU and Rasa Core have been merged into a single framework. As a results, there are some minor changes to the training process and the functionality available. First and foremost, Rasa is an open source machine learning framework to automate text-and voice-based conversation. In other words, you can use Rasa to build create contextual and layered conversations akin to an intelligent chatbot. In this tutorial, we will be focusing on the natural-language understanding part of the framework to capture user’s intention." }, { "code": null, "e": 1090, "s": 851, "text": "As of October 2020, Rasa has officially released version 2.0 (Rasa Open Source). The data training format has changed significantly from version 1. Check my latest article on Chatbots and What’s New in Rasa 2.0 for more information on it." }, { "code": null, "e": 1129, "s": 1090, "text": "There are 5 sections in this tutorial:" }, { "code": null, "e": 1227, "s": 1129, "text": "Setup and installationData preparation and formatTraining and testingRunning NLU ServerConclusion" }, { "code": null, "e": 1250, "s": 1227, "text": "Setup and installation" }, { "code": null, "e": 1278, "s": 1250, "text": "Data preparation and format" }, { "code": null, "e": 1299, "s": 1278, "text": "Training and testing" }, { "code": null, "e": 1318, "s": 1299, "text": "Running NLU Server" }, { "code": null, "e": 1329, "s": 1318, "text": "Conclusion" }, { "code": null, "e": 1549, "s": 1329, "text": "I am using Python 3.6.7 installed in a virtual environment of a Windows operating system. It is recommended to install it in a clean virtual environment as the there are quite a number of python modules to be installed." }, { "code": null, "e": 1864, "s": 1549, "text": "For simplicity, we will just install a standard pipeline that can be used for all languages. In the official documentation, the team recommends using spaCy pipeline but we will be using the supervised_embeddings pipeline which is based on Tensorflow. Activate the virtual environment and run the following command:" }, { "code": null, "e": 1881, "s": 1864, "text": "pip install rasa" }, { "code": null, "e": 2035, "s": 1881, "text": "It may take a while for the modules installation and upgrade. Once it is completed, point to to a directory of your choice and run the following command:" }, { "code": null, "e": 2057, "s": 2035, "text": "rasa init --no-prompt" }, { "code": null, "e": 2181, "s": 2057, "text": "You will be able to see training process for both nlu and core using the default data. The following files will be created:" }, { "code": null, "e": 2696, "s": 2181, "text": "__init__.py: An empty file that helps python find your actions.actions.py: Code for your custom actionsconfig.yml: Configuration of your NLU and Core modelscredentials.yml: Details for connecting to other servicesdata/nlu.md: Your NLU training datadata/stories.md: Your storiesdomain.yml: Your assistant’s domainendpoints.yml: Details for connecting to endpoint channelsmodels/<timestamp>.tar.gz: Your initial model. Timestamp is in the format of YYYYMMDD-hhmmss. NLU-only models will have nlu prefix at the front." }, { "code": null, "e": 2760, "s": 2696, "text": "__init__.py: An empty file that helps python find your actions." }, { "code": null, "e": 2801, "s": 2760, "text": "actions.py: Code for your custom actions" }, { "code": null, "e": 2855, "s": 2801, "text": "config.yml: Configuration of your NLU and Core models" }, { "code": null, "e": 2913, "s": 2855, "text": "credentials.yml: Details for connecting to other services" }, { "code": null, "e": 2949, "s": 2913, "text": "data/nlu.md: Your NLU training data" }, { "code": null, "e": 2979, "s": 2949, "text": "data/stories.md: Your stories" }, { "code": null, "e": 3015, "s": 2979, "text": "domain.yml: Your assistant’s domain" }, { "code": null, "e": 3074, "s": 3015, "text": "endpoints.yml: Details for connecting to endpoint channels" }, { "code": null, "e": 3219, "s": 3074, "text": "models/<timestamp>.tar.gz: Your initial model. Timestamp is in the format of YYYYMMDD-hhmmss. NLU-only models will have nlu prefix at the front." }, { "code": null, "e": 3394, "s": 3219, "text": "In fact, you have already trained a complete model that can be used for intent classification. Let’s move on to the next section to learn more about the training data format." }, { "code": null, "e": 3761, "s": 3394, "text": "If you would like to train it using your own custom data, you can prepare it in either markdown or json format. I will be using markdown in this tutorial since it is the easiest. Kindly refer to the following link for more information on all the available training data format. Open up data/nlu.md data and start to modify the content according to your own use case." }, { "code": null, "e": 3890, "s": 3761, "text": "You can specify intent with ## intent:name_of_intent followed by a list of questions for the intent (space between each intent):" }, { "code": null, "e": 4089, "s": 3890, "text": "## intent:goodbye- bye- goodbye- see you around- see you later- talk to you later## intent:ask_identity- who are you- what is your name- how should i address you- may i know your name- are you a bot" }, { "code": null, "e": 4179, "s": 4089, "text": "You can specify the entity inside each of the question as follow [value](name of entity):" }, { "code": null, "e": 4329, "s": 4179, "text": "## intent:ask_shop_open- does the shop open on [monday](weekday)- does the shop open on [wednesday](weekday)- does the shop open on [friday](weekday)" }, { "code": null, "e": 4679, "s": 4329, "text": "In this case, weekday is the name of the entity and monday is the value. You need to provide a lot of examples in order to capture the entity. Please be noted that upper case and lower case affects the accuracy. Monday is not the same as monday. Hence, it is advisable to train all in lower case and parse input data to lower case during evaluation." }, { "code": null, "e": 4903, "s": 4679, "text": "If you have a long list of values for a single entity, it is advisable to include a lookup table instead of filling in all of them as example sentences. There are two ways to do it. The first one is to include them in-line:" }, { "code": null, "e": 4967, "s": 4903, "text": "## lookup:weekday- monday- tuesday- wednesday- thursday- friday" }, { "code": null, "e": 5086, "s": 4967, "text": "The second is to list it in a text file and include the path in-line. Let’s try it with a new entity called countries:" }, { "code": null, "e": 5127, "s": 5086, "text": "## lookup:countriespath/to/countries.txt" }, { "code": null, "e": 5210, "s": 5127, "text": "In the countries.txt, you can specify each of the element in a new line as follow:" }, { "code": null, "e": 5252, "s": 5210, "text": "singaporemalaysiavietnamindonesiathailand" }, { "code": null, "e": 5335, "s": 5252, "text": "Just like weekday entity, you have to provide a few examples for it to generalize." }, { "code": null, "e": 5470, "s": 5335, "text": "## intent:inform_country_of_origin- i am from [malaysia](countries)- i am from [vietnam](countries)- i came from [thailand](countries)" }, { "code": null, "e": 5618, "s": 5470, "text": "Rasa also provides a way to identify synonym and map it back to a single value. The first method is to add it inline like [synonym1](entity:value):" }, { "code": null, "e": 5781, "s": 5618, "text": "## intent:ask_eaten- what did you have for [breakfast](meal)- what did you have for [break fast](meal:breakfast)- what did you have for [breakfat](meal:breakfast)" }, { "code": null, "e": 5813, "s": 5781, "text": "The second method is as follow:" }, { "code": null, "e": 5855, "s": 5813, "text": "## synonym:breakfast- brekfast- brokefast" }, { "code": null, "e": 6131, "s": 5855, "text": "What makes synonym differs from lookup table is that synonym will map the value of the entity to a single value (breakfast in this example). In other words, synonym is great for catching spelling mistakes and acronym while lookup table is great for generalizing the examples." }, { "code": null, "e": 6202, "s": 6131, "text": "There is also a feature called regex that support regular expressions." }, { "code": null, "e": 6349, "s": 6202, "text": "## intent:inform_zipcode- my zipcode is [12345](zipcode)- my zipcode is [33456](zipcode)- my zipcode is [94056](zipcode)## regex:zipcode- [0-9]{5}" }, { "code": null, "e": 6404, "s": 6349, "text": "I have attached a sample text file for your reference:" }, { "code": null, "e": 6864, "s": 6404, "text": "Markdown is arguably the safest choice for beginner to create the data. However, there can be cased where the training data is automated or came from other source such as LUIS data format, WIT data format, Dialogflow data format and json. Rasa also provides a way for you to convert the data format. Check out the following link to know more about it. Make sure that the virtual environment is activated and run the following command (it converts md to json):" }, { "code": null, "e": 6933, "s": 6864, "text": "rasa data convert nlu --data data/nlu.md --out data/nlu.json -f json" }, { "code": null, "e": 7164, "s": 6933, "text": "--data is the path to the file or directory containing Rasa NLU data.--out is the name of the file to save training data in Rasa format.-f is the output format the training data should be converted into. Accepts either json or md." }, { "code": null, "e": 7234, "s": 7164, "text": "--data is the path to the file or directory containing Rasa NLU data." }, { "code": null, "e": 7302, "s": 7234, "text": "--out is the name of the file to save training data in Rasa format." }, { "code": null, "e": 7397, "s": 7302, "text": "-f is the output format the training data should be converted into. Accepts either json or md." }, { "code": null, "e": 7522, "s": 7397, "text": "Once you have all the required data, move it to the data folder and remove any existing . let’s move on to the next section." }, { "code": null, "e": 7586, "s": 7522, "text": "To train the nlu model, you can just run the following command:" }, { "code": null, "e": 7601, "s": 7586, "text": "rasa train nlu" }, { "code": null, "e": 8027, "s": 7601, "text": "As stated in the official documentation, it will look for NLU training data files in the data folder and saves a trained model in the model folder. Remember to remove any unnecessary data files from the data folder. The name of the model will be prefixed with nlu- to indicate that this is a nlu-only model. Having said that, you can specify the path using the --data parameter. The full list of parameters can be found here." }, { "code": null, "e": 8114, "s": 8027, "text": "You can test the model by running an interactive shell mode via the following command:" }, { "code": null, "e": 8129, "s": 8114, "text": "rasa shell nlu" }, { "code": null, "e": 8237, "s": 8129, "text": "If you have multiple nlu models and would like to test a specific model, use the following command instead." }, { "code": null, "e": 8285, "s": 8237, "text": "rasa shell -m models/nlu-20190515-144445.tar.gz" }, { "code": null, "e": 8468, "s": 8285, "text": "Check the following link to find out more about the additional parameters. You can input your text and press enter. The shell will return a json indicating the intent and confidence." }, { "code": null, "e": 8626, "s": 8468, "text": "Rasa also provides a way for you to start a nlu server which you can call via HTTP API. Run the following command (modify the name of the model accordingly):" }, { "code": null, "e": 8685, "s": 8626, "text": "rasa run --enable-api -m models/nlu-20190515-144445.tar.gz" }, { "code": null, "e": 8722, "s": 8685, "text": "You should see the following output:" }, { "code": null, "e": 8773, "s": 8722, "text": "Starting Rasa Core server on http://localhost:5005" }, { "code": null, "e": 9195, "s": 8773, "text": "You can modify some settings by specifying the parameters together in the command. Check out the following link to find out more. For cors parameters, it accepts a list of URL. It allows Cross-Origin Resources Sharing that tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. You can use “*” to whitelist all the domains." }, { "code": null, "e": 9265, "s": 9195, "text": "rasa run --enable-api -m models/nlu-20190515-144445.tar.gz --cors \"*\"" }, { "code": null, "e": 9648, "s": 9265, "text": "At the time of this writing, there seems to be no way to stop or interrupt the server. I did tried Ctrl+C but it only works from time to time. If you encounter such issue, the only way is to kill the process. Simply click close the command prompt and re-run it. Once the server is running, you can test the result using curl. Open up a new command prompt and run the following line:" }, { "code": null, "e": 9702, "s": 9648, "text": "curl localhost:5005/model/parse -d '{\"text\":\"hello\"}'" }, { "code": null, "e": 9799, "s": 9702, "text": "You should be able to obtain a json result indicating the intent and confidence level as follow:" }, { "code": null, "e": 10163, "s": 9799, "text": "{\"intent\":{\"name\":\"greet\",\"confidence\":0.9770460725},\"entities\":[],\"intent_ranking\":[{\"name\":\"greet\",\"confidence\":0.9770460725},{\"name\":\"mood_unhappy\",\"confidence\":0.0257926807},{\"name\":\"ask_identity\",\"confidence\":0.0009481288},{\"name\":\"mood_great\",\"confidence\":0.0},{\"name\":\"inform_identity\",\"confidence\":0.0},{\"name\":\"goodbye\",\"confidence\":0.0}],\"text\":\"hello\"}" }, { "code": null, "e": 10498, "s": 10163, "text": "Rasa also comes with its own HTTP API that can be useful if you intent to call it via AJAX. Kindly refer the the full list here. In this tutorial, we will be concentrating on just one API call that is used to predict the intent and entities of the message posted to the end point. You can simply send a POST call to the following URL:" }, { "code": null, "e": 10532, "s": 10498, "text": "http://localhost:5005/model/parse" }, { "code": null, "e": 10580, "s": 10532, "text": "The following is an example via AJAX POST call:" }, { "code": null, "e": 10832, "s": 10580, "text": "The latest framework removed the ability to call multiple model in a single server. In the previous framework, we can specify our own model as parameter to indicate which model to be used for classification. Now, it is officially one model per server." } ]
Java program to print a given matrix in Spiral Form.
Following is a Java program to print the spiral form of a given matrix. Live Demo public class PrintMatrixInSpiralForm { public static void main(String args[]){ int a[][]={{1,2,3},{4,5,6},{7,8,9}}; int w = 0; int x = a.length-1; int y = 0; int z = a[0].length-1; while(w <= x && y <= z){ for (int i = w; i <= z; i++) { System.out.print(a[w][i] + " "); } for (int i = w+1; i <= x; i++) { System.out.print(a[i][z] + " "); } if(w+1 <= x){ for (int i = z-1; i >= y; i--) { System.out.print(a[x][i] + " "); } } if(y+1 <= z){ for (int i = x-1; i > w; i--) { System.out.print(a[i][y] + " "); } } w++; x--; y++; z--; } } } 1 2 3 6 9 8 7 4 5
[ { "code": null, "e": 1134, "s": 1062, "text": "Following is a Java program to print the spiral form of a given matrix." }, { "code": null, "e": 1145, "s": 1134, "text": " Live Demo" }, { "code": null, "e": 1936, "s": 1145, "text": "public class PrintMatrixInSpiralForm {\n public static void main(String args[]){\n int a[][]={{1,2,3},{4,5,6},{7,8,9}};\n int w = 0;\n int x = a.length-1;\n int y = 0;\n int z = a[0].length-1;\n while(w <= x && y <= z){\n for (int i = w; i <= z; i++) {\n System.out.print(a[w][i] + \" \");\n }\n for (int i = w+1; i <= x; i++) {\n System.out.print(a[i][z] + \" \");\n }\n if(w+1 <= x){\n for (int i = z-1; i >= y; i--) {\n System.out.print(a[x][i] + \" \");\n }\n }\n if(y+1 <= z){\n for (int i = x-1; i > w; i--) {\n System.out.print(a[i][y] + \" \");\n }\n }\n w++;\n x--;\n y++;\n z--;\n }\n }\n}" }, { "code": null, "e": 1954, "s": 1936, "text": "1 2 3 6 9 8 7 4 5" } ]
What is Sparsemax?. A useful variation of softmax | by Michael Larionov, PhD | Towards Data Science
In machine learning, there are several very useful functions, for example, sigmoid, relu, softmax. The latter is widely used in multi-class classification problems as an output layer of the Neural networks: This function has a useful property: the sum of its elements is one, which makes it very useful to model probabilities. It is also differentiable everywhere and the derivative is never zero, which make it useful in the backpropagation algorithms. in contrast, the derivative of the argmax function, that softmax is called to replace, is always zero. Another useful property is that this function preserves the support of the posterior probability distribution because the output probabilities are never zero, however small values they may be. But sometimes you want to have a sparse output, only preserving several values with non-zero probability. For this scenario, André F. T. Martins and Ramón F. Astudillo proposed a new function called sparsemax in their paper From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification. From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification Andre F. T. Martins ́ †] ANDRE.MARTINS@UNBABEL.COM Ramon F. Astudillo ́ † RAMON@UNBABEL.COM †Unbabel Lda, Rua Visconde de Santarem, 67-B, 1000-286 Lisboa, Portugal ́ ] Instituto de Telecomunicac ̧oes (IT), Instituto Superior T ̃ ecnico, Av. Rovisco Pais, 1, 1049-001 Lisboa, Portugal ́ Instituto de Engenharia de Sistemas e Computadores (INESC-ID), Rua Alves Redol, 9, 1000-029 Lisboa, Portugal Abstract We propose sparsemax, a new activation func- tion similar to the traditional softmax, but able to output sparse probabilities. After deriving its properties, we show how its Jacobian can be efficiently computed, enabling its use in a net- work trained with backpropagation. Then, we propose a new smooth and convex loss function which is the sparsemax analogue of the logis- tic loss. We reveal an unexpected connection between this new loss and the Huber classifi- cation loss. We obtain promising empirical re- sults in multi-label classification problems and in attention-based neural networks for natural lan- guage inference. For the latter, we achieve a sim- ilar performance as the traditional softmax, but with a selective, more compact, attention focus. 1. Introduction The softmax transformation is a key component of several statistical learning models, encompassing multinomial lo- gistic regression (McCullagh & Nelder, 1989), action se- lection in reinforcement learning (Sutton & Barto, 1998), and neural networks for multi-class classification (Bridle, 1990; Goodfellow et al., 2016). Recently, it has also been used to design attention mechanisms in neural networks, with important achievements in machine translation (Bah- danau et al., 2015), image caption generation (Xu et al., 2015), speech recognition (Chorowski et al., 2015), natural language understanding (Hermann et al., 2015; Sukhbaatar et al., 2015; Rocktaschel et al. ̈ , 2015), and computation learning (Graves et al., 2014; Grefenstette et al., 2015). There are a number of reasons why the softmax transfor- Proceedings of the 33 rd International Conference on Machine Learning, New York, NY, USA, 2016. JMLR: W&CP volume 48. Copyright 2016 by the author(s). mation is so appealing: it is simple to evaluate and differ- entiate, and it can be turned into a (concave) log-likelihood function by taking the logarithm of its output. Alternatives proposed in the literature, such as the Bradley-Terry model (Bradley & Terry, 1952; Zadrozny, 2001), the multinomial probit (Albert & Chib, 1993), the spherical softmax (Ol- livier, 2013; de Brebisson & Vincent ́ , 2015), or softmax approximations (Bouchard, 2007), while advantageous in certain scenarios, lack some of these convenient properties. In this paper, we propose the sparsemax transformation. Sparsemax has the distinctive feature that it can return sparse posterior distributions, assigning zero probability to some output variables. This property makes it appealing for filtering large output spaces, predicting multiple labels, or as a component to identify which of a group of variables are relevant for a decision, making the model more inter- pretable. Crucially, this is done while preserving most of the attractive properties of softmax: we show that sparse- max is also simple to evaluate, it is even cheaper to differ- entiate, and that it can be turned into a convex loss function. To sum up, our contributions are as follows: • We formalize the new sparsemax transformation, derive its properties, and show how it can be efficiently com- puted (§2.1–2.3). We show that in the binary case sparse- max reduces to a hard sigmoid (§2.4). • We derive the Jacobian of sparsemax, comparing it to the softmax case, and show that it can lead to faster gradient backpropagation (§2.5). • We propose the sparsemax loss, a new loss function that is the sparsemax analogue of logistic regression (§3). We show that it is convex, everywhere differentiable, and can be regarded as a multi-class generalization of the Hu- ber classification loss (Huber, 1964; Zhang, 2004). • We apply the sparsemax loss to train multi-label linear classifiers (which predict a set of labels instead of a sin- gle label) on benchmark datasets (§4.1–4.2). From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification • Finally, we devise a neural selective attention mecha- nism using the sparsemax transformation, applying to a natural language inference problem (§4.3). 2. The Sparsemax Transformation 2.1. Definition Let ∆K−1 := {p ∈ R K | 1 >p = 1, p ≥ 0} be the (K − 1)-dimensional simplex. We are interested in maps from R K to ∆K−1 . Such maps are useful to convert a vec- tor of real weights (e.g., label scores) to a probability distri- bution (e.g. posterior probabilities of labels). The classical example is the softmax, defined componentwise as: softmaxi(z) = exp(zi) P j exp(zj ) . (1) A limitation of the softmax transformation is that the re- sulting probability distribution always has full support, i.e., softmaxi(z) 6= 0 for every z and i. This is a disadvan- tage in applications where a sparse probability distribution is desired, in which case it is common to define a threshold below which small probability values are truncated to zero. In this paper, we propose as an alternative the following transformation, which we call sparsemax: sparsemax(z) := argmin p∈∆K−1 kp − zk 2 . (2) In words, sparsemax returns the Euclidean projection of the input vector z onto the probability simplex. This projection is likely to hit the boundary of the simplex, in which case sparsemax(z) becomes sparse. We will see that sparsemax retains most of the important properties of softmax, having in addition the ability of producing sparse distributions. 2.2. Closed-Form Solution Many algorithms have been proposed to project onto the simplex (Michelot, 1986; Pardalos & Kovoor, 1990; Duchi et al., 2008). We start by recalling the result that such pro- jections correspond to a soft-thresholding operation. Be- low, we denote [K] := {1, . . . , K} and [t]+ := max{0, t}. Proposition 1 The solution of Eq. 2 is of the form: sparsemaxi (z) = [zi − τ (z)]+, (3) where τ : R K → R is the (unique) function that satis- fies P j [zj − τ (z)]+ = 1 for every z. Furthermore, τ can be expressed as follows. Let z(1) ≥ z(2) ≥ . . . ≥ z(K) be the sorted coordinates of z, and define k(z) := max n k ∈ [K] | 1 + kz(k) > P j≤k z(j) o . Then, τ (z) = P j≤k(z) z(j) − 1 k(z) = P j∈S(z) zj − 1 |S(z)| , (4) Algorithm 1 Sparsemax Evaluation Input: z Sort z as z(1) ≥ . . . ≥ z(K) Find k(z) := max n k ∈ [K] | 1 + kz(k) > P j≤k z(j) o Define τ (z) = ( P j≤k(z) z(j))−1 k(z) Output: p s.t. pi = [zi − τ (z)]+. where S(z) := {j ∈ [K] | sparsemaxj (z) > 0} is the support of sparsemax(z). Proof: See App. A.1 in the supplemental material. In essence, Prop. 1 states that all we need for evaluating the sparsemax is to compute the threshold τ (z); all coordi- nates above this threshold (the ones in the set S(z)) will be shifted by this amount, and the others will be truncated to zero. We call τ in Eq. 4 the threshold function: this piece- wise linear function will play an important role in the se- quel. Alg. 1 illustrates a na ̈ıve O(K log K) algorithm that uses Prop. 1 for evaluating the sparsemax. More elaborate O(K) algorithms exist based on partitioning and median- finding (Blum et al., 1973; Pardalos & Kovoor, 1990).1 2.3. Basic Properties We now highlight some properties that are common to soft- max and sparsemax. Let z(1) := maxk zk, and denote by A(z) := {k ∈ [K] | zk = z(1)} the set of maximal compo- nents of z. We define the indicator vector 1A(z) , whose kth component is 1 if k ∈ A(z), and 0 otherwise. We further denote by γ(z) := z(1) − maxk /∈A(z) zk the gap between the maximal components of z and the second largest. We let 0 and 1 be vectors of zeros and ones, respectively. Proposition 2 The following properties hold for ρ ∈ {softmax,sparsemax}. 1. ρ(0) = 1/K and lim→0+ ρ( −1z) = 1A(z)/|A(z)| (uniform distribution, and distribution peaked on the maximal components of z, respectively). For sparsemax, the last equality holds for any ≤ γ(z) · |A(z)|. 2. ρ(z) = ρ(z + c1), for any c ∈ R (i.e., ρ is invariant to adding the same constant to each coordinate). 3. ρ(Pz) = Pρ(z) for any permutation matrix P (i.e., ρ commutes with permutations). 4. If zi ≤ zj , then 0 ≤ ρj (z) − ρi(z) ≤ η(zj − zi), where η = 1 2 for softmax, and η = 1 for sparsemax. Proof: See App. A.2 in the supplemental material. 1 In practice, there are observed linear time algorithms which are often a better choice. See Condat (2014, Table 1), who provide an empirical comparison among several of these algorithms. From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification − 3 − 2 − 1 0 1 2 3 t 0.0 0.2 0.4 0.6 0.8 1.0 softmax1 ([t,0]) sparsemax1 ([t,0]) Figure 1. Comparison of softmax and sparsemax in 2D (left) and 3D (two righmost plots). Interpreting as a “temperature parameter,” the first clause of Prop. 2 shows that the sparsemax has the same “zero- temperature limit” behaviour as the softmax, but without the need of making the temperature arbitrarily small. We will use this fact in the experiments in §4.2 to control the degree of sparsity achieved with the sparsemax activation. Prop. 2 is reassuring, since it shows that the sparsemax transformation, despite being defined very differently from the softmax, has a similar behaviour and preserves the same invariances. Note that some of these properties are not sat- isfied by other proposed replacements of the softmax: for example, the spherical softmax (Ollivier, 2013), defined as ρi(z) := z 2 i / P j z 2 j , does not satisfy properties 2 and 4. 2.4. Two and Three-Dimensional Cases For the two-class case, it is well known that the softmax activation becomes the logistic (sigmoid) function. More precisely, if z = (t, 0), then softmax1(z) = σ(t) := (1 + exp(−t))−1 . We next show that the analogous in sparsemax is the “hard” version of the sigmoid. In fact, using Prop. 1, Eq. 4, we have that, for z = (t, 0), τ (z) =    t − 1, if t > 1 (t − 1)/2, if −1 ≤ t ≤ 1 −1, if t < −1, (5) and therefore sparsemax1 (z) =    1, if t > 1 (t + 1)/2, if −1 ≤ t ≤ 1 0, if t < −1. (6) Fig. 1 provides an illustration for the two and three- dimensional cases. For the latter, we parameterize z = (t1, t2, 0) and plot softmax1(z) and sparsemax1 (z) as a function of t1 and t2. We can see that sparsemax is piece- wise linear, but asymptotically similar to the softmax. 2.5. Jacobian of Sparsemax The Jacobian matrix of a transformation ρ, Jρ(z) := [∂ρi(z)/∂zj ]i,j , is of key importance to train models with gradient-based optimization. We next derive the Jacobian of the sparsemax activation, but before doing so, let us re- call how the Jacobian of the softmax looks like. We have ∂softmaxi(z) ∂zj = (δij e zi P k e zk − e zi e zj )/( P k e zk ) 2 = softmaxi(z)(δij − softmaxj (z)), (7) where δij is the Kronecker delta, which evaluates to 1 if i = j and 0 otherwise. Letting p = softmax(z), the full Jacobian can be written in matrix notation as Jsoftmax(z) = Diag(p) − pp>, (8) where Diag(p) is a matrix with p in the main diagonal. Let us now turn to the sparsemax case. The sparsemax is differentiable everywhere except at splitting points z where the support set S(z) changes, i.e., where S(z) 6= S(z+d) for some d and infinitesimal . 2 From Eq. 3, we have that: ∂sparsemaxi (z) ∂zj = ( δij − ∂τ(z) ∂zj , if zi > τ (z), 0, if zi ≤ τ (z). (9) From Eq. 4, the gradient of the threshold function τ is: ∂τ (z) ∂zj = 1 |S(z)| if j ∈ S(z), 0, if j /∈ S(z). (10) Note that j ∈ S(z) ⇔ zj > τ (z). Therefore we obtain: ∂sparsemaxi (z) ∂zj = δij − 1 |S(z)| , if i, j ∈ S(z), 0, otherwise. (11) Let s be an indicator vector whose ith entry is 1 if i ∈ S(z), and 0 otherwise. We can write the Jacobian matrix as Jsparsemax(z) = Diag(s) − ss>/|S(z)|. (12) It is instructive to compare Eqs. 8 and 12. We may re- gard the Jacobian of sparsemax as the Laplacian of a graph whose elements of S(z) are fully connected. To compute 2 For those points, we can take an arbitrary matrix in the set of generalized Clarke’s Jacobians (Clarke, 1983), the convex hull of all points of the form limt→∞ Jsparsemax(zt), where zt → z. From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification it, we only need S(z), which can be obtained in O(K) time with the same algorithm that evaluates the sparsemax. Often, e.g., in the gradient backpropagation algorithm, it is not necessary to compute the full Jacobian matrix, but only the product between the Jacobian and a given vector v. In the softmax case, from Eq. 8, we have: Jsoftmax(z)·v = p (v−v ̄1), with v ̄ := P j pjvj , (13) where denotes the Hadamard product; this requires a linear-time computation. For the sparsemax case, we have: Jsparsemax(z)· v = s (v − vˆ1), with vˆ := P j∈S(z) vj |S(z)| . (14) Interestingly, if sparsemax(z) has already been evaluated (i.e., in the forward step), then so has S(z), hence the nonzeros of Jsparsemax(z) · v can be computed in only O(|S(z)|) time, which can be sublinear. This can be an im- portant advantage of sparsemax over softmax if K is large. Computational efficiency. In sum, the computational needs of softmax and sparsemax are compared as follows: • At training time, sparsemax can backpropagate gradients faster due to the sparsity (as stated above). • At inference time, the softmax forward pass is faster, but asymptotically both are linear time. In our experiments (§4), even with the O(K log K) Algorithm 1, similar runtimes were achieved with softmax and sparsemax. 3. A Loss Function for Sparsemax Now that we have defined and analyzed the sparsemax transformation, we will use it to design a new loss function that resembles the logistic loss, but can yield sparse poste- rior distributions. Later (in §4.1–4.2), we apply this loss to label proportion estimation and multi-label classification. 3.1. Logistic Loss Let D := {(xi , yi)} N i=1 be a dataset, where each xi ∈ R D is an input vector and yi ∈ {1, . . . , K} is a target label. We consider empirical risk minimization problems of the form minimize λ 2 kWk 2 F + 1 N X N i=1 L(Wxi + b; yi), w.r.t. W ∈ R K×D, b ∈ R K, (15) where L is a loss function, W is a matrix of weights, and b is a bias vector. The loss function associated with the softmax is the logistic loss (or negative log-likelihood): Lsoftmax(z; k) = − log softmaxk(z) = −zk + logX j exp(zj ), (16) where z = Wxi + b, and k = yi is the “gold” label. The gradient of this loss is, invoking Eq. 7, ∇zLsoftmax(z; k) = −δk + softmax(z), (17) where δk denotes the delta distribution on k, [δk]j = 1 if j = k, and 0 otherwise. This is a well-known result; when plugged into a gradient-based optimizer, it leads to updates that move probability mass from the distribution predicted by the current model (i.e., softmaxk(z)) to the gold label (via δk). Can we have something similar for sparsemax? 3.2. Sparsemax Loss A nice aspect of the log-likelihood (Eq. 16) is that adding up loss terms for several examples, assumed i.i.d, we obtain the log-probability of the full training data. Unfortunately, this idea cannot be carried out to sparsemax: now, some labels may have exactly probability zero, so any model that assigns zero probability to a gold label would zero out the probability of the entire training sample. This is of course highly undesirable. One possible workaround is to define L sparsemax(z; k) = − log + sparsemaxk (z) 1 + K , (18) where is a small constant, and +sparsemaxk(z) 1+K is a “per- turbed” sparsemax. However, this loss is non-convex, un- like the one in Eq. 16. Another possibility, which we explore here, is to construct an alternative loss function whose gradient resembles the one in Eq. 17. Note that the gradient is particularly im- portant, since it is directly involved in the model updates for typical optimization algorithms. Formally, we want Lsparsemax to be a differentiable function such that ∇zLsparsemax(z; k) = −δk + sparsemax(z). (19) We show below that this property is fulfilled by the follow- ing function, henceforth called the sparsemax loss: Lsparsemax(z; k) = −zk+ 1 2 X j∈S(z) (z 2 j −τ 2 (z))+1 2 , (20) where τ 2 is the square of the threshold function in Eq. 4. This loss, which has never been considered in the literature to the best of our knowledge, has a number of interesting properties, stated in the next proposition. Proposition 3 The following holds: 1. Lsparsemax is differentiable everywhere, and its gradient is given by the expression in Eq. 19. 2. Lsparsemax is convex. 3. Lsparsemax(z + c1; k) = Lsparsemax(z; k), ∀c ∈ R. The idea is to set the probabilities of the smallest values of z to zero and keep only probabilities of the highest values of z, but still keep the function differentiable to ensure successful application of backpropagation algorithm. This function is defined as: Here τ(z) is called threshold function and it defines the support function S(z) that contains all non-zero indices of p. A python implementation of sparsemax function is below: Running it and softmax on the same values we can indeed see that it does set some of the probabilities to zero, where softmax keeps them non-zero: np.around(sparsemax([0.1, 1.1, 0.2, 0.3]), decimals=3)array([0. , 0.9, 0. , 0.1])np.around(softmax([0.1, 1.1, 0.2, 0.3]), decimals=3)array([0.165, 0.45 , 0.183, 0.202]) It is also interesting to see how the two functions are different in the two-dimensional case. In this case softmax becomes a sigmoid function, and sparsemax can be represented in this form: The picture below illustrates how they are different: Note, that the sparsemax function is not differentiable everywhere (but neither is relu), but where it is is an easy computation: Here |S(z)| is the number of elements in the support S(z). The obvious problem with sparsemax is vanishing gradient. You can see that the derivative turns to zero once z becomes large. The authors acknowledged the problem and even proposed a new loss function in place of cross-entropy loss. However I believe the main advantage of sparsemax is not in the output layer, but in the middle of the neural network, for example, in the attention mechanism. You can find the code for this article in my github repository.
[ { "code": null, "e": 379, "s": 172, "text": "In machine learning, there are several very useful functions, for example, sigmoid, relu, softmax. The latter is widely used in multi-class classification problems as an output layer of the Neural networks:" }, { "code": null, "e": 922, "s": 379, "text": "This function has a useful property: the sum of its elements is one, which makes it very useful to model probabilities. It is also differentiable everywhere and the derivative is never zero, which make it useful in the backpropagation algorithms. in contrast, the derivative of the argmax function, that softmax is called to replace, is always zero. Another useful property is that this function preserves the support of the posterior probability distribution because the output probabilities are never zero, however small values they may be." }, { "code": null, "e": 1235, "s": 922, "text": "But sometimes you want to have a sparse output, only preserving several values with non-zero probability. For this scenario, André F. T. Martins and Ramón F. Astudillo proposed a new function called sparsemax in their paper From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification." }, { "code": null, "e": 1263, "s": 1235, "text": "From Softmax to Sparsemax:\n" }, { "code": null, "e": 1323, "s": 1263, "text": "A Sparse Model of Attention and Multi-Label Classification\n" }, { "code": null, "e": 1347, "s": 1323, "text": "Andre F. T. Martins ́\n" }, { "code": null, "e": 1377, "s": 1347, "text": "†] ANDRE.MARTINS@UNBABEL.COM\n" }, { "code": null, "e": 1400, "s": 1377, "text": "Ramon F. Astudillo ́\n" }, { "code": null, "e": 1421, "s": 1400, "text": "† RAMON@UNBABEL.COM\n" }, { "code": null, "e": 1497, "s": 1421, "text": "†Unbabel Lda, Rua Visconde de Santarem, 67-B, 1000-286 Lisboa, Portugal ́\n" }, { "code": null, "e": 1500, "s": 1497, "text": "]\n" }, { "code": null, "e": 1621, "s": 1500, "text": "Instituto de Telecomunicac ̧oes (IT), Instituto Superior T ̃ ecnico, Av. Rovisco Pais, 1, 1049-001 Lisboa, Portugal ́\n" }, { "code": null, "e": 1733, "s": 1623, "text": "Instituto de Engenharia de Sistemas e Computadores (INESC-ID), Rua Alves Redol, 9, 1000-029 Lisboa, Portugal\n" }, { "code": null, "e": 1743, "s": 1733, "text": "Abstract\n" }, { "code": null, "e": 1839, "s": 1743, "text": "We propose sparsemax, a new activation func-\ntion similar to the traditional softmax, but able\n" }, { "code": null, "e": 1887, "s": 1839, "text": "to output sparse probabilities. After deriving\n" }, { "code": null, "e": 1936, "s": 1887, "text": "its properties, we show how its Jacobian can be\n" }, { "code": null, "e": 2030, "s": 1936, "text": "efficiently computed, enabling its use in a net-\nwork trained with backpropagation. Then, we\n" }, { "code": null, "e": 2077, "s": 2030, "text": "propose a new smooth and convex loss function\n" }, { "code": null, "e": 2169, "s": 2077, "text": "which is the sparsemax analogue of the logis-\ntic loss. We reveal an unexpected connection\n" }, { "code": null, "e": 2315, "s": 2169, "text": "between this new loss and the Huber classifi-\ncation loss. We obtain promising empirical re-\nsults in multi-label classification problems and in\n" }, { "code": null, "e": 2465, "s": 2315, "text": "attention-based neural networks for natural lan-\nguage inference. For the latter, we achieve a sim-\nilar performance as the traditional softmax, but\n" }, { "code": null, "e": 2515, "s": 2465, "text": "with a selective, more compact, attention focus.\n" }, { "code": null, "e": 2532, "s": 2515, "text": "1. Introduction\n" }, { "code": null, "e": 2590, "s": 2532, "text": "The softmax transformation is a key component of several\n" }, { "code": null, "e": 2764, "s": 2590, "text": "statistical learning models, encompassing multinomial lo-\ngistic regression (McCullagh & Nelder, 1989), action se-\nlection in reinforcement learning (Sutton & Barto, 1998),\n" }, { "code": null, "e": 2825, "s": 2764, "text": "and neural networks for multi-class classification (Bridle,\n" }, { "code": null, "e": 2885, "s": 2825, "text": "1990; Goodfellow et al., 2016). Recently, it has also been\n" }, { "code": null, "e": 2942, "s": 2885, "text": "used to design attention mechanisms in neural networks,\n" }, { "code": null, "e": 3058, "s": 2942, "text": "with important achievements in machine translation (Bah-\ndanau et al., 2015), image caption generation (Xu et al.,\n" }, { "code": null, "e": 3119, "s": 3058, "text": "2015), speech recognition (Chorowski et al., 2015), natural\n" }, { "code": null, "e": 3177, "s": 3119, "text": "language understanding (Hermann et al., 2015; Sukhbaatar\n" }, { "code": null, "e": 3239, "s": 3177, "text": "et al., 2015; Rocktaschel et al. ̈ , 2015), and computation\n" }, { "code": null, "e": 3299, "s": 3239, "text": "learning (Graves et al., 2014; Grefenstette et al., 2015).\n" }, { "code": null, "e": 3417, "s": 3299, "text": "There are a number of reasons why the softmax transfor-\nProceedings of the 33 rd International Conference on Machine\n" }, { "code": null, "e": 3471, "s": 3417, "text": "Learning, New York, NY, USA, 2016. JMLR: W&CP volume\n" }, { "code": null, "e": 3509, "s": 3471, "text": "48. Copyright 2016 by the author(s).\n" }, { "code": null, "e": 3633, "s": 3509, "text": "mation is so appealing: it is simple to evaluate and differ-\nentiate, and it can be turned into a (concave) log-likelihood\n" }, { "code": null, "e": 3695, "s": 3633, "text": "function by taking the logarithm of its output. Alternatives\n" }, { "code": null, "e": 3756, "s": 3695, "text": "proposed in the literature, such as the Bradley-Terry model\n" }, { "code": null, "e": 3814, "s": 3756, "text": "(Bradley & Terry, 1952; Zadrozny, 2001), the multinomial\n" }, { "code": null, "e": 3932, "s": 3814, "text": "probit (Albert & Chib, 1993), the spherical softmax (Ol-\nlivier, 2013; de Brebisson & Vincent ́ , 2015), or softmax\n" }, { "code": null, "e": 3988, "s": 3932, "text": "approximations (Bouchard, 2007), while advantageous in\n" }, { "code": null, "e": 4050, "s": 3988, "text": "certain scenarios, lack some of these convenient properties.\n" }, { "code": null, "e": 4107, "s": 4050, "text": "In this paper, we propose the sparsemax transformation.\n" }, { "code": null, "e": 4165, "s": 4107, "text": "Sparsemax has the distinctive feature that it can return\n" }, { "code": null, "e": 4228, "s": 4165, "text": "sparse posterior distributions, assigning zero probability to\n" }, { "code": null, "e": 4285, "s": 4228, "text": "some output variables. This property makes it appealing\n" }, { "code": null, "e": 4349, "s": 4285, "text": "for filtering large output spaces, predicting multiple labels,\n" }, { "code": null, "e": 4410, "s": 4349, "text": "or as a component to identify which of a group of variables\n" }, { "code": null, "e": 4528, "s": 4410, "text": "are relevant for a decision, making the model more inter-\npretable. Crucially, this is done while preserving most of\n" }, { "code": null, "e": 4714, "s": 4528, "text": "the attractive properties of softmax: we show that sparse-\nmax is also simple to evaluate, it is even cheaper to differ-\nentiate, and that it can be turned into a convex loss function.\n" }, { "code": null, "e": 4760, "s": 4714, "text": "To sum up, our contributions are as follows:\n" }, { "code": null, "e": 4817, "s": 4760, "text": "• We formalize the new sparsemax transformation, derive\n" }, { "code": null, "e": 4970, "s": 4817, "text": "its properties, and show how it can be efficiently com-\nputed (§2.1–2.3). We show that in the binary case sparse-\nmax reduces to a hard sigmoid (§2.4).\n" }, { "code": null, "e": 5030, "s": 4970, "text": "• We derive the Jacobian of sparsemax, comparing it to the\n" }, { "code": null, "e": 5090, "s": 5030, "text": "softmax case, and show that it can lead to faster gradient\n" }, { "code": null, "e": 5115, "s": 5090, "text": "backpropagation (§2.5).\n" }, { "code": null, "e": 5174, "s": 5115, "text": "• We propose the sparsemax loss, a new loss function that\n" }, { "code": null, "e": 5233, "s": 5174, "text": "is the sparsemax analogue of logistic regression (§3). We\n" }, { "code": null, "e": 5289, "s": 5233, "text": "show that it is convex, everywhere differentiable, and\n" }, { "code": null, "e": 5401, "s": 5289, "text": "can be regarded as a multi-class generalization of the Hu-\nber classification loss (Huber, 1964; Zhang, 2004).\n" }, { "code": null, "e": 5460, "s": 5401, "text": "• We apply the sparsemax loss to train multi-label linear\n" }, { "code": null, "e": 5567, "s": 5460, "text": "classifiers (which predict a set of labels instead of a sin-\ngle label) on benchmark datasets (§4.1–4.2).\n" }, { "code": null, "e": 5654, "s": 5567, "text": "From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification\n" }, { "code": null, "e": 5767, "s": 5654, "text": "• Finally, we devise a neural selective attention mecha-\nnism using the sparsemax transformation, applying to a\n" }, { "code": null, "e": 5811, "s": 5767, "text": "natural language inference problem (§4.3).\n" }, { "code": null, "e": 5844, "s": 5811, "text": "2. The Sparsemax Transformation\n" }, { "code": null, "e": 5861, "s": 5844, "text": "2.1. Definition\n" }, { "code": null, "e": 5871, "s": 5861, "text": "Let ∆K−1\n" }, { "code": null, "e": 5882, "s": 5871, "text": ":= {p ∈ R\n" }, { "code": null, "e": 5889, "s": 5882, "text": "K | 1\n" }, { "code": null, "e": 5912, "s": 5889, "text": ">p = 1, p ≥ 0} be the\n" }, { "code": null, "e": 5968, "s": 5912, "text": "(K − 1)-dimensional simplex. We are interested in maps\n" }, { "code": null, "e": 5976, "s": 5968, "text": "from R\n" }, { "code": null, "e": 5987, "s": 5976, "text": "K to ∆K−1\n" }, { "code": null, "e": 6158, "s": 5987, "text": ". Such maps are useful to convert a vec-\ntor of real weights (e.g., label scores) to a probability distri-\nbution (e.g. posterior probabilities of labels). The classical\n" }, { "code": null, "e": 6209, "s": 6158, "text": "example is the softmax, defined componentwise as:\n" }, { "code": null, "e": 6232, "s": 6209, "text": "softmaxi(z) = exp(zi)\n" }, { "code": null, "e": 6235, "s": 6232, "text": "P\n" }, { "code": null, "e": 6238, "s": 6235, "text": "j\n" }, { "code": null, "e": 6248, "s": 6238, "text": "exp(zj )\n" }, { "code": null, "e": 6255, "s": 6248, "text": ". (1)\n" }, { "code": null, "e": 6379, "s": 6255, "text": "A limitation of the softmax transformation is that the re-\nsulting probability distribution always has full support, i.e.,\n" }, { "code": null, "e": 6497, "s": 6379, "text": "softmaxi(z) 6= 0 for every z and i. This is a disadvan-\ntage in applications where a sparse probability distribution\n" }, { "code": null, "e": 6559, "s": 6497, "text": "is desired, in which case it is common to define a threshold\n" }, { "code": null, "e": 6620, "s": 6559, "text": "below which small probability values are truncated to zero.\n" }, { "code": null, "e": 6679, "s": 6620, "text": "In this paper, we propose as an alternative the following\n" }, { "code": null, "e": 6721, "s": 6679, "text": "transformation, which we call sparsemax:\n" }, { "code": null, "e": 6745, "s": 6721, "text": "sparsemax(z) := argmin\n" }, { "code": null, "e": 6753, "s": 6745, "text": "p∈∆K−1\n" }, { "code": null, "e": 6762, "s": 6753, "text": "kp − zk\n" }, { "code": null, "e": 6765, "s": 6762, "text": "2\n" }, { "code": null, "e": 6772, "s": 6765, "text": ". (2)\n" }, { "code": null, "e": 6833, "s": 6772, "text": "In words, sparsemax returns the Euclidean projection of the\n" }, { "code": null, "e": 6895, "s": 6833, "text": "input vector z onto the probability simplex. This projection\n" }, { "code": null, "e": 6956, "s": 6895, "text": "is likely to hit the boundary of the simplex, in which case\n" }, { "code": null, "e": 7013, "s": 6956, "text": "sparsemax(z) becomes sparse. We will see that sparsemax\n" }, { "code": null, "e": 7074, "s": 7013, "text": "retains most of the important properties of softmax, having\n" }, { "code": null, "e": 7134, "s": 7074, "text": "in addition the ability of producing sparse distributions.\n" }, { "code": null, "e": 7161, "s": 7134, "text": "2.2. Closed-Form Solution\n" }, { "code": null, "e": 7217, "s": 7161, "text": "Many algorithms have been proposed to project onto the\n" }, { "code": null, "e": 7274, "s": 7217, "text": "simplex (Michelot, 1986; Pardalos & Kovoor, 1990; Duchi\n" }, { "code": null, "e": 7456, "s": 7274, "text": "et al., 2008). We start by recalling the result that such pro-\njections correspond to a soft-thresholding operation. Be-\nlow, we denote [K] := {1, . . . , K} and [t]+ := max{0, t}.\n" }, { "code": null, "e": 7509, "s": 7456, "text": "Proposition 1 The solution of Eq. 2 is of the form:\n" }, { "code": null, "e": 7521, "s": 7509, "text": "sparsemaxi\n" }, { "code": null, "e": 7547, "s": 7521, "text": "(z) = [zi − τ (z)]+, (3)\n" }, { "code": null, "e": 7560, "s": 7547, "text": "where τ : R\n" }, { "code": null, "e": 7611, "s": 7560, "text": "K → R is the (unique) function that satis-\nfies P\n" }, { "code": null, "e": 7614, "s": 7611, "text": "j\n" }, { "code": null, "e": 7661, "s": 7614, "text": "[zj − τ (z)]+ = 1 for every z. Furthermore, τ\n" }, { "code": null, "e": 7717, "s": 7661, "text": "can be expressed as follows. Let z(1) ≥ z(2) ≥ . . . ≥\n" }, { "code": null, "e": 7774, "s": 7717, "text": "z(K) be the sorted coordinates of z, and define k(z) :=\n" }, { "code": null, "e": 7781, "s": 7774, "text": "max n\n" }, { "code": null, "e": 7804, "s": 7781, "text": "k ∈ [K] | 1 + kz(k) >\n" }, { "code": null, "e": 7807, "s": 7804, "text": "P\n" }, { "code": null, "e": 7812, "s": 7807, "text": "j≤k\n" }, { "code": null, "e": 7818, "s": 7812, "text": "z(j)\n" }, { "code": null, "e": 7821, "s": 7818, "text": "o\n" }, { "code": null, "e": 7830, "s": 7821, "text": ". Then,\n" }, { "code": null, "e": 7839, "s": 7830, "text": "τ (z) =\n" }, { "code": null, "e": 7842, "s": 7839, "text": "P\n" }, { "code": null, "e": 7850, "s": 7842, "text": "j≤k(z)\n" }, { "code": null, "e": 7856, "s": 7850, "text": "z(j)\n" }, { "code": null, "e": 7863, "s": 7858, "text": "− 1\n" }, { "code": null, "e": 7869, "s": 7863, "text": "k(z)\n" }, { "code": null, "e": 7872, "s": 7869, "text": "=\n" }, { "code": null, "e": 7875, "s": 7872, "text": "P\n" }, { "code": null, "e": 7883, "s": 7875, "text": "j∈S(z)\n" }, { "code": null, "e": 7887, "s": 7883, "text": "zj\n" }, { "code": null, "e": 7894, "s": 7889, "text": "− 1\n" }, { "code": null, "e": 7902, "s": 7894, "text": "|S(z)|\n" }, { "code": null, "e": 7909, "s": 7902, "text": ", (4)\n" }, { "code": null, "e": 7943, "s": 7909, "text": "Algorithm 1 Sparsemax Evaluation\n" }, { "code": null, "e": 7953, "s": 7943, "text": "Input: z\n" }, { "code": null, "e": 7984, "s": 7953, "text": "Sort z as z(1) ≥ . . . ≥ z(K)\n" }, { "code": null, "e": 8004, "s": 7984, "text": "Find k(z) := max n\n" }, { "code": null, "e": 8027, "s": 8004, "text": "k ∈ [K] | 1 + kz(k) >\n" }, { "code": null, "e": 8030, "s": 8027, "text": "P\n" }, { "code": null, "e": 8035, "s": 8030, "text": "j≤k\n" }, { "code": null, "e": 8041, "s": 8035, "text": "z(j)\n" }, { "code": null, "e": 8044, "s": 8041, "text": "o\n" }, { "code": null, "e": 8062, "s": 8044, "text": "Define τ (z) = (\n" }, { "code": null, "e": 8065, "s": 8062, "text": "P\n" }, { "code": null, "e": 8073, "s": 8065, "text": "j≤k(z)\n" }, { "code": null, "e": 8082, "s": 8073, "text": "z(j))−1\n" }, { "code": null, "e": 8088, "s": 8082, "text": "k(z)\n" }, { "code": null, "e": 8124, "s": 8088, "text": "Output: p s.t. pi = [zi − τ (z)]+.\n" }, { "code": null, "e": 8161, "s": 8124, "text": "where S(z) := {j ∈ [K] | sparsemaxj\n" }, { "code": null, "e": 8178, "s": 8161, "text": "(z) > 0} is the\n" }, { "code": null, "e": 8204, "s": 8178, "text": "support of sparsemax(z).\n" }, { "code": null, "e": 8255, "s": 8204, "text": "Proof: See App. A.1 in the supplemental material.\n" }, { "code": null, "e": 8315, "s": 8255, "text": "In essence, Prop. 1 states that all we need for evaluating\n" }, { "code": null, "e": 8439, "s": 8315, "text": "the sparsemax is to compute the threshold τ (z); all coordi-\nnates above this threshold (the ones in the set S(z)) will be\n" }, { "code": null, "e": 8500, "s": 8439, "text": "shifted by this amount, and the others will be truncated to\n" }, { "code": null, "e": 8683, "s": 8500, "text": "zero. We call τ in Eq. 4 the threshold function: this piece-\nwise linear function will play an important role in the se-\nquel. Alg. 1 illustrates a na ̈ıve O(K log K) algorithm that\n" }, { "code": null, "e": 8742, "s": 8683, "text": "uses Prop. 1 for evaluating the sparsemax. More elaborate\n" }, { "code": null, "e": 8854, "s": 8742, "text": "O(K) algorithms exist based on partitioning and median-\nfinding (Blum et al., 1973; Pardalos & Kovoor, 1990).1\n" }, { "code": null, "e": 8877, "s": 8854, "text": "2.3. Basic Properties\n" }, { "code": null, "e": 8990, "s": 8877, "text": "We now highlight some properties that are common to soft-\nmax and sparsemax. Let z(1) := maxk zk, and denote by\n" }, { "code": null, "e": 9096, "s": 8990, "text": "A(z) := {k ∈ [K] | zk = z(1)} the set of maximal compo-\nnents of z. We define the indicator vector 1A(z)\n" }, { "code": null, "e": 9109, "s": 9096, "text": ", whose kth\n" }, { "code": null, "e": 9166, "s": 9109, "text": "component is 1 if k ∈ A(z), and 0 otherwise. We further\n" }, { "code": null, "e": 9223, "s": 9166, "text": "denote by γ(z) := z(1) − maxk /∈A(z) zk the gap between\n" }, { "code": null, "e": 9279, "s": 9223, "text": "the maximal components of z and the second largest. We\n" }, { "code": null, "e": 9336, "s": 9279, "text": "let 0 and 1 be vectors of zeros and ones, respectively.\n" }, { "code": null, "e": 9389, "s": 9336, "text": "Proposition 2 The following properties hold for ρ ∈\n" }, { "code": null, "e": 9411, "s": 9389, "text": "{softmax,sparsemax}.\n" }, { "code": null, "e": 9440, "s": 9411, "text": "1. ρ(0) = 1/K and lim→0+ ρ(\n" }, { "code": null, "e": 9461, "s": 9440, "text": "−1z) = 1A(z)/|A(z)|\n" }, { "code": null, "e": 9516, "s": 9461, "text": "(uniform distribution, and distribution peaked on the\n" }, { "code": null, "e": 9572, "s": 9516, "text": "maximal components of z, respectively). For sparsemax,\n" }, { "code": null, "e": 9623, "s": 9572, "text": "the last equality holds for any ≤ γ(z) · |A(z)|.\n" }, { "code": null, "e": 9684, "s": 9623, "text": "2. ρ(z) = ρ(z + c1), for any c ∈ R (i.e., ρ is invariant to\n" }, { "code": null, "e": 9731, "s": 9684, "text": "adding the same constant to each coordinate).\n" }, { "code": null, "e": 9787, "s": 9731, "text": "3. ρ(Pz) = Pρ(z) for any permutation matrix P (i.e., ρ\n" }, { "code": null, "e": 9817, "s": 9787, "text": "commutes with permutations).\n" }, { "code": null, "e": 9878, "s": 9817, "text": "4. If zi ≤ zj , then 0 ≤ ρj (z) − ρi(z) ≤ η(zj − zi), where\n" }, { "code": null, "e": 9883, "s": 9878, "text": "η =\n" }, { "code": null, "e": 9886, "s": 9883, "text": "1\n" }, { "code": null, "e": 9889, "s": 9886, "text": "2\n" }, { "code": null, "e": 9928, "s": 9889, "text": "for softmax, and η = 1 for sparsemax.\n" }, { "code": null, "e": 9979, "s": 9928, "text": "Proof: See App. A.2 in the supplemental material.\n" }, { "code": null, "e": 9982, "s": 9979, "text": "1\n" }, { "code": null, "e": 10044, "s": 9982, "text": "In practice, there are observed linear time algorithms which\n" }, { "code": null, "e": 10112, "s": 10044, "text": "are often a better choice. See Condat (2014, Table 1), who provide\n" }, { "code": null, "e": 10172, "s": 10112, "text": "an empirical comparison among several of these algorithms.\n" }, { "code": null, "e": 10259, "s": 10172, "text": "From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification\n" }, { "code": null, "e": 10280, "s": 10259, "text": "− 3 − 2 − 1 0 1 2 3\n" }, { "code": null, "e": 10283, "s": 10280, "text": "t\n" }, { "code": null, "e": 10288, "s": 10283, "text": "0.0\n" }, { "code": null, "e": 10293, "s": 10288, "text": "0.2\n" }, { "code": null, "e": 10298, "s": 10293, "text": "0.4\n" }, { "code": null, "e": 10303, "s": 10298, "text": "0.6\n" }, { "code": null, "e": 10308, "s": 10303, "text": "0.8\n" }, { "code": null, "e": 10330, "s": 10308, "text": "1.0 softmax1 ([t,0])\n" }, { "code": null, "e": 10350, "s": 10330, "text": "sparsemax1 ([t,0])\n" }, { "code": null, "e": 10439, "s": 10350, "text": "Figure 1. Comparison of softmax and sparsemax in 2D (left) and 3D (two righmost plots).\n" }, { "code": null, "e": 10501, "s": 10439, "text": "Interpreting as a “temperature parameter,” the first clause\n" }, { "code": null, "e": 10615, "s": 10501, "text": "of Prop. 2 shows that the sparsemax has the same “zero-\ntemperature limit” behaviour as the softmax, but without\n" }, { "code": null, "e": 10673, "s": 10615, "text": "the need of making the temperature arbitrarily small. We\n" }, { "code": null, "e": 10735, "s": 10673, "text": "will use this fact in the experiments in §4.2 to control the\n" }, { "code": null, "e": 10795, "s": 10735, "text": "degree of sparsity achieved with the sparsemax activation.\n" }, { "code": null, "e": 10853, "s": 10795, "text": "Prop. 2 is reassuring, since it shows that the sparsemax\n" }, { "code": null, "e": 10914, "s": 10853, "text": "transformation, despite being defined very differently from\n" }, { "code": null, "e": 10975, "s": 10914, "text": "the softmax, has a similar behaviour and preserves the same\n" }, { "code": null, "e": 11095, "s": 10975, "text": "invariances. Note that some of these properties are not sat-\nisfied by other proposed replacements of the softmax: for\n" }, { "code": null, "e": 11156, "s": 11095, "text": "example, the spherical softmax (Ollivier, 2013), defined as\n" }, { "code": null, "e": 11168, "s": 11156, "text": "ρi(z) := z\n" }, { "code": null, "e": 11171, "s": 11168, "text": "2\n" }, { "code": null, "e": 11174, "s": 11171, "text": "i\n" }, { "code": null, "e": 11177, "s": 11174, "text": "/\n" }, { "code": null, "e": 11180, "s": 11177, "text": "P\n" }, { "code": null, "e": 11183, "s": 11180, "text": "j\n" }, { "code": null, "e": 11186, "s": 11183, "text": "z\n" }, { "code": null, "e": 11189, "s": 11186, "text": "2\n" }, { "code": null, "e": 11192, "s": 11189, "text": "j\n" }, { "code": null, "e": 11232, "s": 11192, "text": ", does not satisfy properties 2 and 4.\n" }, { "code": null, "e": 11270, "s": 11232, "text": "2.4. Two and Three-Dimensional Cases\n" }, { "code": null, "e": 11329, "s": 11270, "text": "For the two-class case, it is well known that the softmax\n" }, { "code": null, "e": 11387, "s": 11329, "text": "activation becomes the logistic (sigmoid) function. More\n" }, { "code": null, "e": 11441, "s": 11387, "text": "precisely, if z = (t, 0), then softmax1(z) = σ(t) :=\n" }, { "code": null, "e": 11458, "s": 11441, "text": "(1 + exp(−t))−1\n" }, { "code": null, "e": 11496, "s": 11458, "text": ". We next show that the analogous in\n" }, { "code": null, "e": 11554, "s": 11496, "text": "sparsemax is the “hard” version of the sigmoid. In fact,\n" }, { "code": null, "e": 11607, "s": 11554, "text": "using Prop. 1, Eq. 4, we have that, for z = (t, 0),\n" }, { "code": null, "e": 11616, "s": 11607, "text": "τ (z) =\n" }, { "code": null, "e": 11619, "s": 11616, "text": "\n" }, { "code": null, "e": 11622, "s": 11619, "text": "\n" }, { "code": null, "e": 11625, "s": 11622, "text": "\n" }, { "code": null, "e": 11642, "s": 11625, "text": "t − 1, if t > 1\n" }, { "code": null, "e": 11668, "s": 11642, "text": "(t − 1)/2, if −1 ≤ t ≤ 1\n" }, { "code": null, "e": 11684, "s": 11668, "text": "−1, if t < −1,\n" }, { "code": null, "e": 11689, "s": 11684, "text": "(5)\n" }, { "code": null, "e": 11704, "s": 11689, "text": "and therefore\n" }, { "code": null, "e": 11716, "s": 11704, "text": "sparsemax1\n" }, { "code": null, "e": 11723, "s": 11716, "text": "(z) =\n" }, { "code": null, "e": 11726, "s": 11723, "text": "\n" }, { "code": null, "e": 11729, "s": 11726, "text": "\n" }, { "code": null, "e": 11732, "s": 11729, "text": "\n" }, { "code": null, "e": 11745, "s": 11732, "text": "1, if t > 1\n" }, { "code": null, "e": 11771, "s": 11745, "text": "(t + 1)/2, if −1 ≤ t ≤ 1\n" }, { "code": null, "e": 11786, "s": 11771, "text": "0, if t < −1.\n" }, { "code": null, "e": 11791, "s": 11786, "text": "(6)\n" }, { "code": null, "e": 11902, "s": 11791, "text": "Fig. 1 provides an illustration for the two and three-\ndimensional cases. For the latter, we parameterize z =\n" }, { "code": null, "e": 11951, "s": 11902, "text": "(t1, t2, 0) and plot softmax1(z) and sparsemax1\n" }, { "code": null, "e": 11961, "s": 11951, "text": "(z) as a\n" }, { "code": null, "e": 12077, "s": 11961, "text": "function of t1 and t2. We can see that sparsemax is piece-\nwise linear, but asymptotically similar to the softmax.\n" }, { "code": null, "e": 12105, "s": 12077, "text": "2.5. Jacobian of Sparsemax\n" }, { "code": null, "e": 12158, "s": 12105, "text": "The Jacobian matrix of a transformation ρ, Jρ(z) :=\n" }, { "code": null, "e": 12220, "s": 12158, "text": "[∂ρi(z)/∂zj ]i,j , is of key importance to train models with\n" }, { "code": null, "e": 12278, "s": 12220, "text": "gradient-based optimization. We next derive the Jacobian\n" }, { "code": null, "e": 12397, "s": 12278, "text": "of the sparsemax activation, but before doing so, let us re-\ncall how the Jacobian of the softmax looks like. We have\n" }, { "code": null, "e": 12411, "s": 12397, "text": "∂softmaxi(z)\n" }, { "code": null, "e": 12416, "s": 12411, "text": "∂zj\n" }, { "code": null, "e": 12426, "s": 12416, "text": "= (δij e\n" }, { "code": null, "e": 12432, "s": 12426, "text": "zi P\n" }, { "code": null, "e": 12435, "s": 12432, "text": "k\n" }, { "code": null, "e": 12438, "s": 12435, "text": "e\n" }, { "code": null, "e": 12446, "s": 12438, "text": "zk − e\n" }, { "code": null, "e": 12452, "s": 12446, "text": "zi e\n" }, { "code": null, "e": 12460, "s": 12452, "text": "zj )/(\n" }, { "code": null, "e": 12463, "s": 12460, "text": "P\n" }, { "code": null, "e": 12466, "s": 12463, "text": "k\n" }, { "code": null, "e": 12469, "s": 12466, "text": "e\n" }, { "code": null, "e": 12475, "s": 12469, "text": "zk )\n" }, { "code": null, "e": 12478, "s": 12475, "text": "2\n" }, { "code": null, "e": 12518, "s": 12478, "text": "= softmaxi(z)(δij − softmaxj (z)), (7)\n" }, { "code": null, "e": 12577, "s": 12518, "text": "where δij is the Kronecker delta, which evaluates to 1 if\n" }, { "code": null, "e": 12634, "s": 12577, "text": "i = j and 0 otherwise. Letting p = softmax(z), the full\n" }, { "code": null, "e": 12681, "s": 12634, "text": "Jacobian can be written in matrix notation as\n" }, { "code": null, "e": 12715, "s": 12681, "text": "Jsoftmax(z) = Diag(p) − pp>, (8)\n" }, { "code": null, "e": 12771, "s": 12715, "text": "where Diag(p) is a matrix with p in the main diagonal.\n" }, { "code": null, "e": 12828, "s": 12771, "text": "Let us now turn to the sparsemax case. The sparsemax is\n" }, { "code": null, "e": 12890, "s": 12828, "text": "differentiable everywhere except at splitting points z where\n" }, { "code": null, "e": 12948, "s": 12890, "text": "the support set S(z) changes, i.e., where S(z) 6= S(z+d)\n" }, { "code": null, "e": 12980, "s": 12948, "text": "for some d and infinitesimal .\n" }, { "code": null, "e": 13009, "s": 12980, "text": "2 From Eq. 3, we have that:\n" }, { "code": null, "e": 13022, "s": 13009, "text": "∂sparsemaxi\n" }, { "code": null, "e": 13027, "s": 13022, "text": "(z)\n" }, { "code": null, "e": 13032, "s": 13027, "text": "∂zj\n" }, { "code": null, "e": 13035, "s": 13032, "text": "=\n" }, { "code": null, "e": 13038, "s": 13035, "text": "(\n" }, { "code": null, "e": 13045, "s": 13038, "text": "δij −\n" }, { "code": null, "e": 13052, "s": 13045, "text": "∂τ(z)\n" }, { "code": null, "e": 13057, "s": 13052, "text": "∂zj\n" }, { "code": null, "e": 13075, "s": 13057, "text": ", if zi > τ (z),\n" }, { "code": null, "e": 13094, "s": 13075, "text": "0, if zi ≤ τ (z).\n" }, { "code": null, "e": 13099, "s": 13094, "text": "(9)\n" }, { "code": null, "e": 13157, "s": 13099, "text": "From Eq. 4, the gradient of the threshold function τ is:\n" }, { "code": null, "e": 13165, "s": 13157, "text": "∂τ (z)\n" }, { "code": null, "e": 13170, "s": 13165, "text": "∂zj\n" }, { "code": null, "e": 13173, "s": 13170, "text": "=\n" }, { "code": null, "e": 13177, "s": 13173, "text": " 1\n" }, { "code": null, "e": 13185, "s": 13177, "text": "|S(z)|\n" }, { "code": null, "e": 13199, "s": 13185, "text": "if j ∈ S(z),\n" }, { "code": null, "e": 13217, "s": 13199, "text": "0, if j /∈ S(z).\n" }, { "code": null, "e": 13223, "s": 13217, "text": "(10)\n" }, { "code": null, "e": 13278, "s": 13223, "text": "Note that j ∈ S(z) ⇔ zj > τ (z). Therefore we obtain:\n" }, { "code": null, "e": 13291, "s": 13278, "text": "∂sparsemaxi\n" }, { "code": null, "e": 13296, "s": 13291, "text": "(z)\n" }, { "code": null, "e": 13301, "s": 13296, "text": "∂zj\n" }, { "code": null, "e": 13304, "s": 13301, "text": "=\n" }, { "code": null, "e": 13313, "s": 13306, "text": "δij −\n" }, { "code": null, "e": 13316, "s": 13313, "text": "1\n" }, { "code": null, "e": 13324, "s": 13316, "text": "|S(z)|\n" }, { "code": null, "e": 13343, "s": 13324, "text": ", if i, j ∈ S(z),\n" }, { "code": null, "e": 13363, "s": 13343, "text": "0, otherwise. (11)\n" }, { "code": null, "e": 13427, "s": 13363, "text": "Let s be an indicator vector whose ith entry is 1 if i ∈ S(z),\n" }, { "code": null, "e": 13481, "s": 13427, "text": "and 0 otherwise. We can write the Jacobian matrix as\n" }, { "code": null, "e": 13525, "s": 13481, "text": "Jsparsemax(z) = Diag(s) − ss>/|S(z)|. (12)\n" }, { "code": null, "e": 13640, "s": 13525, "text": "It is instructive to compare Eqs. 8 and 12. We may re-\ngard the Jacobian of sparsemax as the Laplacian of a graph\n" }, { "code": null, "e": 13696, "s": 13640, "text": "whose elements of S(z) are fully connected. To compute\n" }, { "code": null, "e": 13699, "s": 13696, "text": "2\n" }, { "code": null, "e": 13764, "s": 13699, "text": "For those points, we can take an arbitrary matrix in the set of\n" }, { "code": null, "e": 13831, "s": 13764, "text": "generalized Clarke’s Jacobians (Clarke, 1983), the convex hull of\n" }, { "code": null, "e": 13892, "s": 13831, "text": "all points of the form limt→∞ Jsparsemax(zt), where zt → z.\n" }, { "code": null, "e": 13979, "s": 13892, "text": "From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification\n" }, { "code": null, "e": 14038, "s": 13979, "text": "it, we only need S(z), which can be obtained in O(K) time\n" }, { "code": null, "e": 14093, "s": 14038, "text": "with the same algorithm that evaluates the sparsemax.\n" }, { "code": null, "e": 14156, "s": 14093, "text": "Often, e.g., in the gradient backpropagation algorithm, it is\n" }, { "code": null, "e": 14217, "s": 14156, "text": "not necessary to compute the full Jacobian matrix, but only\n" }, { "code": null, "e": 14276, "s": 14217, "text": "the product between the Jacobian and a given vector v. In\n" }, { "code": null, "e": 14316, "s": 14276, "text": "the softmax case, from Eq. 8, we have:\n" }, { "code": null, "e": 14335, "s": 14316, "text": "Jsoftmax(z)·v = p\n" }, { "code": null, "e": 14360, "s": 14335, "text": "(v−v ̄1), with v ̄ := P\n" }, { "code": null, "e": 14363, "s": 14360, "text": "j\n" }, { "code": null, "e": 14376, "s": 14363, "text": "pjvj , (13)\n" }, { "code": null, "e": 14383, "s": 14376, "text": "where\n" }, { "code": null, "e": 14430, "s": 14383, "text": "denotes the Hadamard product; this requires a\n" }, { "code": null, "e": 14489, "s": 14430, "text": "linear-time computation. For the sparsemax case, we have:\n" }, { "code": null, "e": 14511, "s": 14489, "text": "Jsparsemax(z)· v = s\n" }, { "code": null, "e": 14534, "s": 14511, "text": "(v − vˆ1), with vˆ :=\n" }, { "code": null, "e": 14537, "s": 14534, "text": "P\n" }, { "code": null, "e": 14545, "s": 14537, "text": "j∈S(z)\n" }, { "code": null, "e": 14549, "s": 14545, "text": "vj\n" }, { "code": null, "e": 14557, "s": 14549, "text": "|S(z)|\n" }, { "code": null, "e": 14560, "s": 14557, "text": ".\n" }, { "code": null, "e": 14566, "s": 14560, "text": "(14)\n" }, { "code": null, "e": 14625, "s": 14566, "text": "Interestingly, if sparsemax(z) has already been evaluated\n" }, { "code": null, "e": 14683, "s": 14625, "text": "(i.e., in the forward step), then so has S(z), hence the\n" }, { "code": null, "e": 14738, "s": 14683, "text": "nonzeros of Jsparsemax(z) · v can be computed in only\n" }, { "code": null, "e": 14857, "s": 14738, "text": "O(|S(z)|) time, which can be sublinear. This can be an im-\nportant advantage of sparsemax over softmax if K is large.\n" }, { "code": null, "e": 14910, "s": 14857, "text": "Computational efficiency. In sum, the computational\n" }, { "code": null, "e": 14967, "s": 14910, "text": "needs of softmax and sparsemax are compared as follows:\n" }, { "code": null, "e": 15026, "s": 14967, "text": "• At training time, sparsemax can backpropagate gradients\n" }, { "code": null, "e": 15073, "s": 15026, "text": "faster due to the sparsity (as stated above).\n" }, { "code": null, "e": 15135, "s": 15073, "text": "• At inference time, the softmax forward pass is faster, but\n" }, { "code": null, "e": 15192, "s": 15135, "text": "asymptotically both are linear time. In our experiments\n" }, { "code": null, "e": 15245, "s": 15192, "text": "(§4), even with the O(K log K) Algorithm 1, similar\n" }, { "code": null, "e": 15297, "s": 15245, "text": "runtimes were achieved with softmax and sparsemax.\n" }, { "code": null, "e": 15331, "s": 15297, "text": "3. A Loss Function for Sparsemax\n" }, { "code": null, "e": 15384, "s": 15331, "text": "Now that we have defined and analyzed the sparsemax\n" }, { "code": null, "e": 15446, "s": 15384, "text": "transformation, we will use it to design a new loss function\n" }, { "code": null, "e": 15572, "s": 15446, "text": "that resembles the logistic loss, but can yield sparse poste-\nrior distributions. Later (in §4.1–4.2), we apply this loss to\n" }, { "code": null, "e": 15633, "s": 15572, "text": "label proportion estimation and multi-label classification.\n" }, { "code": null, "e": 15653, "s": 15633, "text": "3.1. Logistic Loss\n" }, { "code": null, "e": 15668, "s": 15653, "text": "Let D := {(xi\n" }, { "code": null, "e": 15676, "s": 15668, "text": ", yi)}\n" }, { "code": null, "e": 15679, "s": 15676, "text": "N\n" }, { "code": null, "e": 15716, "s": 15679, "text": "i=1 be a dataset, where each xi ∈ R\n" }, { "code": null, "e": 15719, "s": 15716, "text": "D\n" }, { "code": null, "e": 15785, "s": 15719, "text": "is an input vector and yi ∈ {1, . . . , K} is a target label. We\n" }, { "code": null, "e": 15844, "s": 15785, "text": "consider empirical risk minimization problems of the form\n" }, { "code": null, "e": 15854, "s": 15844, "text": "minimize\n" }, { "code": null, "e": 15857, "s": 15854, "text": "λ\n" }, { "code": null, "e": 15860, "s": 15857, "text": "2\n" }, { "code": null, "e": 15865, "s": 15860, "text": "kWk\n" }, { "code": null, "e": 15868, "s": 15865, "text": "2\n" }, { "code": null, "e": 15873, "s": 15868, "text": "F +\n" }, { "code": null, "e": 15876, "s": 15873, "text": "1\n" }, { "code": null, "e": 15879, "s": 15876, "text": "N\n" }, { "code": null, "e": 15882, "s": 15879, "text": "X\n" }, { "code": null, "e": 15885, "s": 15882, "text": "N\n" }, { "code": null, "e": 15890, "s": 15885, "text": "i=1\n" }, { "code": null, "e": 15907, "s": 15890, "text": "L(Wxi + b; yi),\n" }, { "code": null, "e": 15921, "s": 15907, "text": "w.r.t. W ∈ R\n" }, { "code": null, "e": 15933, "s": 15921, "text": "K×D, b ∈ R\n" }, { "code": null, "e": 15942, "s": 15933, "text": "K, (15)\n" }, { "code": null, "e": 16001, "s": 15942, "text": "where L is a loss function, W is a matrix of weights, and\n" }, { "code": null, "e": 16060, "s": 16001, "text": "b is a bias vector. The loss function associated with the\n" }, { "code": null, "e": 16120, "s": 16060, "text": "softmax is the logistic loss (or negative log-likelihood):\n" }, { "code": null, "e": 16156, "s": 16120, "text": "Lsoftmax(z; k) = − log softmaxk(z)\n" }, { "code": null, "e": 16170, "s": 16156, "text": "= −zk + logX\n" }, { "code": null, "e": 16173, "s": 16170, "text": "j\n" }, { "code": null, "e": 16189, "s": 16173, "text": "exp(zj ), (16)\n" }, { "code": null, "e": 16220, "s": 16189, "text": "where z = Wxi + b, and k = yi\n" }, { "code": null, "e": 16246, "s": 16220, "text": "is the “gold” label. The\n" }, { "code": null, "e": 16289, "s": 16246, "text": "gradient of this loss is, invoking Eq. 7,\n" }, { "code": null, "e": 16332, "s": 16289, "text": "∇zLsoftmax(z; k) = −δk + softmax(z), (17)\n" }, { "code": null, "e": 16392, "s": 16332, "text": "where δk denotes the delta distribution on k, [δk]j = 1 if\n" }, { "code": null, "e": 16451, "s": 16392, "text": "j = k, and 0 otherwise. This is a well-known result; when\n" }, { "code": null, "e": 16513, "s": 16451, "text": "plugged into a gradient-based optimizer, it leads to updates\n" }, { "code": null, "e": 16573, "s": 16513, "text": "that move probability mass from the distribution predicted\n" }, { "code": null, "e": 16633, "s": 16573, "text": "by the current model (i.e., softmaxk(z)) to the gold label\n" }, { "code": null, "e": 16689, "s": 16633, "text": "(via δk). Can we have something similar for sparsemax?\n" }, { "code": null, "e": 16710, "s": 16689, "text": "3.2. Sparsemax Loss\n" }, { "code": null, "e": 16771, "s": 16710, "text": "A nice aspect of the log-likelihood (Eq. 16) is that adding\n" }, { "code": null, "e": 16833, "s": 16771, "text": "up loss terms for several examples, assumed i.i.d, we obtain\n" }, { "code": null, "e": 16896, "s": 16833, "text": "the log-probability of the full training data. Unfortunately,\n" }, { "code": null, "e": 16953, "s": 16896, "text": "this idea cannot be carried out to sparsemax: now, some\n" }, { "code": null, "e": 17014, "s": 16953, "text": "labels may have exactly probability zero, so any model that\n" }, { "code": null, "e": 17075, "s": 17014, "text": "assigns zero probability to a gold label would zero out the\n" }, { "code": null, "e": 17137, "s": 17075, "text": "probability of the entire training sample. This is of course\n" }, { "code": null, "e": 17195, "s": 17137, "text": "highly undesirable. One possible workaround is to define\n" }, { "code": null, "e": 17198, "s": 17195, "text": "L\n" }, { "code": null, "e": 17239, "s": 17200, "text": "sparsemax(z; k) = − log + sparsemaxk\n" }, { "code": null, "e": 17244, "s": 17239, "text": "(z)\n" }, { "code": null, "e": 17251, "s": 17244, "text": "1 + K\n" }, { "code": null, "e": 17259, "s": 17251, "text": ", (18)\n" }, { "code": null, "e": 17307, "s": 17259, "text": "where is a small constant, and +sparsemaxk(z)\n" }, { "code": null, "e": 17404, "s": 17307, "text": "1+K is a “per-\nturbed” sparsemax. However, this loss is non-convex, un-\nlike the one in Eq. 16.\n" }, { "code": null, "e": 17465, "s": 17404, "text": "Another possibility, which we explore here, is to construct\n" }, { "code": null, "e": 17524, "s": 17465, "text": "an alternative loss function whose gradient resembles the\n" }, { "code": null, "e": 17643, "s": 17524, "text": "one in Eq. 17. Note that the gradient is particularly im-\nportant, since it is directly involved in the model updates\n" }, { "code": null, "e": 17699, "s": 17643, "text": "for typical optimization algorithms. Formally, we want\n" }, { "code": null, "e": 17753, "s": 17699, "text": "Lsparsemax to be a differentiable function such that\n" }, { "code": null, "e": 17800, "s": 17753, "text": "∇zLsparsemax(z; k) = −δk + sparsemax(z). (19)\n" }, { "code": null, "e": 17914, "s": 17800, "text": "We show below that this property is fulfilled by the follow-\ning function, henceforth called the sparsemax loss:\n" }, { "code": null, "e": 17939, "s": 17914, "text": "Lsparsemax(z; k) = −zk+\n" }, { "code": null, "e": 17942, "s": 17939, "text": "1\n" }, { "code": null, "e": 17945, "s": 17942, "text": "2\n" }, { "code": null, "e": 17948, "s": 17945, "text": "X\n" }, { "code": null, "e": 17956, "s": 17948, "text": "j∈S(z)\n" }, { "code": null, "e": 17960, "s": 17956, "text": "(z\n" }, { "code": null, "e": 17963, "s": 17960, "text": "2\n" }, { "code": null, "e": 17969, "s": 17963, "text": "j −τ\n" }, { "code": null, "e": 17972, "s": 17969, "text": "2\n" }, { "code": null, "e": 17980, "s": 17972, "text": "(z))+1\n" }, { "code": null, "e": 17983, "s": 17980, "text": "2\n" }, { "code": null, "e": 17991, "s": 17983, "text": ", (20)\n" }, { "code": null, "e": 18000, "s": 17991, "text": "where τ\n" }, { "code": null, "e": 18003, "s": 18000, "text": "2\n" }, { "code": null, "e": 18054, "s": 18003, "text": "is the square of the threshold function in Eq. 4.\n" }, { "code": null, "e": 18116, "s": 18054, "text": "This loss, which has never been considered in the literature\n" }, { "code": null, "e": 18175, "s": 18116, "text": "to the best of our knowledge, has a number of interesting\n" }, { "code": null, "e": 18220, "s": 18175, "text": "properties, stated in the next proposition.\n" }, { "code": null, "e": 18256, "s": 18220, "text": "Proposition 3 The following holds:\n" }, { "code": null, "e": 18318, "s": 18256, "text": "1. Lsparsemax is differentiable everywhere, and its gradient\n" }, { "code": null, "e": 18357, "s": 18318, "text": "is given by the expression in Eq. 19.\n" }, { "code": null, "e": 18383, "s": 18357, "text": "2. Lsparsemax is convex.\n" }, { "code": null, "e": 18437, "s": 18383, "text": "3. Lsparsemax(z + c1; k) = Lsparsemax(z; k), ∀c ∈ R.\n" }, { "code": null, "e": 18701, "s": 18437, "text": "The idea is to set the probabilities of the smallest values of z to zero and keep only probabilities of the highest values of z, but still keep the function differentiable to ensure successful application of backpropagation algorithm. This function is defined as:" }, { "code": null, "e": 18878, "s": 18701, "text": "Here τ(z) is called threshold function and it defines the support function S(z) that contains all non-zero indices of p. A python implementation of sparsemax function is below:" }, { "code": null, "e": 19025, "s": 18878, "text": "Running it and softmax on the same values we can indeed see that it does set some of the probabilities to zero, where softmax keeps them non-zero:" }, { "code": null, "e": 19196, "s": 19025, "text": "np.around(sparsemax([0.1, 1.1, 0.2, 0.3]), decimals=3)array([0. , 0.9, 0. , 0.1])np.around(softmax([0.1, 1.1, 0.2, 0.3]), decimals=3)array([0.165, 0.45 , 0.183, 0.202])" }, { "code": null, "e": 19387, "s": 19196, "text": "It is also interesting to see how the two functions are different in the two-dimensional case. In this case softmax becomes a sigmoid function, and sparsemax can be represented in this form:" }, { "code": null, "e": 19441, "s": 19387, "text": "The picture below illustrates how they are different:" }, { "code": null, "e": 19571, "s": 19441, "text": "Note, that the sparsemax function is not differentiable everywhere (but neither is relu), but where it is is an easy computation:" }, { "code": null, "e": 19630, "s": 19571, "text": "Here |S(z)| is the number of elements in the support S(z)." }, { "code": null, "e": 20023, "s": 19630, "text": "The obvious problem with sparsemax is vanishing gradient. You can see that the derivative turns to zero once z becomes large. The authors acknowledged the problem and even proposed a new loss function in place of cross-entropy loss. However I believe the main advantage of sparsemax is not in the output layer, but in the middle of the neural network, for example, in the attention mechanism." } ]
How to Package A Python Application using Anaconda and Docker | Towards Data Science
I rarely use anaconda for my python projects, but recently it happened to me to rely on a python package which is available only via Anaconda. Therefore, I had to set my project using conda environment. However, I encountered a problem packaging my python application using Docker, because of the conda virtual environment and I didn’t find much documentation to solve my problem. I finally found a solution and I share it with you here in this article. The Source codes for this article are available on GitHub below: github.com The project structure for this article is the simple. Four files are necessary : Create a file with .yaml extension: environment.yaml Name your conda environment, for instance app Add a list of channels where the desired packages are hosted List packages you want to install such as flask, gunicorn, numpy... under dependencies You can also install pip packages from the YAML file. One way to it is by adding a pip command to install (pip) packages from a requirements.txt, (-r in the command stands for requirement) For instance: requirements.txt Here we have created a test file main.py for testing the application. main.py Create a file named Dockerfile (without extension) from which we build a docker image for our Python application. Dockerfile For simplicity we start from the base image of miniconda3 (line1) Copy the files from the folder to docker (line 6) Create a conda environment and install the packages defined in YAML file (line 9) Edit the shell command so we can launch python scripts from within the newly created conda environment (line 11) Define an entry-point for the docker image such that it execute the main.py python script of the application (line 13) We build a docker image, named app, with the following commands docker build --tag myapp . ... then wait for docker to build an image for your app (it might tight a take for downloading and update it the packages list). Note: The Dockerfile must be located in the root directory of the applicationMake sure Docker is installed on your machine (www.docker.com). The Dockerfile must be located in the root directory of the application Make sure Docker is installed on your machine (www.docker.com). To run the App from the docker image we created docker run --rm -ti myapp This should outputs: Hello World !Numpy version is 1.19.4 Done. In this tutorial I walked you through a quick tutorial on how to package your python application using Docker and leveraging python package from pip and anaconda together. The key solution is in the SHELL command of Dockerfile. Without it Docker can not run the code inside the conda environment. I hope it will benefit you. Peace. github.com www.python.org www.anaconda.com www.docker.com PS: If you encounter a problem please create an issue on GitHub or comment below.
[ { "code": null, "e": 626, "s": 172, "text": "I rarely use anaconda for my python projects, but recently it happened to me to rely on a python package which is available only via Anaconda. Therefore, I had to set my project using conda environment. However, I encountered a problem packaging my python application using Docker, because of the conda virtual environment and I didn’t find much documentation to solve my problem. I finally found a solution and I share it with you here in this article." }, { "code": null, "e": 691, "s": 626, "text": "The Source codes for this article are available on GitHub below:" }, { "code": null, "e": 702, "s": 691, "text": "github.com" }, { "code": null, "e": 783, "s": 702, "text": "The project structure for this article is the simple. Four files are necessary :" }, { "code": null, "e": 819, "s": 783, "text": "Create a file with .yaml extension:" }, { "code": null, "e": 836, "s": 819, "text": "environment.yaml" }, { "code": null, "e": 882, "s": 836, "text": "Name your conda environment, for instance app" }, { "code": null, "e": 943, "s": 882, "text": "Add a list of channels where the desired packages are hosted" }, { "code": null, "e": 1030, "s": 943, "text": "List packages you want to install such as flask, gunicorn, numpy... under dependencies" }, { "code": null, "e": 1219, "s": 1030, "text": "You can also install pip packages from the YAML file. One way to it is by adding a pip command to install (pip) packages from a requirements.txt, (-r in the command stands for requirement)" }, { "code": null, "e": 1233, "s": 1219, "text": "For instance:" }, { "code": null, "e": 1250, "s": 1233, "text": "requirements.txt" }, { "code": null, "e": 1320, "s": 1250, "text": "Here we have created a test file main.py for testing the application." }, { "code": null, "e": 1328, "s": 1320, "text": "main.py" }, { "code": null, "e": 1442, "s": 1328, "text": "Create a file named Dockerfile (without extension) from which we build a docker image for our Python application." }, { "code": null, "e": 1453, "s": 1442, "text": "Dockerfile" }, { "code": null, "e": 1519, "s": 1453, "text": "For simplicity we start from the base image of miniconda3 (line1)" }, { "code": null, "e": 1569, "s": 1519, "text": "Copy the files from the folder to docker (line 6)" }, { "code": null, "e": 1651, "s": 1569, "text": "Create a conda environment and install the packages defined in YAML file (line 9)" }, { "code": null, "e": 1764, "s": 1651, "text": "Edit the shell command so we can launch python scripts from within the newly created conda environment (line 11)" }, { "code": null, "e": 1883, "s": 1764, "text": "Define an entry-point for the docker image such that it execute the main.py python script of the application (line 13)" }, { "code": null, "e": 1947, "s": 1883, "text": "We build a docker image, named app, with the following commands" }, { "code": null, "e": 1974, "s": 1947, "text": "docker build --tag myapp ." }, { "code": null, "e": 2103, "s": 1974, "text": "... then wait for docker to build an image for your app (it might tight a take for downloading and update it the packages list)." }, { "code": null, "e": 2109, "s": 2103, "text": "Note:" }, { "code": null, "e": 2244, "s": 2109, "text": "The Dockerfile must be located in the root directory of the applicationMake sure Docker is installed on your machine (www.docker.com)." }, { "code": null, "e": 2316, "s": 2244, "text": "The Dockerfile must be located in the root directory of the application" }, { "code": null, "e": 2380, "s": 2316, "text": "Make sure Docker is installed on your machine (www.docker.com)." }, { "code": null, "e": 2428, "s": 2380, "text": "To run the App from the docker image we created" }, { "code": null, "e": 2455, "s": 2428, "text": "docker run --rm -ti myapp " }, { "code": null, "e": 2476, "s": 2455, "text": "This should outputs:" }, { "code": null, "e": 2514, "s": 2476, "text": "Hello World !Numpy version is 1.19.4" }, { "code": null, "e": 2520, "s": 2514, "text": "Done." }, { "code": null, "e": 2817, "s": 2520, "text": "In this tutorial I walked you through a quick tutorial on how to package your python application using Docker and leveraging python package from pip and anaconda together. The key solution is in the SHELL command of Dockerfile. Without it Docker can not run the code inside the conda environment." }, { "code": null, "e": 2845, "s": 2817, "text": "I hope it will benefit you." }, { "code": null, "e": 2852, "s": 2845, "text": "Peace." }, { "code": null, "e": 2863, "s": 2852, "text": "github.com" }, { "code": null, "e": 2878, "s": 2863, "text": "www.python.org" }, { "code": null, "e": 2895, "s": 2878, "text": "www.anaconda.com" }, { "code": null, "e": 2910, "s": 2895, "text": "www.docker.com" } ]
How to get the height and width of the android.widget.ImageView?
This example demonstrates how do I get the height and width of the android.widget.ImageView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="200dp" android:src="@drawable/image"/> <Button android:id="@+id/btnCheckSize" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20sp" android:textSize="12sp" android:textStyle="bold" android:text="Check ImageView size"/> <TextView android:id="@+id/textView" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textSize="16sp" android:textStyle="bold"/> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; Button button; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); textView = findViewById(R.id.textView); button = findViewById(R.id.btnCheckSize); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setText(String.format("Size of ImageView:\nHeight: %s\nWidth: %s", String.valueOf(imageView.getWidth()), String.valueOf(imageView.getHeight()))); } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 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 – Click here to download the project code.
[ { "code": null, "e": 1166, "s": 1062, "text": "This example demonstrates how do I get the height and width of the android.widget.ImageView in android." }, { "code": null, "e": 1295, "s": 1166, "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": 1360, "s": 1295, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2453, "s": 1360, "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 <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"200dp\"\n android:src=\"@drawable/image\"/>\n <Button\n android:id=\"@+id/btnCheckSize\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20sp\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold\"\n android:text=\"Check ImageView size\"/>\n <TextView\n android:id=\"@+id/textView\"\n android:layout_marginTop=\"10dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"/>\n</LinearLayout>" }, { "code": null, "e": 2510, "s": 2453, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3437, "s": 2510, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n Button button;\n ImageView imageView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n textView = findViewById(R.id.textView);\n button = findViewById(R.id.btnCheckSize);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n textView.setText(String.format(\"Size of ImageView:\\nHeight: %s\\nWidth: %s\", String.valueOf(imageView.getWidth()), String.valueOf(imageView.getHeight())));\n }\n });\n }\n}" }, { "code": null, "e": 3492, "s": 3437, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4162, "s": 3492, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4509, "s": 4162, "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": 4550, "s": 4509, "text": "Click here to download the project code." } ]
Why the #1054 - Unknown column error occurs in MySQL and how to fix it?
Let’s see when the #1054 error occurs in MySQL. While inserting a varchar value, if you will forget to add single quotes, then this error will arise. Following is the error − mysql> insert into DemoTable798 values(100,Adam); ERROR 1054 (42S22): Unknown column 'Adam' in 'field list' You need to use single quotes around the string value to fix this error as shown below − mysql> insert into DemoTable798 values(100,’Adam’); Let us first create a table − mysql> create table DemoTable798 ( StudentId int, StudentName varchar(100) ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert command − mysql> insert into DemoTable798 values(100,'Adam'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable798 values(101,'Chris'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable798 values(102,'Robert'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable798 values(103,'Carol'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select *from DemoTable798; This will produce the following output - +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 100 | Adam | | 101 | Chris | | 102 | Robert | | 103 | Carol | +-----------+-------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1213, "s": 1062, "text": "Let’s see when the #1054 error occurs in MySQL. While inserting a varchar value, if you will forget to add single quotes, then this error will arise.\n" }, { "code": null, "e": 1238, "s": 1213, "text": "Following is the error −" }, { "code": null, "e": 1346, "s": 1238, "text": "mysql> insert into DemoTable798 values(100,Adam);\nERROR 1054 (42S22): Unknown column 'Adam' in 'field list'" }, { "code": null, "e": 1435, "s": 1346, "text": "You need to use single quotes around the string value to fix this error as shown below −" }, { "code": null, "e": 1487, "s": 1435, "text": "mysql> insert into DemoTable798 values(100,’Adam’);" }, { "code": null, "e": 1517, "s": 1487, "text": "Let us first create a table −" }, { "code": null, "e": 1638, "s": 1517, "text": "mysql> create table DemoTable798 (\n StudentId int,\n StudentName varchar(100)\n);\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1694, "s": 1638, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2050, "s": 1694, "text": "mysql> insert into DemoTable798 values(100,'Adam');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable798 values(101,'Chris');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable798 values(102,'Robert');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable798 values(103,'Carol');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2110, "s": 2050, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2144, "s": 2110, "text": "mysql> select *from DemoTable798;" }, { "code": null, "e": 2185, "s": 2144, "text": "This will produce the following output -" }, { "code": null, "e": 2434, "s": 2185, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 100 | Adam |\n| 101 | Chris |\n| 102 | Robert |\n| 103 | Carol |\n+-----------+-------------+\n4 rows in set (0.00 sec)" } ]
How to lock Screen Orientation programmatically in iOS?
You might come across a scenario where you need to show the UI in a specific orientation may be Landscape or Portrait. We will be seeing how to lock orientation programmatically using Swift in iOS. Open Xcode → New Project → ViewController.swift write the below code. // Set the shouldAutorotate to False override open var shouldAutorotate: Bool { return false } // Specify the orientation. override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait }
[ { "code": null, "e": 1181, "s": 1062, "text": "You might come across a scenario where you need to show the UI in a specific orientation may be Landscape or Portrait." }, { "code": null, "e": 1260, "s": 1181, "text": "We will be seeing how to lock orientation programmatically using Swift in iOS." }, { "code": null, "e": 1330, "s": 1260, "text": "Open Xcode → New Project → ViewController.swift write the below code." }, { "code": null, "e": 1558, "s": 1330, "text": "// Set the shouldAutorotate to False\noverride open var shouldAutorotate: Bool {\n return false\n}\n\n// Specify the orientation.\noverride open var supportedInterfaceOrientations: UIInterfaceOrientationMask {\n return .portrait\n}" } ]
CSS font-weight Property - GeeksforGeeks
11 Oct, 2021 The font-weight property of the CSS is used to set the weight or thickness of the font being used with the HTML Text. The font-weight applied will depend on font-family used and the browser. For instance, some font-family is available only in specific weights. Syntax: font-weight: normal|bold|lighter|bolder|number|initial|inherit|unset; Property Values: normal: This is the default font-weight & defines the normal font-weight. It is equal to the number value 400. bold: This defines the bold font-weight, it is equal to the number value 700. lighter: This makes the font-weight one level lighter than the parent element, considering the available font weights of the font family. bolder: This makes the font-weight one level heavier than the parent element, considering the available font weights of the font family. number: This sets the font-weight according to the number specified. The number can range between 1 to 1000. If the exact weight is unavailable, a suitable weight is applied. Global Values: initial: This sets the font-weight to the initial(default) value. inherit: This sets the font-weight equal to the value inherited from its parent element. unset: This sets the font-weight equal to the value inherited from its parent element since font-weight is an inheritable property. When lighter or bolder is specified, the below chart shows how the absolute font-weight of the element is determined. 100 100 400 200 100 400 300 100 400 400 100 700 500 100 700 600 400 900 700 400 900 800 700 900 900 700 900 Example: The following example demonstrates the use of CSS font-weight property in which the property has been set to different values. HTML <!DOCTYPE html><html><head> <title> font-weight property </title> <!-- font-weight CSS property --> <style> body { font-weight: bold; font-family: sans-serif; } p.one { font-weight: bold; } p.two { font-weight: lighter; } p.three { font-weight: 1000; } p.four { font-weight: initial; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>CSS font-weight Property</h3> <!-- font-weight: bold; length; property --> <p class="one"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <!-- font-weight: lighter; length; property --> <p class="two"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <!-- font-weight: 1000; length; property --> <p class="three"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <!-- font-weight: initial; length; property --> <p class="four"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </body></html> Output: Supported Browsers: The browser supported by CSS font-weight Property are listed below: Google Chrome 2.0 Internet Explorer 3.0 Microsoft Edge 12.0 Firefox 1.0 Safari 1.0 Opera 3.5 Akanksha_Rai ManasChhabra2 bhaskargeeksforgeeks CSS-Properties Picked Technical Scripter 2018 CSS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form 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 ? Convert a string to an integer in JavaScript
[ { "code": null, "e": 23720, "s": 23692, "text": "\n11 Oct, 2021" }, { "code": null, "e": 23981, "s": 23720, "text": "The font-weight property of the CSS is used to set the weight or thickness of the font being used with the HTML Text. The font-weight applied will depend on font-family used and the browser. For instance, some font-family is available only in specific weights." }, { "code": null, "e": 23989, "s": 23981, "text": "Syntax:" }, { "code": null, "e": 24059, "s": 23989, "text": "font-weight: normal|bold|lighter|bolder|number|initial|inherit|unset;" }, { "code": null, "e": 24076, "s": 24059, "text": "Property Values:" }, { "code": null, "e": 24187, "s": 24076, "text": "normal: This is the default font-weight & defines the normal font-weight. It is equal to the number value 400." }, { "code": null, "e": 24265, "s": 24187, "text": "bold: This defines the bold font-weight, it is equal to the number value 700." }, { "code": null, "e": 24403, "s": 24265, "text": "lighter: This makes the font-weight one level lighter than the parent element, considering the available font weights of the font family." }, { "code": null, "e": 24540, "s": 24403, "text": "bolder: This makes the font-weight one level heavier than the parent element, considering the available font weights of the font family." }, { "code": null, "e": 24715, "s": 24540, "text": "number: This sets the font-weight according to the number specified. The number can range between 1 to 1000. If the exact weight is unavailable, a suitable weight is applied." }, { "code": null, "e": 24730, "s": 24715, "text": "Global Values:" }, { "code": null, "e": 24796, "s": 24730, "text": "initial: This sets the font-weight to the initial(default) value." }, { "code": null, "e": 24885, "s": 24796, "text": "inherit: This sets the font-weight equal to the value inherited from its parent element." }, { "code": null, "e": 25017, "s": 24885, "text": "unset: This sets the font-weight equal to the value inherited from its parent element since font-weight is an inheritable property." }, { "code": null, "e": 25135, "s": 25017, "text": "When lighter or bolder is specified, the below chart shows how the absolute font-weight of the element is determined." }, { "code": null, "e": 25139, "s": 25135, "text": "100" }, { "code": null, "e": 25143, "s": 25139, "text": "100" }, { "code": null, "e": 25147, "s": 25143, "text": "400" }, { "code": null, "e": 25151, "s": 25147, "text": "200" }, { "code": null, "e": 25155, "s": 25151, "text": "100" }, { "code": null, "e": 25159, "s": 25155, "text": "400" }, { "code": null, "e": 25163, "s": 25159, "text": "300" }, { "code": null, "e": 25167, "s": 25163, "text": "100" }, { "code": null, "e": 25171, "s": 25167, "text": "400" }, { "code": null, "e": 25175, "s": 25171, "text": "400" }, { "code": null, "e": 25179, "s": 25175, "text": "100" }, { "code": null, "e": 25183, "s": 25179, "text": "700" }, { "code": null, "e": 25187, "s": 25183, "text": "500" }, { "code": null, "e": 25191, "s": 25187, "text": "100" }, { "code": null, "e": 25195, "s": 25191, "text": "700" }, { "code": null, "e": 25199, "s": 25195, "text": "600" }, { "code": null, "e": 25203, "s": 25199, "text": "400" }, { "code": null, "e": 25207, "s": 25203, "text": "900" }, { "code": null, "e": 25211, "s": 25207, "text": "700" }, { "code": null, "e": 25215, "s": 25211, "text": "400" }, { "code": null, "e": 25219, "s": 25215, "text": "900" }, { "code": null, "e": 25223, "s": 25219, "text": "800" }, { "code": null, "e": 25227, "s": 25223, "text": "700" }, { "code": null, "e": 25231, "s": 25227, "text": "900" }, { "code": null, "e": 25235, "s": 25231, "text": "900" }, { "code": null, "e": 25239, "s": 25235, "text": "700" }, { "code": null, "e": 25243, "s": 25239, "text": "900" }, { "code": null, "e": 25379, "s": 25243, "text": "Example: The following example demonstrates the use of CSS font-weight property in which the property has been set to different values." }, { "code": null, "e": 25384, "s": 25379, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title> font-weight property </title> <!-- font-weight CSS property --> <style> body { font-weight: bold; font-family: sans-serif; } p.one { font-weight: bold; } p.two { font-weight: lighter; } p.three { font-weight: 1000; } p.four { font-weight: initial; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>CSS font-weight Property</h3> <!-- font-weight: bold; length; property --> <p class=\"one\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <!-- font-weight: lighter; length; property --> <p class=\"two\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <!-- font-weight: 1000; length; property --> <p class=\"three\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <!-- font-weight: initial; length; property --> <p class=\"four\"> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </body></html>", "e": 27563, "s": 25384, "text": null }, { "code": null, "e": 27571, "s": 27563, "text": "Output:" }, { "code": null, "e": 27659, "s": 27571, "text": "Supported Browsers: The browser supported by CSS font-weight Property are listed below:" }, { "code": null, "e": 27677, "s": 27659, "text": "Google Chrome 2.0" }, { "code": null, "e": 27699, "s": 27677, "text": "Internet Explorer 3.0" }, { "code": null, "e": 27719, "s": 27699, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 27731, "s": 27719, "text": "Firefox 1.0" }, { "code": null, "e": 27742, "s": 27731, "text": "Safari 1.0" }, { "code": null, "e": 27752, "s": 27742, "text": "Opera 3.5" }, { "code": null, "e": 27765, "s": 27752, "text": "Akanksha_Rai" }, { "code": null, "e": 27779, "s": 27765, "text": "ManasChhabra2" }, { "code": null, "e": 27800, "s": 27779, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27815, "s": 27800, "text": "CSS-Properties" }, { "code": null, "e": 27822, "s": 27815, "text": "Picked" }, { "code": null, "e": 27846, "s": 27822, "text": "Technical Scripter 2018" }, { "code": null, "e": 27850, "s": 27846, "text": "CSS" }, { "code": null, "e": 27869, "s": 27850, "text": "Technical Scripter" }, { "code": null, "e": 27886, "s": 27869, "text": "Web Technologies" }, { "code": null, "e": 27984, "s": 27886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28046, "s": 27984, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28096, "s": 28046, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28154, "s": 28096, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28202, "s": 28154, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28252, "s": 28202, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 28294, "s": 28252, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28327, "s": 28294, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28389, "s": 28327, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28432, "s": 28389, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use context in a fragment?
This example demonstrate about How to use context in a fragment Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/linearlayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ccc" android:layout_weight="1" android:orientation="vertical"> <fragment android:name="com.example.myapplication.FirstFragment" android:id="@+id/frag_1" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> <LinearLayout android:id="@+id/linearlayout02" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:background="#eee" android:orientation="vertical"> <fragment android:name="com.example.myapplication.SecondFragment" android:id="@+id/frag_2" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> </LinearLayout> In the above code, we have taken two fragments. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 4 − Add the following code to src/ FirstFragment.java package com.example.myapplication; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class FirstFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment, null); TextView but = (TextView) root.findViewById(R.id.text); but.setText(""+getActivity()); return root; } } Step 4 − Add the following code to src/ SecondFragment.java package com.example.myapplication; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class SecondFragment extends Fragment { TextView textView; View view; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment, container, false); return view; } } 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 – Click here to download the project code
[ { "code": null, "e": 1126, "s": 1062, "text": "This example demonstrate about How to use context in a fragment" }, { "code": null, "e": 1255, "s": 1126, "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": 1320, "s": 1255, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2477, "s": 1320, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <LinearLayout\n android:id=\"@+id/linearlayout01\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:background=\"#ccc\"\n android:layout_weight=\"1\"\n android:orientation=\"vertical\">\n <fragment android:name=\"com.example.myapplication.FirstFragment\"\n android:id=\"@+id/frag_1\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\" />\n </LinearLayout>\n <LinearLayout\n android:id=\"@+id/linearlayout02\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:layout_weight=\"1\"\n android:background=\"#eee\"\n android:orientation=\"vertical\">\n <fragment android:name=\"com.example.myapplication.SecondFragment\"\n android:id=\"@+id/frag_2\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\" />\n </LinearLayout>\n</LinearLayout>" }, { "code": null, "e": 2525, "s": 2477, "text": "In the above code, we have taken two fragments." }, { "code": null, "e": 2582, "s": 2525, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2905, "s": 2582, "text": "package com.example.myapplication;\nimport android.os.Bundle;\nimport android.support.v4.app.FragmentActivity;\npublic class MainActivity extends FragmentActivity {\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 2964, "s": 2905, "text": "Step 4 − Add the following code to src/ FirstFragment.java" }, { "code": null, "e": 3555, "s": 2964, "text": "package com.example.myapplication;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class FirstFragment extends Fragment {\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment, null);\n TextView but = (TextView) root.findViewById(R.id.text);\n but.setText(\"\"+getActivity());\n return root;\n }\n}" }, { "code": null, "e": 3615, "s": 3555, "text": "Step 4 − Add the following code to src/ SecondFragment.java" }, { "code": null, "e": 4263, "s": 3615, "text": "package com.example.myapplication;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class SecondFragment extends Fragment {\n TextView textView;\n View view;\n @Nullable\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n view = inflater.inflate(R.layout.fragment, container, false);\n return view;\n }\n}" }, { "code": null, "e": 4610, "s": 4263, "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": 4650, "s": 4610, "text": "Click here to download the project code" } ]
Symfony - View Engine
A View Layer is the presentation layer of the MVC application. It separates the application logic from the presentation logic. When a controller needs to generate HTML, CSS, or any other content then, it forwards the task to the templating engine. Templates are basically text files used to generate any text-based documents such as HTML, XML, etc. It is used to save time and reduce errors. By default, templates can reside in two different locations − app/Resources/views/ − The application's views directory can contain your application's layouts and templates of the application bundle. It also overrides third party bundle templates. vendor/path/to/Bundle/Resources/views/ − Each third party bundle contains its templates in it's “Resources/views/” directory. Symfony uses a powerful templating language called Twig. Twig allows you to write concise and readable templates in a very easy manner. Twig templates are simple and won't process PHP tags. Twig performs whitespace control, sandboxing, and automatic HTML escaping. Twig contains three types of special syntax − {{ ... }} − Prints a variable or the result of an expression to the template. {{ ... }} − Prints a variable or the result of an expression to the template. {% ... %} − A tag that controls the logic of the template. It is mainly used to execute a function. {% ... %} − A tag that controls the logic of the template. It is mainly used to execute a function. {# ... #} − Comment syntax. It is used to add a single or multi-line comments. {# ... #} − Comment syntax. It is used to add a single or multi-line comments. The twig base template is located at “app/Resources/views/base.html.twig”. Let’s go through a simple example using twig engine. <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class StudentController extends Controller { /** * @Route("/student/home") */ public function homeAction() { return $this->render('student/home.html.twig'); } } Here, the render() method renders a template and puts that content into a Response object. Now move to the “views” directory and create a folder “student” and inside that folder create a file “home.html.twig”. Add the following changes in the file. //app/Resources/views/student/home.html.twig <h3>Student application!</h3> You can obtain the result by requesting the url “http://localhost:8000/student/home”. By default, Twig comes with a long list of tags, filters, and functions. Let’s go through one by one in detail. Twig supports the following important tags − The do tag performs similar functions as regular expression with the exception that it doesn't print anything. Its syntax is as follows − {% do 5 + 6 %} The include statement includes a template and returns the rendered content of that file into the current namespace. Its syntax is as follows − {% include 'template.html' %} The extends tag can be used to extend a template from another one. Its syntax is as follows − {% extends "template.html" %} Block acts as a placeholder and replaces the contents. Block names consists of alphanumeric characters and underscores. For example, <title>{% block title %}{% endblock %}</title> The embed tag performs a combination of both include and extends. It allows you to include another template's contents. It also allows you to override any block defined inside the included template, such as when extending a template. Its syntax is as follows − {% embed “new_template.twig” %} {# These blocks are defined in “new_template.twig" #} {% block center %} Block content {% endblock %} {% endembed %} Filter sections allow you to apply regular Twig filters on a block of template data. For example, {% filter upper %} symfony framework {% endfilter %} Here, the text will be changed to upper case. For loop fetches each item in a sequence. For example, {% for x in 0..10 %} {{ x }} {% endfor %} The if statement in Twig is similar to PHP. The expression evaluates to true or false. For example, {% if value == true %} <p>Simple If statement</p> {% endif %} Twig contains filters. It is used to modify content before being rendered. Following are some of the notable filters. The length filter returns the length of a string. Its syntax is as follows − {% if name|length > 5 %} ... {% endif %} The lower filter converts a value to lowercase. For example, {{ 'SYMFONY'|lower }} It would produce the following result − symfony Similarly, you can try for upper case. The replace filter formats a given string by replacing the placeholders. For example, {{ "tutorials point site %si% and %te%."|replace({'%si%': web, '%te%': "site"}) }} It will produce the following result − tutorials point website The title filter returns a titlecase version of the value. For example, {{ 'symfony framework '|title }} It will produce the following result − Symfony Framework The sort filter sorts an array. Its syntax is as follows − {% for user in names|sort %} ... {% endfor %} The trim filter trims whitespace (or other characters) from the beginning and the end of a string. For example, {{ ' Symfony! '|trim }} It will produce the following result − Symfony! Twig supports functions. It is used to obtain a particular result. Following are some of the important Twig functions. The attribute function can be used to access a “dynamic” attribute of a variable. Its syntax is as follows − {{ attribute(object, method) }} {{ attribute(object, method, arguments) }} {{ attribute(array, item) }} For example, {{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }} Constant function returns the constant value for a specified string. For example, {{ constant('Namespace\\Classname::CONSTANT_NAME') }} The cycle function cycles on an array of values. For example, {% set months = [‘Jan’, ‘Feb’, ‘Mar’] %} {% for x in 0..12 %} { cycle(months, x) }} {% endfor %} Converts an argument to a date to allow date comparison. For example, <p>Choose your location before {{ 'next Monday'|date('M j, Y') }}</p> It will produce the following result − Choose your location before May 15, 2017 The argument must be in one of PHP’s supported date and time formats. You can pass a timezone as the second argument. The dump function dumps information about a template variable. For example, {{ dump(user) }} The max function returns the largest value of a sequence. For example, {{ max(1, 5, 9, 11, 15) }} The min function returns the smallest value of a sequence. For example, {{ min(1, 3, 2) }} The include function returns the rendered content of a template. For example, {{ include('template.html') }} The random function generates a random value. For example, {{ random([‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’]) }} {# example output: Jan #} Range function returns a list containing an arithmetic progression of integers. For example, {% for x in range(1, 5) %} {{ x }}, {% endfor %} It will produce the following result − 1,2,3,4,5 A Layout represents the common parts of multiple views, i.e. for example, page header, and footer. A template can be used by another one. We can achieve this using template inheritance concept. Template inheritance allows you to build a base “layout” template that contains all the common elements of web site defined as blocks. Let’s take a simple example to understand more about template inheritance. Consider the base template located at “app/Resources/views/base.html.twig”. Add the following changes in the file. base.html.twig <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>{% block title %}Parent template Layout{% endblock %}</title> </head> </html> Now move to the index template file located at “app/Resources/views/default/index.html.twig“. Add the following changes in it. index.html.twig {% extends 'base.html.twig' %} {% block title %}Child template Layout{% endblock %} Here, the {% extends %} tag informs the templating engine to first evaluate the base template, which sets up the layout and defines the block. The child template is then rendered. A child template can extend the base layout and override the title block. Now, request the url “http://localhost:8000” and you can obtain its result. The Asset manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files, and image files. To include JavaScript files, use the javascripts tag in any template. {# Include javascript #} {% block javascripts %} {% javascripts '@AppBundle/Resources/public/js/*' %} <script src="{{ asset_url }}"></script> {% endjavascripts %} {% endblock %} To include stylesheet files, use the stylesheets tag in any template {# include style sheet #} {% block stylesheets %} {% stylesheets 'bundles/app/css/*' filter = 'cssrewrite' %} <link rel = "stylesheet" href="{{ asset_url }}" /> {% endstylesheets %} {% endblock %} To include an image, you can use the image tag. It is defined as follows. {% image '@AppBundle/Resources/public/images/example.jpg' %} <img src = "{{ asset_url }}" alt = "Example" /> {% endimage %} You can combine many files into one. This helps to reduce the number of HTTP requests, and produces greater front-end performance. {% javascripts '@AppBundle/Resources/public/js/*' '@AcmeBarBundle/Resources/public/js/form.js' '@AcmeBarBundle/Resources/public/js/calendar.js' %} <script src = "{{ asset_url }}"></script> {% endjavascripts %} Print Add Notes Bookmark this page
[ { "code": null, "e": 2330, "s": 2203, "text": "A View Layer is the presentation layer of the MVC application. It separates the application logic from the presentation logic." }, { "code": null, "e": 2451, "s": 2330, "text": "When a controller needs to generate HTML, CSS, or any other content then, it forwards the task to the templating engine." }, { "code": null, "e": 2595, "s": 2451, "text": "Templates are basically text files used to generate any text-based documents such as HTML, XML, etc. It is used to save time and reduce errors." }, { "code": null, "e": 2657, "s": 2595, "text": "By default, templates can reside in two different locations −" }, { "code": null, "e": 2842, "s": 2657, "text": "app/Resources/views/ − The application's views directory can contain your application's layouts and templates of the application bundle. It also overrides third party bundle templates." }, { "code": null, "e": 2968, "s": 2842, "text": "vendor/path/to/Bundle/Resources/views/ − Each third party bundle contains its templates in it's “Resources/views/” directory." }, { "code": null, "e": 3233, "s": 2968, "text": "Symfony uses a powerful templating language called Twig. Twig allows you to write concise and readable templates in a very easy manner. Twig templates are simple and won't process PHP tags. Twig performs whitespace control, sandboxing, and automatic HTML escaping." }, { "code": null, "e": 3279, "s": 3233, "text": "Twig contains three types of special syntax −" }, { "code": null, "e": 3357, "s": 3279, "text": "{{ ... }} − Prints a variable or the result of an expression to the template." }, { "code": null, "e": 3435, "s": 3357, "text": "{{ ... }} − Prints a variable or the result of an expression to the template." }, { "code": null, "e": 3536, "s": 3435, "text": "{% ... %} − A tag that controls the logic of the template. It is mainly used to execute a function." }, { "code": null, "e": 3637, "s": 3536, "text": "{% ... %} − A tag that controls the logic of the template. It is mainly used to execute a function." }, { "code": null, "e": 3716, "s": 3637, "text": "{# ... #} − Comment syntax. It is used to add a single or multi-line comments." }, { "code": null, "e": 3795, "s": 3716, "text": "{# ... #} − Comment syntax. It is used to add a single or multi-line comments." }, { "code": null, "e": 3870, "s": 3795, "text": "The twig base template is located at “app/Resources/views/base.html.twig”." }, { "code": null, "e": 3924, "s": 3870, "text": "Let’s go through a simple example using twig engine. " }, { "code": null, "e": 4329, "s": 3924, "text": "<?php \nnamespace AppBundle\\Controller; \n\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Route; \nuse Symfony\\Component\\HttpFoundation\\Response; \nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller; \n\nclass StudentController extends Controller { \n /** \n * @Route(\"/student/home\") \n */ \n public function homeAction() { \n return $this->render('student/home.html.twig'); \n } \n}" }, { "code": null, "e": 4420, "s": 4329, "text": "Here, the render() method renders a template and puts that content into a Response object." }, { "code": null, "e": 4578, "s": 4420, "text": "Now move to the “views” directory and create a folder “student” and inside that folder create a file “home.html.twig”. Add the following changes in the file." }, { "code": null, "e": 4657, "s": 4578, "text": "//app/Resources/views/student/home.html.twig \n<h3>Student application!</h3> \n" }, { "code": null, "e": 4743, "s": 4657, "text": "You can obtain the result by requesting the url “http://localhost:8000/student/home”." }, { "code": null, "e": 4855, "s": 4743, "text": "By default, Twig comes with a long list of tags, filters, and functions. Let’s go through one by one in detail." }, { "code": null, "e": 4900, "s": 4855, "text": "Twig supports the following important tags −" }, { "code": null, "e": 5038, "s": 4900, "text": "The do tag performs similar functions as regular expression with the exception that it doesn't print anything. Its syntax is as follows −" }, { "code": null, "e": 5055, "s": 5038, "text": "{% do 5 + 6 %} \n" }, { "code": null, "e": 5198, "s": 5055, "text": "The include statement includes a template and returns the rendered content of that file into the current namespace. Its syntax is as follows −" }, { "code": null, "e": 5229, "s": 5198, "text": "{% include 'template.html' %}\n" }, { "code": null, "e": 5323, "s": 5229, "text": "The extends tag can be used to extend a template from another one. Its syntax is as follows −" }, { "code": null, "e": 5354, "s": 5323, "text": "{% extends \"template.html\" %}\n" }, { "code": null, "e": 5487, "s": 5354, "text": "Block acts as a placeholder and replaces the contents. Block names consists of alphanumeric characters and underscores. For example," }, { "code": null, "e": 5535, "s": 5487, "text": "<title>{% block title %}{% endblock %}</title>\n" }, { "code": null, "e": 5796, "s": 5535, "text": "The embed tag performs a combination of both include and extends. It allows you to include another template's contents. It also allows you to override any block defined inside the included template, such as when extending a template. Its syntax is as follows −" }, { "code": null, "e": 5967, "s": 5796, "text": "{% embed “new_template.twig” %} \n {# These blocks are defined in “new_template.twig\" #} \n {% block center %} \n Block content \n {% endblock %} \n{% endembed %} \n" }, { "code": null, "e": 6065, "s": 5967, "text": "Filter sections allow you to apply regular Twig filters on a block of template data. For example," }, { "code": null, "e": 6124, "s": 6065, "text": "{% filter upper %} \n symfony framework \n{% endfilter %} " }, { "code": null, "e": 6170, "s": 6124, "text": "Here, the text will be changed to upper case." }, { "code": null, "e": 6225, "s": 6170, "text": "For loop fetches each item in a sequence. For example," }, { "code": null, "e": 6272, "s": 6225, "text": "{% for x in 0..10 %} \n {{ x }} \n{% endfor %}" }, { "code": null, "e": 6372, "s": 6272, "text": "The if statement in Twig is similar to PHP. The expression evaluates to true or false. For example," }, { "code": null, "e": 6439, "s": 6372, "text": "{% if value == true %} \n <p>Simple If statement</p> \n{% endif %}" }, { "code": null, "e": 6557, "s": 6439, "text": "Twig contains filters. It is used to modify content before being rendered. Following are some of the notable filters." }, { "code": null, "e": 6634, "s": 6557, "text": "The length filter returns the length of a string. Its syntax is as follows −" }, { "code": null, "e": 6682, "s": 6634, "text": "{% if name|length > 5 %} \n ... \n{% endif %} \n" }, { "code": null, "e": 6743, "s": 6682, "text": "The lower filter converts a value to lowercase. For example," }, { "code": null, "e": 6765, "s": 6743, "text": "{{ 'SYMFONY'|lower }}" }, { "code": null, "e": 6805, "s": 6765, "text": "It would produce the following result −" }, { "code": null, "e": 6814, "s": 6805, "text": "symfony\n" }, { "code": null, "e": 6853, "s": 6814, "text": "Similarly, you can try for upper case." }, { "code": null, "e": 6939, "s": 6853, "text": "The replace filter formats a given string by replacing the placeholders. For example," }, { "code": null, "e": 7023, "s": 6939, "text": "{{ \"tutorials point site %si% and %te%.\"|replace({'%si%': web, '%te%': \"site\"}) }} " }, { "code": null, "e": 7062, "s": 7023, "text": "It will produce the following result −" }, { "code": null, "e": 7088, "s": 7062, "text": "tutorials point website \n" }, { "code": null, "e": 7160, "s": 7088, "text": "The title filter returns a titlecase version of the value. For example," }, { "code": null, "e": 7193, "s": 7160, "text": "{{ 'symfony framework '|title }}" }, { "code": null, "e": 7232, "s": 7193, "text": "It will produce the following result −" }, { "code": null, "e": 7252, "s": 7232, "text": " Symfony Framework\n" }, { "code": null, "e": 7311, "s": 7252, "text": "The sort filter sorts an array. Its syntax is as follows −" }, { "code": null, "e": 7363, "s": 7311, "text": "{% for user in names|sort %} \n ... \n{% endfor %}\n" }, { "code": null, "e": 7475, "s": 7363, "text": "The trim filter trims whitespace (or other characters) from the beginning and the end of a string. For example," }, { "code": null, "e": 7502, "s": 7475, "text": "{{ ' Symfony! '|trim }} " }, { "code": null, "e": 7541, "s": 7502, "text": "It will produce the following result −" }, { "code": null, "e": 7551, "s": 7541, "text": "Symfony!\n" }, { "code": null, "e": 7670, "s": 7551, "text": "Twig supports functions. It is used to obtain a particular result. Following are some of the important Twig functions." }, { "code": null, "e": 7779, "s": 7670, "text": "The attribute function can be used to access a “dynamic” attribute of a variable. Its syntax is as follows −" }, { "code": null, "e": 7887, "s": 7779, "text": "{{ attribute(object, method) }} \n{{ attribute(object, method, arguments) }} \n{{ attribute(array, item) }} \n" }, { "code": null, "e": 7900, "s": 7887, "text": "For example," }, { "code": null, "e": 7987, "s": 7900, "text": "{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}" }, { "code": null, "e": 8069, "s": 7987, "text": "Constant function returns the constant value for a specified string. For example," }, { "code": null, "e": 8123, "s": 8069, "text": "{{ constant('Namespace\\\\Classname::CONSTANT_NAME') }}" }, { "code": null, "e": 8185, "s": 8123, "text": "The cycle function cycles on an array of values. For example," }, { "code": null, "e": 8289, "s": 8185, "text": "{% set months = [‘Jan’, ‘Feb’, ‘Mar’] %} \n{% for x in 0..12 %} \n { cycle(months, x) }} \n{% endfor %}" }, { "code": null, "e": 8359, "s": 8289, "text": "Converts an argument to a date to allow date comparison. For example," }, { "code": null, "e": 8430, "s": 8359, "text": "<p>Choose your location before {{ 'next Monday'|date('M j, Y') }}</p> " }, { "code": null, "e": 8469, "s": 8430, "text": "It will produce the following result −" }, { "code": null, "e": 8511, "s": 8469, "text": "Choose your location before May 15, 2017\n" }, { "code": null, "e": 8581, "s": 8511, "text": "The argument must be in one of PHP’s supported date and time formats." }, { "code": null, "e": 8629, "s": 8581, "text": "You can pass a timezone as the second argument." }, { "code": null, "e": 8705, "s": 8629, "text": "The dump function dumps information about a template variable. For example," }, { "code": null, "e": 8722, "s": 8705, "text": "{{ dump(user) }}" }, { "code": null, "e": 8793, "s": 8722, "text": "The max function returns the largest value of a sequence. For example," }, { "code": null, "e": 8820, "s": 8793, "text": "{{ max(1, 5, 9, 11, 15) }}" }, { "code": null, "e": 8892, "s": 8820, "text": "The min function returns the smallest value of a sequence. For example," }, { "code": null, "e": 8911, "s": 8892, "text": "{{ min(1, 3, 2) }}" }, { "code": null, "e": 8989, "s": 8911, "text": "The include function returns the rendered content of a template. For example," }, { "code": null, "e": 9020, "s": 8989, "text": "{{ include('template.html') }}" }, { "code": null, "e": 9079, "s": 9020, "text": "The random function generates a random value. For example," }, { "code": null, "e": 9150, "s": 9079, "text": "{{ random([‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’]) }} \n{# example output: Jan #} " }, { "code": null, "e": 9243, "s": 9150, "text": "Range function returns a list containing an arithmetic progression of integers. For example," }, { "code": null, "e": 9298, "s": 9243, "text": "{% for x in range(1, 5) %} \n {{ x }}, \n{% endfor %} " }, { "code": null, "e": 9337, "s": 9298, "text": "It will produce the following result −" }, { "code": null, "e": 9348, "s": 9337, "text": "1,2,3,4,5\n" }, { "code": null, "e": 9447, "s": 9348, "text": "A Layout represents the common parts of multiple views, i.e. for example, page header, and footer." }, { "code": null, "e": 9677, "s": 9447, "text": "A template can be used by another one. We can achieve this using template inheritance concept. Template inheritance allows you to build a base “layout” template that contains all the common elements of web site defined as blocks." }, { "code": null, "e": 9752, "s": 9677, "text": "Let’s take a simple example to understand more about template inheritance." }, { "code": null, "e": 9867, "s": 9752, "text": "Consider the base template located at “app/Resources/views/base.html.twig”. Add the following changes in the file." }, { "code": null, "e": 9882, "s": 9867, "text": "base.html.twig" }, { "code": null, "e": 10046, "s": 9882, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset = \"UTF-8\"> \n <title>{% block title %}Parent template Layout{% endblock %}</title> \n </head> \n</html>" }, { "code": null, "e": 10173, "s": 10046, "text": "Now move to the index template file located at “app/Resources/views/default/index.html.twig“. Add the following changes in it." }, { "code": null, "e": 10189, "s": 10173, "text": "index.html.twig" }, { "code": null, "e": 10275, "s": 10189, "text": "{% extends 'base.html.twig' %} \n{% block title %}Child template Layout{% endblock %}" }, { "code": null, "e": 10605, "s": 10275, "text": "Here, the {% extends %} tag informs the templating engine to first evaluate the base template, which sets up the layout and defines the block. The child template is then rendered. A child template can extend the base layout and override the title block. Now, request the url “http://localhost:8000” and you can obtain its result." }, { "code": null, "e": 10727, "s": 10605, "text": "The Asset manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files, and image files." }, { "code": null, "e": 10797, "s": 10727, "text": "To include JavaScript files, use the javascripts tag in any template." }, { "code": null, "e": 10993, "s": 10797, "text": "{# Include javascript #} \n{% block javascripts %} \n {% javascripts '@AppBundle/Resources/public/js/*' %} \n <script src=\"{{ asset_url }}\"></script> \n {% endjavascripts %} \n{% endblock %} " }, { "code": null, "e": 11062, "s": 10993, "text": "To include stylesheet files, use the stylesheets tag in any template" }, { "code": null, "e": 11275, "s": 11062, "text": "{# include style sheet #} \n{% block stylesheets %} \n {% stylesheets 'bundles/app/css/*' filter = 'cssrewrite' %} \n <link rel = \"stylesheet\" href=\"{{ asset_url }}\" />\n {% endstylesheets %} \n{% endblock %}" }, { "code": null, "e": 11349, "s": 11275, "text": "To include an image, you can use the image tag. It is defined as follows." }, { "code": null, "e": 11480, "s": 11349, "text": "{% image '@AppBundle/Resources/public/images/example.jpg' %} \n <img src = \"{{ asset_url }}\" alt = \"Example\" /> \n{% endimage %} \n" }, { "code": null, "e": 11611, "s": 11480, "text": "You can combine many files into one. This helps to reduce the number of HTTP requests, and produces greater front-end performance." }, { "code": null, "e": 11838, "s": 11611, "text": "{% javascripts \n '@AppBundle/Resources/public/js/*' \n '@AcmeBarBundle/Resources/public/js/form.js' \n '@AcmeBarBundle/Resources/public/js/calendar.js' %} \n <script src = \"{{ asset_url }}\"></script> \n{% endjavascripts %}" }, { "code": null, "e": 11845, "s": 11838, "text": " Print" }, { "code": null, "e": 11856, "s": 11845, "text": " Add Notes" } ]
JSF - h:commandButton
The h:commandButton tag renders an HTML input element of the type "submit". <h:commandButton value = "Click Me!" onclick = "alert('Hello World!');" /> <input type = "submit" name = "j_idt10:j_idt13" value = "Click Me!" onclick = "alert('Hello World!');" /> id Identifier for a component rendered A boolean; false suppresses rendering value A component’s value, typically a value binding valueChangeListener A method binding to a method that responds to value changes coords Coordinates for an element whose shape is a rectangle, circle, or polygon dir Direction for text. Valid values are ltr (left to right) and rtl (right to left) disabled Disabled state of an input element or button tabindex Numerical value specifying a tab index target The name of a frame in which a document is opened title A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value width Width of an element onblur Element loses focus onchange Element’s value changes onclick Mouse button is clicked over the element ondblclick Mouse button is double-clicked over the element onfocus Element receives focus onkeydown Key is pressed onkeypress Key is pressed and subsequently released onkeyup Key is released onmousedown Mouse button is pressed over the element onmousemove Mouse moves over the element onmouseout Mouse leaves the element’s area onmouseover Mouse moves onto an element onmouseup Mouse button is released onreset Form is reset onselect Text is selected in an input field Let us create a test JSF application to test the above tag. <!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>h:commandButton example</h2> <hr /> <h:form> <h:commandButton value = "Click Me!" onclick = "alert('Hello World!');" /> </h:form> </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. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2028, "s": 1952, "text": "The h:commandButton tag renders an HTML input element of the type \"submit\"." }, { "code": null, "e": 2104, "s": 2028, "text": "<h:commandButton value = \"Click Me!\" onclick = \"alert('Hello World!');\" /> " }, { "code": null, "e": 2215, "s": 2104, "text": "<input type = \"submit\" name = \"j_idt10:j_idt13\" value = \"Click Me!\" \n onclick = \"alert('Hello World!');\" />\n" }, { "code": null, "e": 2218, "s": 2215, "text": "id" }, { "code": null, "e": 2245, "s": 2218, "text": "Identifier for a component" }, { "code": null, "e": 2254, "s": 2245, "text": "rendered" }, { "code": null, "e": 2292, "s": 2254, "text": "A boolean; false suppresses rendering" }, { "code": null, "e": 2298, "s": 2292, "text": "value" }, { "code": null, "e": 2345, "s": 2298, "text": "A component’s value, typically a value binding" }, { "code": null, "e": 2365, "s": 2345, "text": "valueChangeListener" }, { "code": null, "e": 2425, "s": 2365, "text": "A method binding to a method that responds to value changes" }, { "code": null, "e": 2432, "s": 2425, "text": "coords" }, { "code": null, "e": 2506, "s": 2432, "text": "Coordinates for an element whose shape is a rectangle, circle, or polygon" }, { "code": null, "e": 2510, "s": 2506, "text": "dir" }, { "code": null, "e": 2591, "s": 2510, "text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)" }, { "code": null, "e": 2600, "s": 2591, "text": "disabled" }, { "code": null, "e": 2645, "s": 2600, "text": "Disabled state of an input element or button" }, { "code": null, "e": 2654, "s": 2645, "text": "tabindex" }, { "code": null, "e": 2693, "s": 2654, "text": "Numerical value specifying a tab index" }, { "code": null, "e": 2700, "s": 2693, "text": "target" }, { "code": null, "e": 2750, "s": 2700, "text": "The name of a frame in which a document is opened" }, { "code": null, "e": 2756, "s": 2750, "text": "title" }, { "code": null, "e": 2880, "s": 2756, "text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value" }, { "code": null, "e": 2886, "s": 2880, "text": "width" }, { "code": null, "e": 2906, "s": 2886, "text": "Width of an element" }, { "code": null, "e": 2913, "s": 2906, "text": "onblur" }, { "code": null, "e": 2933, "s": 2913, "text": "Element loses focus" }, { "code": null, "e": 2942, "s": 2933, "text": "onchange" }, { "code": null, "e": 2966, "s": 2942, "text": "Element’s value changes" }, { "code": null, "e": 2974, "s": 2966, "text": "onclick" }, { "code": null, "e": 3015, "s": 2974, "text": "Mouse button is clicked over the element" }, { "code": null, "e": 3026, "s": 3015, "text": "ondblclick" }, { "code": null, "e": 3074, "s": 3026, "text": "Mouse button is double-clicked over the element" }, { "code": null, "e": 3082, "s": 3074, "text": "onfocus" }, { "code": null, "e": 3105, "s": 3082, "text": "Element receives focus" }, { "code": null, "e": 3115, "s": 3105, "text": "onkeydown" }, { "code": null, "e": 3130, "s": 3115, "text": "Key is pressed" }, { "code": null, "e": 3141, "s": 3130, "text": "onkeypress" }, { "code": null, "e": 3182, "s": 3141, "text": "Key is pressed and subsequently released" }, { "code": null, "e": 3190, "s": 3182, "text": "onkeyup" }, { "code": null, "e": 3206, "s": 3190, "text": "Key is released" }, { "code": null, "e": 3218, "s": 3206, "text": "onmousedown" }, { "code": null, "e": 3259, "s": 3218, "text": "Mouse button is pressed over the element" }, { "code": null, "e": 3271, "s": 3259, "text": "onmousemove" }, { "code": null, "e": 3300, "s": 3271, "text": "Mouse moves over the element" }, { "code": null, "e": 3311, "s": 3300, "text": "onmouseout" }, { "code": null, "e": 3343, "s": 3311, "text": "Mouse leaves the element’s area" }, { "code": null, "e": 3355, "s": 3343, "text": "onmouseover" }, { "code": null, "e": 3383, "s": 3355, "text": "Mouse moves onto an element" }, { "code": null, "e": 3393, "s": 3383, "text": "onmouseup" }, { "code": null, "e": 3418, "s": 3393, "text": "Mouse button is released" }, { "code": null, "e": 3426, "s": 3418, "text": "onreset" }, { "code": null, "e": 3440, "s": 3426, "text": "Form is reset" }, { "code": null, "e": 3449, "s": 3440, "text": "onselect" }, { "code": null, "e": 3485, "s": 3449, "text": "Text is selected in an input field " }, { "code": null, "e": 3545, "s": 3485, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 3980, "s": 3545, "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>h:commandButton example</h2>\n <hr />\n \n <h:form>\n <h:commandButton value = \"Click Me!\" onclick = \"alert('Hello World!');\" />\n </h:form>\n </body>\n</html>" }, { "code": null, "e": 4196, "s": 3980, "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": 4231, "s": 4196, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4246, "s": 4231, "text": " Chaand Sheikh" }, { "code": null, "e": 4253, "s": 4246, "text": " Print" }, { "code": null, "e": 4264, "s": 4253, "text": " Add Notes" } ]
Building an End-To-End Data Science Project | by George Liu | Towards Data Science
It is often said that the majority of a Data Scientist’s work is not the actual analysis and modeling, but rather the data wrangling and cleaning part. As a result, full-cycle data science projects that involve these stages will be more valuable since they prove the author’s abilities to work independently with real data, as opposed to a given cleaned dataset. Fully understanding the value of an end-to-end data science project, I always wanted to build one but not able to, until now :) I have recently finished my Ideal Profiles project. Since it’s a major project that involves many moving parts, I want to document the process and the lessons learned, which is a further learning opportunity (inspired by William Koehrsen’s great post on the value of data science writing). In my opinion, a full-cycle data science project should include the following stages: The biggest counter-argument for working on a Kaggle project is often that it’s only focused on the second stage. Therefore, in this project, I made sure that all three stages are covered. For the first stage, I did web scraping to get the data and since the data was dirty, I had to wrangle to make the data ready for analysis. Then I made various data visualizations and performed analyses as stage two. Lastly, I wrote posts to communicate findings and launch this project into production. Of course, I could have made this project even more complete by including a machine learning component, e.g. using NLP to classify job postings based on contents, but that will delay the project completion time significantly which brings us to the next point: Potentially, there can be an unlimited number of things to work on for a given project, but in reality, we only have limited time. To coordinate these two competing factors, we need to be disciplined. For me, “iterative thinking” really helped — look, Rome wasn’t built in a day, so let’s build something that works and ship it first, and then we can always come back to improve with more features. On the other hand, this also means we need to be able to deal with “non-perfectness” and not get fixated on details. With this philosophy in mind, I was able to delay some very tempting features and put them in the To-do’s section of the project doc. One of them was to use a larger dataset by scraping data from Indeed USA instead of the Canadian site. Given the end-to-end nature of the project, there were many different aspects to work on — web scraping, data preprocessing, plotting...If we put all codes in one Jupyter Notebook, it’ll be too long and too complex to manage. I then decided to use Python scripts combined with a central Jupyter Notebook to solve this problem. I divided supporting functions into three big categories and housed them in three corresponding scripts: scrape_data.py — containing functions needed for web scraping such as “get_soup()” and “get_urls()” process_text.py — containing text processing and cleaning functions such as “tokenize_text()” and “check_freq()” helper.py — containing file I/O and plotting functions, e.g. “plot_skill()” This way, I was able to maintain a super light and organized central Notebook. Functions are then imported and called from the Notebook as needed like this: from scrape_data import *from process_text import *from helper import * As many of the scraping scripts I found online didn’t work, I was determined to make sure that my project is reproducible. Aside from solid code, a robust README document and a complete environment dependency file were also part of the solution. README.md — I made painstaking efforts to make sure all relevant details are captured, particularly, how to set up the environment and how to use the scripts. env_ideal_profiles.yaml — by freezing all dependencies into this file, I made sure the user can exactly re-create the same Anaconda Python environment I used. More info is available here. Good coding practice does matter! In particular, I found the following practices incredibly useful in coding larger and more complex projects: Write clear, concise and informative comments Have meaningful and descriptive variable/function names Provide detailed and structured docstrings Ensure exception handling using Python “try except” block These things may seem trivial when you have a project that is a 30-line Jupyter Notebook, but can really be critical when dealing with a major project that needs hundreds of lines of code! I used to feel comfortable with just basic Matplotlib skills. However, for this project, I not only needed to combine several plots into one but also had to do detailed customization such as rotating axis tick labels...at that point, basic Matplotlib skills simply won’t suffice anymore. It actually turned out to be a great opportunity to learn Matplotlib. Once I learned what it can do, I found it impossible to look back, simply because, Matplotlib is really powerful! Its object-oriented approach allows you to modify almost anything...Check out the below tutorials to find out: Matplotlib Tutorial: Python Plotting Effectively Using Matplotlib Python Plotting With Matplotlib (Guide) That’s all, the final blog post about the Ideal Profiles project I recently completed. You can find the other two articles here and here. What’s your thought? Anything I missed or I could improve on? Please feel free to comment below. I welcome any feedback. Thank you for reading!
[ { "code": null, "e": 534, "s": 171, "text": "It is often said that the majority of a Data Scientist’s work is not the actual analysis and modeling, but rather the data wrangling and cleaning part. As a result, full-cycle data science projects that involve these stages will be more valuable since they prove the author’s abilities to work independently with real data, as opposed to a given cleaned dataset." }, { "code": null, "e": 662, "s": 534, "text": "Fully understanding the value of an end-to-end data science project, I always wanted to build one but not able to, until now :)" }, { "code": null, "e": 952, "s": 662, "text": "I have recently finished my Ideal Profiles project. Since it’s a major project that involves many moving parts, I want to document the process and the lessons learned, which is a further learning opportunity (inspired by William Koehrsen’s great post on the value of data science writing)." }, { "code": null, "e": 1038, "s": 952, "text": "In my opinion, a full-cycle data science project should include the following stages:" }, { "code": null, "e": 1227, "s": 1038, "text": "The biggest counter-argument for working on a Kaggle project is often that it’s only focused on the second stage. Therefore, in this project, I made sure that all three stages are covered." }, { "code": null, "e": 1531, "s": 1227, "text": "For the first stage, I did web scraping to get the data and since the data was dirty, I had to wrangle to make the data ready for analysis. Then I made various data visualizations and performed analyses as stage two. Lastly, I wrote posts to communicate findings and launch this project into production." }, { "code": null, "e": 1791, "s": 1531, "text": "Of course, I could have made this project even more complete by including a machine learning component, e.g. using NLP to classify job postings based on contents, but that will delay the project completion time significantly which brings us to the next point:" }, { "code": null, "e": 1992, "s": 1791, "text": "Potentially, there can be an unlimited number of things to work on for a given project, but in reality, we only have limited time. To coordinate these two competing factors, we need to be disciplined." }, { "code": null, "e": 2307, "s": 1992, "text": "For me, “iterative thinking” really helped — look, Rome wasn’t built in a day, so let’s build something that works and ship it first, and then we can always come back to improve with more features. On the other hand, this also means we need to be able to deal with “non-perfectness” and not get fixated on details." }, { "code": null, "e": 2544, "s": 2307, "text": "With this philosophy in mind, I was able to delay some very tempting features and put them in the To-do’s section of the project doc. One of them was to use a larger dataset by scraping data from Indeed USA instead of the Canadian site." }, { "code": null, "e": 2871, "s": 2544, "text": "Given the end-to-end nature of the project, there were many different aspects to work on — web scraping, data preprocessing, plotting...If we put all codes in one Jupyter Notebook, it’ll be too long and too complex to manage. I then decided to use Python scripts combined with a central Jupyter Notebook to solve this problem." }, { "code": null, "e": 2976, "s": 2871, "text": "I divided supporting functions into three big categories and housed them in three corresponding scripts:" }, { "code": null, "e": 3076, "s": 2976, "text": "scrape_data.py — containing functions needed for web scraping such as “get_soup()” and “get_urls()”" }, { "code": null, "e": 3189, "s": 3076, "text": "process_text.py — containing text processing and cleaning functions such as “tokenize_text()” and “check_freq()”" }, { "code": null, "e": 3265, "s": 3189, "text": "helper.py — containing file I/O and plotting functions, e.g. “plot_skill()”" }, { "code": null, "e": 3422, "s": 3265, "text": "This way, I was able to maintain a super light and organized central Notebook. Functions are then imported and called from the Notebook as needed like this:" }, { "code": null, "e": 3494, "s": 3422, "text": "from scrape_data import *from process_text import *from helper import *" }, { "code": null, "e": 3740, "s": 3494, "text": "As many of the scraping scripts I found online didn’t work, I was determined to make sure that my project is reproducible. Aside from solid code, a robust README document and a complete environment dependency file were also part of the solution." }, { "code": null, "e": 3899, "s": 3740, "text": "README.md — I made painstaking efforts to make sure all relevant details are captured, particularly, how to set up the environment and how to use the scripts." }, { "code": null, "e": 4087, "s": 3899, "text": "env_ideal_profiles.yaml — by freezing all dependencies into this file, I made sure the user can exactly re-create the same Anaconda Python environment I used. More info is available here." }, { "code": null, "e": 4230, "s": 4087, "text": "Good coding practice does matter! In particular, I found the following practices incredibly useful in coding larger and more complex projects:" }, { "code": null, "e": 4276, "s": 4230, "text": "Write clear, concise and informative comments" }, { "code": null, "e": 4332, "s": 4276, "text": "Have meaningful and descriptive variable/function names" }, { "code": null, "e": 4375, "s": 4332, "text": "Provide detailed and structured docstrings" }, { "code": null, "e": 4433, "s": 4375, "text": "Ensure exception handling using Python “try except” block" }, { "code": null, "e": 4622, "s": 4433, "text": "These things may seem trivial when you have a project that is a 30-line Jupyter Notebook, but can really be critical when dealing with a major project that needs hundreds of lines of code!" }, { "code": null, "e": 4910, "s": 4622, "text": "I used to feel comfortable with just basic Matplotlib skills. However, for this project, I not only needed to combine several plots into one but also had to do detailed customization such as rotating axis tick labels...at that point, basic Matplotlib skills simply won’t suffice anymore." }, { "code": null, "e": 5205, "s": 4910, "text": "It actually turned out to be a great opportunity to learn Matplotlib. Once I learned what it can do, I found it impossible to look back, simply because, Matplotlib is really powerful! Its object-oriented approach allows you to modify almost anything...Check out the below tutorials to find out:" }, { "code": null, "e": 5242, "s": 5205, "text": "Matplotlib Tutorial: Python Plotting" }, { "code": null, "e": 5271, "s": 5242, "text": "Effectively Using Matplotlib" }, { "code": null, "e": 5311, "s": 5271, "text": "Python Plotting With Matplotlib (Guide)" }, { "code": null, "e": 5449, "s": 5311, "text": "That’s all, the final blog post about the Ideal Profiles project I recently completed. You can find the other two articles here and here." }, { "code": null, "e": 5570, "s": 5449, "text": "What’s your thought? Anything I missed or I could improve on? Please feel free to comment below. I welcome any feedback." } ]
Java Program for Maximum Product Subarray - GeeksforGeeks
21 Dec, 2021 Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used. Examples: Input: arr[] = {6, -3, -10, 0, 2} Output: 180 // The subarray is {6, -3, -10} Input: arr[] = {-1, -3, -10, 0, 60} Output: 60 // The subarray is {60} Input: arr[] = {-2, -40, 0, -2, -3} Output: 80 // The subarray is {-2, -40} Naive Solution: The idea is to traverse over every contiguous subarrays, find the product of each of these subarrays and return the maximum product from these results. Below is the implementation of the above approach. Java // Java program to find maximum product subarrayimport java.io.*; class GFG { /* Returns the product of max product subarray.*/ static int maxSubarrayProduct(int arr[]) { // Initializing result int result = arr[0]; int n = arr.length; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the // maximum product result = Math.max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = Math.max(result, mul); } return result; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println("Maximum Sub array product is " + maxSubarrayProduct(arr)); }} // This code is contributed by yashbeersingh42 Output: Maximum Sub array product is 112 Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Solution: The following solution assumes that the given input array always has a positive output. The solution works for all cases mentioned above. It doesn’t work for arrays like {0, 0, -20, 0}, {0, 0, 0}.. etc. The solution can be easily modified to handle this case. It is similar to Largest Sum Contiguous Subarray problem. The only thing to note here is, maximum product can also be obtained by minimum (negative) product ending with the previous element multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2}, when we are at element -2, the maximum product is multiplication of, minimum product ending with -6 and -2. Java // Java program to find maximum product subarrayimport java.io.*; class ProductSubarray { // Utility functions to get // minimum of two integers static int min(int x, int y) { return x < y ? x : y; } // Utility functions to get // maximum of two integers static int max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int arr[]) { int n = arr.length; // max positive product // ending at the current // position int max_ending_here = 1; // min negative product // ending at the current // position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the ith iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending _here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println("Maximum Sub array product is " + maxSubarrayProduct(arr)); }} /*This code is contributed by Devesh Agrawal*/ Maximum Sub array product is 112 Time Complexity: O(n) Auxiliary Space: O(1) Please refer complete article on Maximum Product Subarray for more details! Amazon Microsoft Morgan Stanley Myntra Myntra-Question Arrays Java Java Programs Morgan Stanley Amazon Microsoft Myntra Arrays Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Trapping Rain Water Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space Window Sliding Technique Split() String method in Java with examples For-each loop in Java Reverse a string in Java HashMap in Java with Examples Interfaces in Java
[ { "code": null, "e": 24405, "s": 24377, "text": "\n21 Dec, 2021" }, { "code": null, "e": 24593, "s": 24405, "text": "Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used." }, { "code": null, "e": 24603, "s": 24593, "text": "Examples:" }, { "code": null, "e": 24839, "s": 24603, "text": "Input: arr[] = {6, -3, -10, 0, 2}\nOutput: 180 // The subarray is {6, -3, -10}\n\nInput: arr[] = {-1, -3, -10, 0, 60}\nOutput: 60 // The subarray is {60}\n\nInput: arr[] = {-2, -40, 0, -2, -3}\nOutput: 80 // The subarray is {-2, -40}" }, { "code": null, "e": 24855, "s": 24839, "text": "Naive Solution:" }, { "code": null, "e": 25007, "s": 24855, "text": "The idea is to traverse over every contiguous subarrays, find the product of each of these subarrays and return the maximum product from these results." }, { "code": null, "e": 25058, "s": 25007, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 25063, "s": 25058, "text": "Java" }, { "code": "// Java program to find maximum product subarrayimport java.io.*; class GFG { /* Returns the product of max product subarray.*/ static int maxSubarrayProduct(int arr[]) { // Initializing result int result = arr[0]; int n = arr.length; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the // maximum product result = Math.max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = Math.max(result, mul); } return result; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println(\"Maximum Sub array product is \" + maxSubarrayProduct(arr)); }} // This code is contributed by yashbeersingh42", "e": 26129, "s": 25063, "text": null }, { "code": null, "e": 26137, "s": 26129, "text": "Output:" }, { "code": null, "e": 26170, "s": 26137, "text": "Maximum Sub array product is 112" }, { "code": null, "e": 26214, "s": 26170, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 26234, "s": 26214, "text": "Efficient Solution:" }, { "code": null, "e": 26868, "s": 26234, "text": "The following solution assumes that the given input array always has a positive output. The solution works for all cases mentioned above. It doesn’t work for arrays like {0, 0, -20, 0}, {0, 0, 0}.. etc. The solution can be easily modified to handle this case. It is similar to Largest Sum Contiguous Subarray problem. The only thing to note here is, maximum product can also be obtained by minimum (negative) product ending with the previous element multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2}, when we are at element -2, the maximum product is multiplication of, minimum product ending with -6 and -2. " }, { "code": null, "e": 26873, "s": 26868, "text": "Java" }, { "code": "// Java program to find maximum product subarrayimport java.io.*; class ProductSubarray { // Utility functions to get // minimum of two integers static int min(int x, int y) { return x < y ? x : y; } // Utility functions to get // maximum of two integers static int max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int arr[]) { int n = arr.length; // max positive product // ending at the current // position int max_ending_here = 1; // min negative product // ending at the current // position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the ith iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending _here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println(\"Maximum Sub array product is \" + maxSubarrayProduct(arr)); }} /*This code is contributed by Devesh Agrawal*/", "e": 30034, "s": 26873, "text": null }, { "code": null, "e": 30067, "s": 30034, "text": "Maximum Sub array product is 112" }, { "code": null, "e": 30111, "s": 30067, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 30187, "s": 30111, "text": "Please refer complete article on Maximum Product Subarray for more details!" }, { "code": null, "e": 30194, "s": 30187, "text": "Amazon" }, { "code": null, "e": 30204, "s": 30194, "text": "Microsoft" }, { "code": null, "e": 30219, "s": 30204, "text": "Morgan Stanley" }, { "code": null, "e": 30226, "s": 30219, "text": "Myntra" }, { "code": null, "e": 30242, "s": 30226, "text": "Myntra-Question" }, { "code": null, "e": 30249, "s": 30242, "text": "Arrays" }, { "code": null, "e": 30254, "s": 30249, "text": "Java" }, { "code": null, "e": 30268, "s": 30254, "text": "Java Programs" }, { "code": null, "e": 30283, "s": 30268, "text": "Morgan Stanley" }, { "code": null, "e": 30290, "s": 30283, "text": "Amazon" }, { "code": null, "e": 30300, "s": 30290, "text": "Microsoft" }, { "code": null, "e": 30307, "s": 30300, "text": "Myntra" }, { "code": null, "e": 30314, "s": 30307, "text": "Arrays" }, { "code": null, "e": 30319, "s": 30314, "text": "Java" }, { "code": null, "e": 30417, "s": 30319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30426, "s": 30417, "text": "Comments" }, { "code": null, "e": 30439, "s": 30426, "text": "Old Comments" }, { "code": null, "e": 30488, "s": 30439, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30508, "s": 30488, "text": "Trapping Rain Water" }, { "code": null, "e": 30546, "s": 30508, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30631, "s": 30546, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 30656, "s": 30631, "text": "Window Sliding Technique" }, { "code": null, "e": 30700, "s": 30656, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30722, "s": 30700, "text": "For-each loop in Java" }, { "code": null, "e": 30747, "s": 30722, "text": "Reverse a string in Java" }, { "code": null, "e": 30777, "s": 30747, "text": "HashMap in Java with Examples" } ]
Histograms with Python’s Matplotlib | by Thiago Carvalho | Towards Data Science
Karl Pearson coined the term histogram, but it’s hard to tell who invented the visualization, and it’s most likely that it was used way before Pearson named it. William Playfair is considered the inventor of bar charts or the first to publish such graphs, so it’s not hard to imagine that he would have drawn a couple of those charts to visualize a frequency in the late 1700s or early 1800s. After all, that’s pretty much what histograms are; they’re bar charts, usually visualized with the bars connected, where the values are separated into equal ranges, called bins or classes. The heights of the bars represent the number of records in that class, also known as frequency. In this article, I’ll go through the basics of this visualization, and we’ll also explore some of Matplotlib’s many customization options while we learn more about histograms. I’ll run my code in Jupyter, using Pandas, Numpy, and Matplotlib to develop the visuals. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import AutoMinorLocatorfrom matplotlib import gridspec In this example, the dataset we’ll explore has data on all space missions since 1957 and was scraped from nextspaceflight.com by Agirlcoding. df = pd.read_csv('medium/data/Space_Corrected.csv')df After loading the dataset, we can proceed to some cleaning and minor adjustments. # date column to datetimedf['Datum'] = pd.to_datetime(df['Datum'], utc=True)# costs column to numericdf['Rocket'] = pd.to_numeric(df[' Rocket'], errors='coerce')# drop columns# ' Rocket' had an extra space and was renameddf.drop([' Rocket', 'Unnamed: 0', 'Unnamed: 0.1'], axis=1, inplace=True) Now that’s all set, we can effortlessly plot our histogram with Matplotlib. Mostly I want to visualize the data on the ‘Rocket’ column, which is the cost of the mission in millions of USD. My idea is to observe the distribution of values in that column. plt.hist(df.Rocket)plt.show() That’s ok, the default chart gives us a simple x-axis and y-axis, and the bars are automatically divided into bins. Before going any further, let’s assign the bins of our histogram to a variable to get a better look at it. n, bins, patches = plt.hist(df.Rocket)bins That means our values are divided into ten bins, like so: 5.3 ≤ n < 49.77 49.77 ≤ n < 94.24 ... 405.53 ≤ n ≤ 450 Note that the top value of each bin is excluded (<), but the last range includes it (≤). Cool, now that we have a list with the edges of our bins, let’s try using it as the ticks for the x-axis. Let’s also add a figure and increase the size of our graph. fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)plt.xticks(bins)plt.show() That’s better. Since we didn’t give Matplotlib any information about the bins, it automatically defined its numbers and ranges. We can set the bins by passing a list of edges when defining the plot; this allows us to create unevenly spaced bins, which is not typically recommended — but there’s that. Another way we can set them is using an integer with the number of bins we want. fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket, bins=16)plt.xticks(bins)plt.show() The main point of a histogram is to visualize the distribution of our data. We don’t want our chart to have too many bins because that could hide the concentrations in our data; simultaneously, we don’t want a low number of classes because we could misinterpret the distribution. Choosing the number of classes in our histogram is sometimes very intuitive, but other times is quite a struggle. Luckily, we got plenty of algorithms for that, and Matplotlib allows us to chose which one to use. fig = plt.figure(figsize=(16,6))# 'auto', 'sturges', 'fd', 'doane', 'scott', 'rice' or 'sqrt'n, bins, patches = plt.hist(df.Rocket, bins='rice')plt.xticks(bins)plt.show() Quite simply, we already know the basics of how a histogram works. Now we can try to customize it. We could use some gridlines in the x-axis to better visualize where the bins start and end. A title would also be great. fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)plt.xticks(bins)plt.grid(color='white', lw = 0.5, axis='x')plt.title('Histogram of Space Missions Costs', loc = 'left', fontsize = 18)plt.show() It would be better if the ticks were in the center of the bars and displayed both the lower and upper boundaries of the range. We could define the labels by going through all the bins but the last while joining the current value with the next one. Something like this: # x ticks labels[ "{:.2f} - {:.2f}".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])] And the ticks positions should be at the center of the two values, as so: # x ticks positions[(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])] Cool, when we add this to our plot, we need to redefine the grids. If we draw the grid lines with the ticks, we’ll have the line in the middle of the bar. To fix that, we’ll use AutoMinorLocator, the class we imported at the beginning. That class will help us set the minor ticks, which we can use to draw the grid. fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)# define minor ticks and draw a grid with themminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color='white', lw = 0.5)# x ticksxticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ "{:.2f}\nto\n{:.2f}".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels = xticks_labels)plt.title('Histogram of Space Missions Costs (Millions of USD)', loc = 'left', fontsize = 18) It’s starting to look great; let’s remove the spines of our chart and the markings of the ticks to make it look cleaner. fig, ax = plt.subplots(1, figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)# define minor ticks and draw a grid with themminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color='white', lw = 0.5)# x ticksxticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ "{:.2f}\nto\n{:.2f}".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels = xticks_labels)# remove major and minor ticks from the x axis, but keep the labelsax.tick_params(axis='x', which='both',length=0)# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('Histogram of Space Missions Costs (Millions of USD)', loc = 'left', fontsize = 18) For the y-axis, we could print the values on top of the bars and remove the y ticks. n the first variable we get from plotting our histograms holds a list with the counts for each bin. We can get the x positions for xticks from the list we built earlier and the labels and y values from n. fig, ax = plt.subplots(1, figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)# define minor ticks and draw a grid with themminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color='white', lw = 0.5)# x ticksxticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ "{:.2f}\nto\n{:.2f}".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels = xticks_labels)ax.tick_params(axis='x', which='both',length=0)# remove y ticksplt.yticks([])# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)# plot values on top of barsfor idx, value in enumerate(n): if value > 0: plt.text(xticks[idx], value+5, int(value), ha='center')plt.title('Histogram of Space Missions Costs (Millions of USD)', loc = 'left', fontsize = 18)plt.show() Awesome! The elements are in place; all that’s left to do is change the colors, font sizes, add some labels on the x and y-axis, and customize the chart as desired. facecolor = '#EAEAEA'color_bars = '#3475D0'txt_color1 = '#252525'txt_color2 = '#004C74'fig, ax = plt.subplots(1, figsize=(20,6), facecolor=facecolor)ax.set_facecolor(facecolor)n, bins, patches = plt.hist(df.Rocket, color=color_bars, bins='doane')#gridminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color=facecolor, lw = 0.5)xticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ "{:.0f}-{:.0f}".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels=xticks_labels, c=txt_color1, fontsize=13)# remove major and minor ticks from the x axis, but keep the labelsax.tick_params(axis='x', which='both',length=0)# remove y ticksplt.yticks([])# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)for idx, value in enumerate(n): if value > 0: plt.text(xticks[idx], value+5, int(value), ha='center', fontsize=16, c=txt_color1)plt.title('Histogram of Space Missions Costs\n', loc = 'left', fontsize = 20, c=txt_color1)plt.xlabel('\nMillions of USD', c=txt_color2, fontsize=14)plt.ylabel('Number of Space Missions', c=txt_color2, fontsize=14)plt.tight_layout()plt.savefig('costs.png', facecolor=facecolor) Great! We got a numerical field and described its distribution with a beautiful chart. Now let’s have a look at how to handle dates in histograms. To figure out the bins on this one, we can start by looking at the earliest and latest date in our data. We can easily select the bins for numerical fields with the many different algorithms that Matplotlib supports, but those techniques may not yield the best results when dealing with dates. Don’t get me wrong, as much as you can find that the optimal size of bin to describe the distribution of your variable is 378 days, using a whole year is way more understandable. Alright, so let’s convert our date-time objects to a number format that Matplotlib can handle, then we’ll adjust our ticks and see how it looks. import matplotlib.dates as mdates# convert the date format to matplotlib date format plt_date = mdates.date2num(df['Datum'])bins = mdates.datestr2num(["{}/01/01".format(i) for i in np.arange(1957, 2022)])# plot itfig, ax = plt.subplots(1, figsize=(22,6))n, bins, patches = plt.hist(plt_date, bins=bins)# x ticks and limitax.xaxis.set_major_locator(mdates.YearLocator())ax.xaxis.set_major_formatter(mdates.DateFormatter('%y'))plt.xlim(mdates.datestr2num(['1957/01/01','2021/12/31']))plt.show() That’s very interesting. We can see the space race taking shape from 57 to the late ’70s and a more recent increase in space programs in the last five years. Now we can adapt our previous design to our new histogram. facecolor = '#EAEAEA'color_bars = '#3475D0'txt_color1 = '#252525'txt_color2 = '#004C74'# convert the date format to matplotlib date format plt_date = mdates.date2num(df['Datum'])bins = mdates.datestr2num(["{}/01/01".format(i) for i in np.arange(1957, 2022)])# plot itfig, ax = plt.subplots(1, figsize=(22,8), facecolor=facecolor)ax.set_facecolor(facecolor)n, bins, patches = plt.hist(plt_date, bins=bins, color=color_bars)ax.xaxis.set_major_locator(mdates.YearLocator())ax.xaxis.set_major_formatter(mdates.DateFormatter('%y'))plt.xlim(mdates.datestr2num(['1957/01/01','2021/12/31']))#gridplt.grid(axis='y', color=color_bars, lw = 0.5, alpha=0.7)plt.grid(axis='x', color=facecolor, lw = 0.5)#remove major and minor ticks from the x axis, but keep the labelsax.tick_params(axis='both', which='both',length=0)# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)ax.spines['left'].set_position(('outward', 10))plt.xticks(c=txt_color1, fontsize=12)plt.yticks(c=txt_color1, fontsize=12)plt.title('Histogram of Space Missions Dates\n', loc = 'left', fontsize = 20, c=txt_color1)plt.xlabel('\nYear', c=txt_color2, fontsize=14)plt.ylabel('Number of Space Missions', c=txt_color2, fontsize=14)plt.tight_layout()plt.savefig('hist.png', facecolor=facecolor) And that’s it! We built two histograms, got a look at the different ways we have to define the bins and classes, changed lots of visual elements to make our chart look just like we wanted to, explored date formats, major and minor ticks, grid lines, and texts. Thanks for reading my article. I hope you enjoyed it. You can find more tutorials about Python and Matplotlib here. Resources:Data;Code (GitHub);Matplotlib .hist;Matplotlib Dates;Matplotlib Tick Formatters;Matplotlib Date Tick Labels — Example;History of Histograms;
[ { "code": null, "e": 333, "s": 172, "text": "Karl Pearson coined the term histogram, but it’s hard to tell who invented the visualization, and it’s most likely that it was used way before Pearson named it." }, { "code": null, "e": 565, "s": 333, "text": "William Playfair is considered the inventor of bar charts or the first to publish such graphs, so it’s not hard to imagine that he would have drawn a couple of those charts to visualize a frequency in the late 1700s or early 1800s." }, { "code": null, "e": 850, "s": 565, "text": "After all, that’s pretty much what histograms are; they’re bar charts, usually visualized with the bars connected, where the values are separated into equal ranges, called bins or classes. The heights of the bars represent the number of records in that class, also known as frequency." }, { "code": null, "e": 1026, "s": 850, "text": "In this article, I’ll go through the basics of this visualization, and we’ll also explore some of Matplotlib’s many customization options while we learn more about histograms." }, { "code": null, "e": 1115, "s": 1026, "text": "I’ll run my code in Jupyter, using Pandas, Numpy, and Matplotlib to develop the visuals." }, { "code": null, "e": 1261, "s": 1115, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import AutoMinorLocatorfrom matplotlib import gridspec" }, { "code": null, "e": 1403, "s": 1261, "text": "In this example, the dataset we’ll explore has data on all space missions since 1957 and was scraped from nextspaceflight.com by Agirlcoding." }, { "code": null, "e": 1457, "s": 1403, "text": "df = pd.read_csv('medium/data/Space_Corrected.csv')df" }, { "code": null, "e": 1539, "s": 1457, "text": "After loading the dataset, we can proceed to some cleaning and minor adjustments." }, { "code": null, "e": 1833, "s": 1539, "text": "# date column to datetimedf['Datum'] = pd.to_datetime(df['Datum'], utc=True)# costs column to numericdf['Rocket'] = pd.to_numeric(df[' Rocket'], errors='coerce')# drop columns# ' Rocket' had an extra space and was renameddf.drop([' Rocket', 'Unnamed: 0', 'Unnamed: 0.1'], axis=1, inplace=True)" }, { "code": null, "e": 1909, "s": 1833, "text": "Now that’s all set, we can effortlessly plot our histogram with Matplotlib." }, { "code": null, "e": 2087, "s": 1909, "text": "Mostly I want to visualize the data on the ‘Rocket’ column, which is the cost of the mission in millions of USD. My idea is to observe the distribution of values in that column." }, { "code": null, "e": 2117, "s": 2087, "text": "plt.hist(df.Rocket)plt.show()" }, { "code": null, "e": 2233, "s": 2117, "text": "That’s ok, the default chart gives us a simple x-axis and y-axis, and the bars are automatically divided into bins." }, { "code": null, "e": 2340, "s": 2233, "text": "Before going any further, let’s assign the bins of our histogram to a variable to get a better look at it." }, { "code": null, "e": 2383, "s": 2340, "text": "n, bins, patches = plt.hist(df.Rocket)bins" }, { "code": null, "e": 2441, "s": 2383, "text": "That means our values are divided into ten bins, like so:" }, { "code": null, "e": 2457, "s": 2441, "text": "5.3 ≤ n < 49.77" }, { "code": null, "e": 2475, "s": 2457, "text": "49.77 ≤ n < 94.24" }, { "code": null, "e": 2479, "s": 2475, "text": "..." }, { "code": null, "e": 2496, "s": 2479, "text": "405.53 ≤ n ≤ 450" }, { "code": null, "e": 2585, "s": 2496, "text": "Note that the top value of each bin is excluded (<), but the last range includes it (≤)." }, { "code": null, "e": 2691, "s": 2585, "text": "Cool, now that we have a list with the edges of our bins, let’s try using it as the ticks for the x-axis." }, { "code": null, "e": 2751, "s": 2691, "text": "Let’s also add a figure and increase the size of our graph." }, { "code": null, "e": 2848, "s": 2751, "text": "fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)plt.xticks(bins)plt.show()" }, { "code": null, "e": 2863, "s": 2848, "text": "That’s better." }, { "code": null, "e": 2976, "s": 2863, "text": "Since we didn’t give Matplotlib any information about the bins, it automatically defined its numbers and ranges." }, { "code": null, "e": 3149, "s": 2976, "text": "We can set the bins by passing a list of edges when defining the plot; this allows us to create unevenly spaced bins, which is not typically recommended — but there’s that." }, { "code": null, "e": 3230, "s": 3149, "text": "Another way we can set them is using an integer with the number of bins we want." }, { "code": null, "e": 3336, "s": 3230, "text": "fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket, bins=16)plt.xticks(bins)plt.show()" }, { "code": null, "e": 3616, "s": 3336, "text": "The main point of a histogram is to visualize the distribution of our data. We don’t want our chart to have too many bins because that could hide the concentrations in our data; simultaneously, we don’t want a low number of classes because we could misinterpret the distribution." }, { "code": null, "e": 3829, "s": 3616, "text": "Choosing the number of classes in our histogram is sometimes very intuitive, but other times is quite a struggle. Luckily, we got plenty of algorithms for that, and Matplotlib allows us to chose which one to use." }, { "code": null, "e": 4000, "s": 3829, "text": "fig = plt.figure(figsize=(16,6))# 'auto', 'sturges', 'fd', 'doane', 'scott', 'rice' or 'sqrt'n, bins, patches = plt.hist(df.Rocket, bins='rice')plt.xticks(bins)plt.show()" }, { "code": null, "e": 4099, "s": 4000, "text": "Quite simply, we already know the basics of how a histogram works. Now we can try to customize it." }, { "code": null, "e": 4220, "s": 4099, "text": "We could use some gridlines in the x-axis to better visualize where the bins start and end. A title would also be great." }, { "code": null, "e": 4435, "s": 4220, "text": "fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)plt.xticks(bins)plt.grid(color='white', lw = 0.5, axis='x')plt.title('Histogram of Space Missions Costs', loc = 'left', fontsize = 18)plt.show()" }, { "code": null, "e": 4562, "s": 4435, "text": "It would be better if the ticks were in the center of the bars and displayed both the lower and upper boundaries of the range." }, { "code": null, "e": 4683, "s": 4562, "text": "We could define the labels by going through all the bins but the last while joining the current value with the next one." }, { "code": null, "e": 4704, "s": 4683, "text": "Something like this:" }, { "code": null, "e": 4807, "s": 4704, "text": "# x ticks labels[ \"{:.2f} - {:.2f}\".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]" }, { "code": null, "e": 4881, "s": 4807, "text": "And the ticks positions should be at the center of the two values, as so:" }, { "code": null, "e": 4965, "s": 4881, "text": "# x ticks positions[(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]" }, { "code": null, "e": 5120, "s": 4965, "text": "Cool, when we add this to our plot, we need to redefine the grids. If we draw the grid lines with the ticks, we’ll have the line in the middle of the bar." }, { "code": null, "e": 5281, "s": 5120, "text": "To fix that, we’ll use AutoMinorLocator, the class we imported at the beginning. That class will help us set the minor ticks, which we can use to draw the grid." }, { "code": null, "e": 5851, "s": 5281, "text": "fig = plt.figure(figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)# define minor ticks and draw a grid with themminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color='white', lw = 0.5)# x ticksxticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ \"{:.2f}\\nto\\n{:.2f}\".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels = xticks_labels)plt.title('Histogram of Space Missions Costs (Millions of USD)', loc = 'left', fontsize = 18)" }, { "code": null, "e": 5972, "s": 5851, "text": "It’s starting to look great; let’s remove the spines of our chart and the markings of the ticks to make it look cleaner." }, { "code": null, "e": 6842, "s": 5972, "text": "fig, ax = plt.subplots(1, figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)# define minor ticks and draw a grid with themminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color='white', lw = 0.5)# x ticksxticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ \"{:.2f}\\nto\\n{:.2f}\".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels = xticks_labels)# remove major and minor ticks from the x axis, but keep the labelsax.tick_params(axis='x', which='both',length=0)# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('Histogram of Space Missions Costs (Millions of USD)', loc = 'left', fontsize = 18)" }, { "code": null, "e": 6927, "s": 6842, "text": "For the y-axis, we could print the values on top of the bars and remove the y ticks." }, { "code": null, "e": 7027, "s": 6927, "text": "n the first variable we get from plotting our histograms holds a list with the counts for each bin." }, { "code": null, "e": 7132, "s": 7027, "text": "We can get the x positions for xticks from the list we built earlier and the labels and y values from n." }, { "code": null, "e": 8114, "s": 7132, "text": "fig, ax = plt.subplots(1, figsize=(16,6))n, bins, patches = plt.hist(df.Rocket)# define minor ticks and draw a grid with themminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color='white', lw = 0.5)# x ticksxticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ \"{:.2f}\\nto\\n{:.2f}\".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels = xticks_labels)ax.tick_params(axis='x', which='both',length=0)# remove y ticksplt.yticks([])# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)# plot values on top of barsfor idx, value in enumerate(n): if value > 0: plt.text(xticks[idx], value+5, int(value), ha='center')plt.title('Histogram of Space Missions Costs (Millions of USD)', loc = 'left', fontsize = 18)plt.show()" }, { "code": null, "e": 8123, "s": 8114, "text": "Awesome!" }, { "code": null, "e": 8279, "s": 8123, "text": "The elements are in place; all that’s left to do is change the colors, font sizes, add some labels on the x and y-axis, and customize the chart as desired." }, { "code": null, "e": 9640, "s": 8279, "text": "facecolor = '#EAEAEA'color_bars = '#3475D0'txt_color1 = '#252525'txt_color2 = '#004C74'fig, ax = plt.subplots(1, figsize=(20,6), facecolor=facecolor)ax.set_facecolor(facecolor)n, bins, patches = plt.hist(df.Rocket, color=color_bars, bins='doane')#gridminor_locator = AutoMinorLocator(2)plt.gca().xaxis.set_minor_locator(minor_locator)plt.grid(which='minor', color=facecolor, lw = 0.5)xticks = [(bins[idx+1] + value)/2 for idx, value in enumerate(bins[:-1])]xticks_labels = [ \"{:.0f}-{:.0f}\".format(value, bins[idx+1]) for idx, value in enumerate(bins[:-1])]plt.xticks(xticks, labels=xticks_labels, c=txt_color1, fontsize=13)# remove major and minor ticks from the x axis, but keep the labelsax.tick_params(axis='x', which='both',length=0)# remove y ticksplt.yticks([])# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)for idx, value in enumerate(n): if value > 0: plt.text(xticks[idx], value+5, int(value), ha='center', fontsize=16, c=txt_color1)plt.title('Histogram of Space Missions Costs\\n', loc = 'left', fontsize = 20, c=txt_color1)plt.xlabel('\\nMillions of USD', c=txt_color2, fontsize=14)plt.ylabel('Number of Space Missions', c=txt_color2, fontsize=14)plt.tight_layout()plt.savefig('costs.png', facecolor=facecolor)" }, { "code": null, "e": 9787, "s": 9640, "text": "Great! We got a numerical field and described its distribution with a beautiful chart. Now let’s have a look at how to handle dates in histograms." }, { "code": null, "e": 9892, "s": 9787, "text": "To figure out the bins on this one, we can start by looking at the earliest and latest date in our data." }, { "code": null, "e": 10081, "s": 9892, "text": "We can easily select the bins for numerical fields with the many different algorithms that Matplotlib supports, but those techniques may not yield the best results when dealing with dates." }, { "code": null, "e": 10260, "s": 10081, "text": "Don’t get me wrong, as much as you can find that the optimal size of bin to describe the distribution of your variable is 378 days, using a whole year is way more understandable." }, { "code": null, "e": 10405, "s": 10260, "text": "Alright, so let’s convert our date-time objects to a number format that Matplotlib can handle, then we’ll adjust our ticks and see how it looks." }, { "code": null, "e": 10898, "s": 10405, "text": "import matplotlib.dates as mdates# convert the date format to matplotlib date format plt_date = mdates.date2num(df['Datum'])bins = mdates.datestr2num([\"{}/01/01\".format(i) for i in np.arange(1957, 2022)])# plot itfig, ax = plt.subplots(1, figsize=(22,6))n, bins, patches = plt.hist(plt_date, bins=bins)# x ticks and limitax.xaxis.set_major_locator(mdates.YearLocator())ax.xaxis.set_major_formatter(mdates.DateFormatter('%y'))plt.xlim(mdates.datestr2num(['1957/01/01','2021/12/31']))plt.show()" }, { "code": null, "e": 11056, "s": 10898, "text": "That’s very interesting. We can see the space race taking shape from 57 to the late ’70s and a more recent increase in space programs in the last five years." }, { "code": null, "e": 11115, "s": 11056, "text": "Now we can adapt our previous design to our new histogram." }, { "code": null, "e": 12485, "s": 11115, "text": "facecolor = '#EAEAEA'color_bars = '#3475D0'txt_color1 = '#252525'txt_color2 = '#004C74'# convert the date format to matplotlib date format plt_date = mdates.date2num(df['Datum'])bins = mdates.datestr2num([\"{}/01/01\".format(i) for i in np.arange(1957, 2022)])# plot itfig, ax = plt.subplots(1, figsize=(22,8), facecolor=facecolor)ax.set_facecolor(facecolor)n, bins, patches = plt.hist(plt_date, bins=bins, color=color_bars)ax.xaxis.set_major_locator(mdates.YearLocator())ax.xaxis.set_major_formatter(mdates.DateFormatter('%y'))plt.xlim(mdates.datestr2num(['1957/01/01','2021/12/31']))#gridplt.grid(axis='y', color=color_bars, lw = 0.5, alpha=0.7)plt.grid(axis='x', color=facecolor, lw = 0.5)#remove major and minor ticks from the x axis, but keep the labelsax.tick_params(axis='both', which='both',length=0)# Hide the right and top spinesax.spines['bottom'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)ax.spines['left'].set_position(('outward', 10))plt.xticks(c=txt_color1, fontsize=12)plt.yticks(c=txt_color1, fontsize=12)plt.title('Histogram of Space Missions Dates\\n', loc = 'left', fontsize = 20, c=txt_color1)plt.xlabel('\\nYear', c=txt_color2, fontsize=14)plt.ylabel('Number of Space Missions', c=txt_color2, fontsize=14)plt.tight_layout()plt.savefig('hist.png', facecolor=facecolor)" }, { "code": null, "e": 12746, "s": 12485, "text": "And that’s it! We built two histograms, got a look at the different ways we have to define the bins and classes, changed lots of visual elements to make our chart look just like we wanted to, explored date formats, major and minor ticks, grid lines, and texts." }, { "code": null, "e": 12800, "s": 12746, "text": "Thanks for reading my article. I hope you enjoyed it." }, { "code": null, "e": 12862, "s": 12800, "text": "You can find more tutorials about Python and Matplotlib here." } ]
JavaFX - 3D Shape Box
A cuboid is a three dimensional or solid shape. Cuboids are made from 6 rectangles, which are placed at right angles. A cuboid that uses square faces is a cube, if the faces are rectangles, other than cubes, it looks like a shoe box. A cuboid is a three-dimensional shape with a length (depth), width, and a height as shown in the following diagram − In JavaFX, a 3-dimensional box is represented by a class named Box. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a Box node in JavaFX. This class has 3 properties of the double datatype, which are − width − The width of the box. width − The width of the box. height − The height of the box. height − The height of the box. depth − The depth of the box. depth − The depth of the box. To draw a cubic curve, you need to pass values to these properties by passing them to the constructor of this class. This has to be done in the same order at the time of instantiation as shown below − Box box = new Box(width, height, depth); Or, by using their respective setter methods as follows − setWidth(value); setHeight(value); setDepth(value); To Draw a 3D box in JavaFX, follow the steps given below. Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows − public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { } } You can create a Box in JavaFX by instantiating the class named BOX, which belongs to a package javafx.scene.shape. You can instantiate this class as follows. //Creating an object of the class Box Box box = new Box(); Set the properties of the 3D box, Width, Height and Depth, using their respective setter methods as shown in the following code block. //Setting the properties of the Box box.setWidth(200.0); box.setHeight(400.0); box.setDepth(200.0); In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Box (node) object, created in the previous step, as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows − Group root = new Group(box); Create a Scene by instantiating the class named Scene, which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step. In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows − Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object, which is passed to the start method of the scene class as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as follows. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using the following method − primaryStage.setScene(scene); Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows − public static void main(String args[]){ launch(args); } Following is a program which generates a 3D box using JavaFX. Save this code in a file with the name BoxExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Box; import javafx.stage.Stage; public class BoxExample extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box = new Box(); //Setting the properties of the Box box.setWidth(200.0); box.setHeight(400.0); box.setDepth(200.0); //Creating a Group object Group root = new Group(box); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Box"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac BoxExample.java java BoxExample On executing, the above program generates a JavaFX window displaying a 3D Box as shown below − 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2134, "s": 1900, "text": "A cuboid is a three dimensional or solid shape. Cuboids are made from 6 rectangles, which are placed at right angles. A cuboid that uses square faces is a cube, if the faces are rectangles, other than cubes, it looks like a shoe box." }, { "code": null, "e": 2251, "s": 2134, "text": "A cuboid is a three-dimensional shape with a length (depth), width, and a height as shown in the following diagram −" }, { "code": null, "e": 2373, "s": 2251, "text": "In JavaFX, a 3-dimensional box is represented by a class named Box. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 2439, "s": 2373, "text": "By instantiating this class, you can create a Box node in JavaFX." }, { "code": null, "e": 2503, "s": 2439, "text": "This class has 3 properties of the double datatype, which are −" }, { "code": null, "e": 2533, "s": 2503, "text": "width − The width of the box." }, { "code": null, "e": 2563, "s": 2533, "text": "width − The width of the box." }, { "code": null, "e": 2595, "s": 2563, "text": "height − The height of the box." }, { "code": null, "e": 2627, "s": 2595, "text": "height − The height of the box." }, { "code": null, "e": 2657, "s": 2627, "text": "depth − The depth of the box." }, { "code": null, "e": 2687, "s": 2657, "text": "depth − The depth of the box." }, { "code": null, "e": 2888, "s": 2687, "text": "To draw a cubic curve, you need to pass values to these properties by passing them to the constructor of this class. This has to be done in the same order at the time of instantiation as shown below −" }, { "code": null, "e": 2931, "s": 2888, "text": "Box box = new Box(width, height, depth); \n" }, { "code": null, "e": 2989, "s": 2931, "text": "Or, by using their respective setter methods as follows −" }, { "code": null, "e": 3044, "s": 2989, "text": "setWidth(value);\nsetHeight(value); \nsetDepth(value); \n" }, { "code": null, "e": 3102, "s": 3044, "text": "To Draw a 3D box in JavaFX, follow the steps given below." }, { "code": null, "e": 3250, "s": 3102, "text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows −" }, { "code": null, "e": 3392, "s": 3250, "text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}" }, { "code": null, "e": 3551, "s": 3392, "text": "You can create a Box in JavaFX by instantiating the class named BOX, which belongs to a package javafx.scene.shape. You can instantiate this class as follows." }, { "code": null, "e": 3612, "s": 3551, "text": "//Creating an object of the class Box \nBox box = new Box();\n" }, { "code": null, "e": 3747, "s": 3612, "text": "Set the properties of the 3D box, Width, Height and Depth, using their respective setter methods as shown in the following code block." }, { "code": null, "e": 3853, "s": 3747, "text": "//Setting the properties of the Box \nbox.setWidth(200.0); \nbox.setHeight(400.0); \nbox.setDepth(200.0);\n" }, { "code": null, "e": 3981, "s": 3853, "text": "In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene." }, { "code": null, "e": 4158, "s": 3981, "text": "Pass the Box (node) object, created in the previous step, as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows −" }, { "code": null, "e": 4188, "s": 4158, "text": "Group root = new Group(box);\n" }, { "code": null, "e": 4361, "s": 4188, "text": "Create a Scene by instantiating the class named Scene, which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step." }, { "code": null, "e": 4531, "s": 4361, "text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows −" }, { "code": null, "e": 4574, "s": 4531, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 4764, "s": 4574, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object, which is passed to the start method of the scene class as a parameter." }, { "code": null, "e": 4856, "s": 4764, "text": "Using the primaryStage object, set the title of the scene as Sample Application as follows." }, { "code": null, "e": 4902, "s": 4856, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 5077, "s": 4902, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using the following method −" }, { "code": null, "e": 5109, "s": 5077, "text": "primaryStage.setScene(scene); \n" }, { "code": null, "e": 5204, "s": 5109, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 5227, "s": 5204, "text": "primaryStage.show(); \n" }, { "code": null, "e": 5354, "s": 5227, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows −" }, { "code": null, "e": 5427, "s": 5354, "text": "public static void main(String args[]){ \n launch(args); \n} " }, { "code": null, "e": 5545, "s": 5427, "text": "Following is a program which generates a 3D box using JavaFX. Save this code in a file with the name BoxExample.java." }, { "code": null, "e": 6484, "s": 5545, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.shape.Box; \nimport javafx.stage.Stage; \n \npublic class BoxExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Box \n Box box = new Box(); \n \n //Setting the properties of the Box \n box.setWidth(200.0); \n box.setHeight(400.0); \n box.setDepth(200.0); \n \n //Creating a Group object \n Group root = new Group(box); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Box\"); \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 static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 6578, "s": 6484, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 6618, "s": 6578, "text": "javac BoxExample.java \njava BoxExample\n" }, { "code": null, "e": 6713, "s": 6618, "text": "On executing, the above program generates a JavaFX window displaying a 3D Box as shown below −" }, { "code": null, "e": 6748, "s": 6713, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6759, "s": 6748, "text": " Syed Raza" }, { "code": null, "e": 6795, "s": 6759, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6831, "s": 6795, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6864, "s": 6831, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 6900, "s": 6864, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6907, "s": 6900, "text": " Print" }, { "code": null, "e": 6918, "s": 6907, "text": " Add Notes" } ]
Bootstrap - Badges
This chapter will discuss about Bootstrap badges. Badges are similar to labels; the primary difference is that the corners are more rounded. Badges are mainly used to highlight new or unread items. To use badges just add <span class = "badge"> to links, Bootstrap navs, and more. The following example demonstrates this − <a href = "#">Mailbox <span class = "badge">50</span></a> When there are no new or unread items, badges will simply collapse via CSS's :empty selector, provided no content exists within. You can place badges in active states of pill and list navigations. You can achieve this by placing <span class = "badge"> to active links, as demonstrated in the following example − <h4>Example for Active State in Pill </h4> <ul class = "nav nav-pills"> <li class = "active"><a href = "#">Home <span class ="badge">42</span></a></li> <li><a href = "#">Profile</a></li> <li><a href = "#">Messages <span class = "badge">3</span></a></li> </ul> <br> <h4>Example for Active State in navigations</h4> <ul class = "nav nav-pills nav-stacked" style = "max-width: 260px;"> <li class = "active"> <a href = "#"> <span class = "badge pull-right">42</span> Home </a> </li> <li><a href = "#">Profile</a></li> <li> <a href = "#"> <span class = "badge pull-right">3</span> Messages </a> </li> </ul> Home 42 Profile Messages 3 42 Home Profile 3 Messages 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3472, "s": 3331, "text": "This chapter will discuss about Bootstrap badges. Badges are similar to labels; the primary difference is that the corners are more rounded." }, { "code": null, "e": 3611, "s": 3472, "text": "Badges are mainly used to highlight new or unread items. To use badges just add <span class = \"badge\"> to links, Bootstrap navs, and more." }, { "code": null, "e": 3653, "s": 3611, "text": "The following example demonstrates this −" }, { "code": null, "e": 3711, "s": 3653, "text": "<a href = \"#\">Mailbox <span class = \"badge\">50</span></a>" }, { "code": null, "e": 3841, "s": 3711, "text": "When there are no new or unread items, badges will simply collapse via CSS's :empty selector, provided no content exists within." }, { "code": null, "e": 4024, "s": 3841, "text": "You can place badges in active states of pill and list navigations. You can achieve this by placing <span class = \"badge\"> to active links, as demonstrated in the following example −" }, { "code": null, "e": 4718, "s": 4024, "text": "<h4>Example for Active State in Pill </h4>\n\n<ul class = \"nav nav-pills\">\n <li class = \"active\"><a href = \"#\">Home <span class =\"badge\">42</span></a></li>\n <li><a href = \"#\">Profile</a></li>\n <li><a href = \"#\">Messages <span class = \"badge\">3</span></a></li>\n</ul>\n\n<br>\n\n<h4>Example for Active State in navigations</h4>\n\n<ul class = \"nav nav-pills nav-stacked\" style = \"max-width: 260px;\">\n <li class = \"active\">\n <a href = \"#\">\n <span class = \"badge pull-right\">42</span>\n Home\n </a>\n </li>\n\t\n <li><a href = \"#\">Profile</a></li>\n\t\n <li>\n <a href = \"#\">\n <span class = \"badge pull-right\">3</span>\n Messages\n </a>\n </li>\n</ul>" }, { "code": null, "e": 4726, "s": 4718, "text": "Home 42" }, { "code": null, "e": 4734, "s": 4726, "text": "Profile" }, { "code": null, "e": 4745, "s": 4734, "text": "Messages 3" }, { "code": null, "e": 4784, "s": 4745, "text": "\n\n42\n Home\n \n" }, { "code": null, "e": 4792, "s": 4784, "text": "Profile" }, { "code": null, "e": 4834, "s": 4792, "text": "\n\n3\n Messages\n \n" }, { "code": null, "e": 4867, "s": 4834, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4881, "s": 4867, "text": " Anadi Sharma" }, { "code": null, "e": 4916, "s": 4881, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4933, "s": 4916, "text": " Frahaan Hussain" }, { "code": null, "e": 4970, "s": 4933, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 4998, "s": 4970, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5031, "s": 4998, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 5043, "s": 5031, "text": " Azaz Patel" }, { "code": null, "e": 5078, "s": 5043, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5095, "s": 5078, "text": " Muhammad Ismail" }, { "code": null, "e": 5128, "s": 5095, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 5148, "s": 5128, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 5155, "s": 5148, "text": " Print" }, { "code": null, "e": 5166, "s": 5155, "text": " Add Notes" } ]
Tryit Editor v3.7
CSS Rounded Corners Tryit: Specify each corner
[ { "code": null, "e": 29, "s": 9, "text": "CSS Rounded Corners" } ]
Count of nodes that are greater than Ancestors - GeeksforGeeks
10 Jun, 2021 Given the root of a tree, the task is to find the count of nodes which are greater than all of its ancestors.Examples: Input: 4 / \ 5 2 / \ 3 6 Output: 3 The nodes are 4, 5 and 6. Input: 10 / \ 8 6 \ \ 3 5 / 1 Output: 1 Approach: The problem can be solved using dfs. In every function call, pass a variable maxx which stores the maximum among all the nodes traversed so far, and every node whose value is greater than maxx is the node that satisfies the given condition. Hence, increment the count.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Structure for the node of the treestruct Tree { int val; Tree* left; Tree* right; Tree(int _val) { val = _val; left = NULL; right = NULL; }}; // Dfs Functionvoid dfs(Tree* node, int maxx, int& count){ // Base case if (node == NULL) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node->val > maxx) count++; // Left traversal dfs(node->left, max(maxx, node->val), count); // Right traversal dfs(node->right, max(maxx, node->val), count); }} // Driver codeint main(){ Tree* root = new Tree(4); root->left = new Tree(5); root->right = new Tree(2); root->right->left = new Tree(3); root->right->right = new Tree(6); // To store the required count int count = 0; dfs(root, INT_MIN, count); cout << count; return 0;} // Java implementation of the approachclass GFG{ static int count; // Structure for the node of the treestatic class Tree{ int val; Tree left; Tree right; Tree(int _val) { val = _val; left = null; right = null; }}; // Dfs Functionstatic void dfs(Tree node, int maxx){ // Base case if (node == null) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node.val > maxx) count++; // Left traversal dfs(node.left, Math.max(maxx, node.val)); // Right traversal dfs(node.right, Math.max(maxx, node.val)); }} // Driver codepublic static void main(String[] args){ Tree root = new Tree(4); root.left = new Tree(5); root.right = new Tree(2); root.right.left = new Tree(3); root.right.right = new Tree(6); // To store the required count count = 0; dfs(root, Integer.MIN_VALUE); System.out.print(count);}} // This code is contributed by 29AjayKumar # Python3 program for the# above approachfrom collections import deque # A Tree nodeclass Tree: def __init__(self, x): self.val = x self.left = None self.right = None count = 0 # Dfs Functiondef dfs(node, maxx): global count # Base case if (node == None): return else: # Increment the count if # the current node's value # is greater than the maximum # value in it's ancestors if (node.val > maxx): count += 1 # Left traversal dfs(node.left, max(maxx, node.val)) # Right traversal dfs(node.right, max(maxx, node.val)) # Driver codeif __name__ == '__main__': root = Tree(4) root.left = Tree(5) root.right = Tree(2) root.right.left = Tree(3) root.right.right = Tree(6) # To store the required # count count = 0 dfs(root, -10 ** 9) print(count) # This code is contributed by Mohit Kumar 29 // C# implementation of the approachusing System; class GFG{static int count; // Structure for the node of the treepublic class Tree{ public int val; public Tree left; public Tree right; public Tree(int _val) { val = _val; left = null; right = null; }}; // Dfs Functionstatic void dfs(Tree node, int maxx){ // Base case if (node == null) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node.val > maxx) count++; // Left traversal dfs(node.left, Math.Max(maxx, node.val)); // Right traversal dfs(node.right, Math.Max(maxx, node.val)); }} // Driver codepublic static void Main(String[] args){ Tree root = new Tree(4); root.left = new Tree(5); root.right = new Tree(2); root.right.left = new Tree(3); root.right.right = new Tree(6); // To store the required count count = 0; dfs(root, int.MinValue); Console.Write(count);}} // This code is contributed by Rajput-Ji <script>// Javascript implementation of the approach let count=0;// Structure for the node of the treeclass Tree{ constructor(val) { this.val=val; this.left=this.right=null; }} // Dfs Functionfunction dfs(node,maxx){ // Base case if (node == null) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node.val > maxx) count++; // Left traversal dfs(node.left, Math.max(maxx, node.val)); // Right traversal dfs(node.right, Math.max(maxx, node.val)); }} // Driver codelet root = new Tree(4);root.left = new Tree(5);root.right = new Tree(2);root.right.left = new Tree(3);root.right.right = new Tree(6); // To store the required countcount = 0; dfs(root, Number.MIN_VALUE); document.write(count); // This code is contributed by unknown2108</script> 3 29AjayKumar Rajput-Ji mohit kumar 29 unknown2108 Binary Tree Recursion Tree Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all possible combinations of r elements in a given array of size n Recursive Practice Problems with Solutions Write a program to reverse digits of a number Recursive Functions Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 25228, "s": 25200, "text": "\n10 Jun, 2021" }, { "code": null, "e": 25348, "s": 25228, "text": "Given the root of a tree, the task is to find the count of nodes which are greater than all of its ancestors.Examples: " }, { "code": null, "e": 25488, "s": 25348, "text": "Input: \n 4\n / \\\n5 2\n / \\\n 3 6\nOutput: 3\nThe nodes are 4, 5 and 6.\n\nInput: \n 10\n / \\\n 8 6\n \\ \\\n 3 5\n /\n 1\nOutput: 1" }, { "code": null, "e": 25819, "s": 25488, "text": "Approach: The problem can be solved using dfs. In every function call, pass a variable maxx which stores the maximum among all the nodes traversed so far, and every node whose value is greater than maxx is the node that satisfies the given condition. Hence, increment the count.Below is the implementation of the above approach: " }, { "code": null, "e": 25823, "s": 25819, "text": "C++" }, { "code": null, "e": 25828, "s": 25823, "text": "Java" }, { "code": null, "e": 25836, "s": 25828, "text": "Python3" }, { "code": null, "e": 25839, "s": 25836, "text": "C#" }, { "code": null, "e": 25850, "s": 25839, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Structure for the node of the treestruct Tree { int val; Tree* left; Tree* right; Tree(int _val) { val = _val; left = NULL; right = NULL; }}; // Dfs Functionvoid dfs(Tree* node, int maxx, int& count){ // Base case if (node == NULL) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node->val > maxx) count++; // Left traversal dfs(node->left, max(maxx, node->val), count); // Right traversal dfs(node->right, max(maxx, node->val), count); }} // Driver codeint main(){ Tree* root = new Tree(4); root->left = new Tree(5); root->right = new Tree(2); root->right->left = new Tree(3); root->right->right = new Tree(6); // To store the required count int count = 0; dfs(root, INT_MIN, count); cout << count; return 0;}", "e": 26896, "s": 25850, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int count; // Structure for the node of the treestatic class Tree{ int val; Tree left; Tree right; Tree(int _val) { val = _val; left = null; right = null; }}; // Dfs Functionstatic void dfs(Tree node, int maxx){ // Base case if (node == null) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node.val > maxx) count++; // Left traversal dfs(node.left, Math.max(maxx, node.val)); // Right traversal dfs(node.right, Math.max(maxx, node.val)); }} // Driver codepublic static void main(String[] args){ Tree root = new Tree(4); root.left = new Tree(5); root.right = new Tree(2); root.right.left = new Tree(3); root.right.right = new Tree(6); // To store the required count count = 0; dfs(root, Integer.MIN_VALUE); System.out.print(count);}} // This code is contributed by 29AjayKumar", "e": 27980, "s": 26896, "text": null }, { "code": "# Python3 program for the# above approachfrom collections import deque # A Tree nodeclass Tree: def __init__(self, x): self.val = x self.left = None self.right = None count = 0 # Dfs Functiondef dfs(node, maxx): global count # Base case if (node == None): return else: # Increment the count if # the current node's value # is greater than the maximum # value in it's ancestors if (node.val > maxx): count += 1 # Left traversal dfs(node.left, max(maxx, node.val)) # Right traversal dfs(node.right, max(maxx, node.val)) # Driver codeif __name__ == '__main__': root = Tree(4) root.left = Tree(5) root.right = Tree(2) root.right.left = Tree(3) root.right.right = Tree(6) # To store the required # count count = 0 dfs(root, -10 ** 9) print(count) # This code is contributed by Mohit Kumar 29", "e": 29005, "s": 27980, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{static int count; // Structure for the node of the treepublic class Tree{ public int val; public Tree left; public Tree right; public Tree(int _val) { val = _val; left = null; right = null; }}; // Dfs Functionstatic void dfs(Tree node, int maxx){ // Base case if (node == null) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node.val > maxx) count++; // Left traversal dfs(node.left, Math.Max(maxx, node.val)); // Right traversal dfs(node.right, Math.Max(maxx, node.val)); }} // Driver codepublic static void Main(String[] args){ Tree root = new Tree(4); root.left = new Tree(5); root.right = new Tree(2); root.right.left = new Tree(3); root.right.right = new Tree(6); // To store the required count count = 0; dfs(root, int.MinValue); Console.Write(count);}} // This code is contributed by Rajput-Ji", "e": 30118, "s": 29005, "text": null }, { "code": "<script>// Javascript implementation of the approach let count=0;// Structure for the node of the treeclass Tree{ constructor(val) { this.val=val; this.left=this.right=null; }} // Dfs Functionfunction dfs(node,maxx){ // Base case if (node == null) { return; } else { // Increment the count if the current // node's value is greater than the // maximum value in it's ancestors if (node.val > maxx) count++; // Left traversal dfs(node.left, Math.max(maxx, node.val)); // Right traversal dfs(node.right, Math.max(maxx, node.val)); }} // Driver codelet root = new Tree(4);root.left = new Tree(5);root.right = new Tree(2);root.right.left = new Tree(3);root.right.right = new Tree(6); // To store the required countcount = 0; dfs(root, Number.MIN_VALUE); document.write(count); // This code is contributed by unknown2108</script>", "e": 31067, "s": 30118, "text": null }, { "code": null, "e": 31069, "s": 31067, "text": "3" }, { "code": null, "e": 31083, "s": 31071, "text": "29AjayKumar" }, { "code": null, "e": 31093, "s": 31083, "text": "Rajput-Ji" }, { "code": null, "e": 31108, "s": 31093, "text": "mohit kumar 29" }, { "code": null, "e": 31120, "s": 31108, "text": "unknown2108" }, { "code": null, "e": 31132, "s": 31120, "text": "Binary Tree" }, { "code": null, "e": 31142, "s": 31132, "text": "Recursion" }, { "code": null, "e": 31147, "s": 31142, "text": "Tree" }, { "code": null, "e": 31157, "s": 31147, "text": "Recursion" }, { "code": null, "e": 31162, "s": 31157, "text": "Tree" }, { "code": null, "e": 31260, "s": 31162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31288, "s": 31260, "text": "Backtracking | Introduction" }, { "code": null, "e": 31361, "s": 31288, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31404, "s": 31361, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 31450, "s": 31404, "text": "Write a program to reverse digits of a number" }, { "code": null, "e": 31470, "s": 31450, "text": "Recursive Functions" }, { "code": null, "e": 31520, "s": 31470, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 31555, "s": 31520, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 31589, "s": 31555, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 31618, "s": 31589, "text": "AVL Tree | Set 1 (Insertion)" } ]
The Filter Function in Python. Learn how to use the filter function in... | by Luay Matalka | Towards Data Science
Even though Python is an object-oriented language, it still offers functions that provide a functional programming style. In a previous article, we discussed one of those functions, map. In this article, we will discuss another one of these Python built-in functions, the filter function. In this tutorial, we will learn what the filter function is in Python and how to use it. Article on the map function: towardsdatascience.com Let’s say we want to create a list using a list that we already have. But we want our new list to contain only the elements that satisfy a given condition. For example, we have a list of numbers, and we want to create a new list that contains only the even numbers from our list. We can accomplish this task with a for loop as follows: We have a list of numbers, list_of_nums, that contains the numbers 1, 2, 3, 4, 5, and 6. We want to create a new list of numbers, list_of_even_nums, that only contains the even numbers from list_of_nums. So we created a function, is_even, that takes in an input, and returns True if that input is even, or False if it is not. We then created a for loop that loops through list_of_nums and checks if each number of that list is even by passing in that element to the is_even function. If the is_even function returns True, that number is appended to list_of_even_nums. If is_even returns False, then that number is not appended to list_of_even_nums. Another way of accomplishing this would be to use the built-in Python filter function. towardsdatascience.com The filter function takes in two arguments: a function that returns True or False (checks for a specific condition) and the iterable object we want to apply it to (such as a list in this case). filter(function, iterable) The filter function takes each element from our list (or whatever iterable we pass in) and passes it in to the function we give it. If the function with that specific element as an argument returns True, the filter function will add that value to the filter object (that we can then create a list from just like we did with the map object returned by the map function). If the function returns False, then that element will not be added to our filter object. In other words, we can think of the filter function as filtering our list or sequence based on some condition. [x,y,z] → filter → [x (if f(x) returns True), y (if f(y) returns True), z (if f(z) returns True)] If we have a list of [x,y,z], then if f(x) returns True, x will be added to the filter object. If it returns False, it will not be added to the filter object. f being the function we pass in to the filter function. If f(y) returns True, it will be added to the filter object. And so on... Again, the filter function will return a filter object, which is an iterator. If we want to create a list from this filter object, we would need to pass in our filter object to the built-in list function (just like we did with the map object) as follows: list(filter(function, sequence)) We can then use the filter function to create the above list as follows: The filter function took the first element from list_of_nums, which is a 1, and passed it in as an argument to the is_even function (since we passed that function in as the first argument to the filter function). The is_even function then returns False, since 1 is not even, so 1 is not added to our filter object. The filter function then took the second element from list_of_nums, which is 2, and passed it in as an argument to the is_even function. The is_even function returns True, since 2 is even, and thus 2 is added to our filter object. After it goes through the rest of the elements in list_of_nums and the rest of the even numbers are added to our filter object, the list function casts this filter object onto a list, and that list was assigned to the variable list_of_even_nums. We can shorten our code even further by instead passing in a lambda expression as our function: Learn about lambda functions here: towardsdatascience.com If we recall, list comprehensions are used to create lists out of other sequences, either by applying some operation to the elements, by filtering through the elements, or some combination of both. In other words, list comprehensions can have the same functionality as the built-in map and filter functions. The operation applied to each element is similar to the map function, and if we add a condition to which elements are added to the list in the list comprehension, that’s similar to the filter function. Also, the expression that is added in the beginning of a list comprehension is similar to the lambda expression that can be used inside the map and filter functions. This is a list comprehension that adds the square of the elements from 0 to 9, only if the element is even: [x**2 for x in range(10) if x%2==0]# [0,4,16,36,64] We can use the map and filter functions, along with lambda functions, to accomplish the same thing: list(map(lambda x:x**2, filter(lambda x:x%2==0, range(10))))# [0,4,16,36,64] The function passed into the map function is a lambda expression that takes input x and returns its square. The list passed into the map function is a filtered list that contains the even elements from 0 to 9. Learn more about list comprehensions here: towardsdatascience.com Performance comparison of map, filter, and list comprehensions: towardsdatascience.com I hope you enjoyed this article on the filter function in Python. Thank you for reading!
[ { "code": null, "e": 336, "s": 47, "text": "Even though Python is an object-oriented language, it still offers functions that provide a functional programming style. In a previous article, we discussed one of those functions, map. In this article, we will discuss another one of these Python built-in functions, the filter function." }, { "code": null, "e": 425, "s": 336, "text": "In this tutorial, we will learn what the filter function is in Python and how to use it." }, { "code": null, "e": 454, "s": 425, "text": "Article on the map function:" }, { "code": null, "e": 477, "s": 454, "text": "towardsdatascience.com" }, { "code": null, "e": 813, "s": 477, "text": "Let’s say we want to create a list using a list that we already have. But we want our new list to contain only the elements that satisfy a given condition. For example, we have a list of numbers, and we want to create a new list that contains only the even numbers from our list. We can accomplish this task with a for loop as follows:" }, { "code": null, "e": 1462, "s": 813, "text": "We have a list of numbers, list_of_nums, that contains the numbers 1, 2, 3, 4, 5, and 6. We want to create a new list of numbers, list_of_even_nums, that only contains the even numbers from list_of_nums. So we created a function, is_even, that takes in an input, and returns True if that input is even, or False if it is not. We then created a for loop that loops through list_of_nums and checks if each number of that list is even by passing in that element to the is_even function. If the is_even function returns True, that number is appended to list_of_even_nums. If is_even returns False, then that number is not appended to list_of_even_nums." }, { "code": null, "e": 1549, "s": 1462, "text": "Another way of accomplishing this would be to use the built-in Python filter function." }, { "code": null, "e": 1572, "s": 1549, "text": "towardsdatascience.com" }, { "code": null, "e": 1766, "s": 1572, "text": "The filter function takes in two arguments: a function that returns True or False (checks for a specific condition) and the iterable object we want to apply it to (such as a list in this case)." }, { "code": null, "e": 1793, "s": 1766, "text": "filter(function, iterable)" }, { "code": null, "e": 2363, "s": 1793, "text": "The filter function takes each element from our list (or whatever iterable we pass in) and passes it in to the function we give it. If the function with that specific element as an argument returns True, the filter function will add that value to the filter object (that we can then create a list from just like we did with the map object returned by the map function). If the function returns False, then that element will not be added to our filter object. In other words, we can think of the filter function as filtering our list or sequence based on some condition." }, { "code": null, "e": 2461, "s": 2363, "text": "[x,y,z] → filter → [x (if f(x) returns True), y (if f(y) returns True), z (if f(z) returns True)]" }, { "code": null, "e": 2750, "s": 2461, "text": "If we have a list of [x,y,z], then if f(x) returns True, x will be added to the filter object. If it returns False, it will not be added to the filter object. f being the function we pass in to the filter function. If f(y) returns True, it will be added to the filter object. And so on..." }, { "code": null, "e": 3005, "s": 2750, "text": "Again, the filter function will return a filter object, which is an iterator. If we want to create a list from this filter object, we would need to pass in our filter object to the built-in list function (just like we did with the map object) as follows:" }, { "code": null, "e": 3038, "s": 3005, "text": "list(filter(function, sequence))" }, { "code": null, "e": 3111, "s": 3038, "text": "We can then use the filter function to create the above list as follows:" }, { "code": null, "e": 3903, "s": 3111, "text": "The filter function took the first element from list_of_nums, which is a 1, and passed it in as an argument to the is_even function (since we passed that function in as the first argument to the filter function). The is_even function then returns False, since 1 is not even, so 1 is not added to our filter object. The filter function then took the second element from list_of_nums, which is 2, and passed it in as an argument to the is_even function. The is_even function returns True, since 2 is even, and thus 2 is added to our filter object. After it goes through the rest of the elements in list_of_nums and the rest of the even numbers are added to our filter object, the list function casts this filter object onto a list, and that list was assigned to the variable list_of_even_nums." }, { "code": null, "e": 3999, "s": 3903, "text": "We can shorten our code even further by instead passing in a lambda expression as our function:" }, { "code": null, "e": 4034, "s": 3999, "text": "Learn about lambda functions here:" }, { "code": null, "e": 4057, "s": 4034, "text": "towardsdatascience.com" }, { "code": null, "e": 4733, "s": 4057, "text": "If we recall, list comprehensions are used to create lists out of other sequences, either by applying some operation to the elements, by filtering through the elements, or some combination of both. In other words, list comprehensions can have the same functionality as the built-in map and filter functions. The operation applied to each element is similar to the map function, and if we add a condition to which elements are added to the list in the list comprehension, that’s similar to the filter function. Also, the expression that is added in the beginning of a list comprehension is similar to the lambda expression that can be used inside the map and filter functions." }, { "code": null, "e": 4841, "s": 4733, "text": "This is a list comprehension that adds the square of the elements from 0 to 9, only if the element is even:" }, { "code": null, "e": 4893, "s": 4841, "text": "[x**2 for x in range(10) if x%2==0]# [0,4,16,36,64]" }, { "code": null, "e": 4993, "s": 4893, "text": "We can use the map and filter functions, along with lambda functions, to accomplish the same thing:" }, { "code": null, "e": 5070, "s": 4993, "text": "list(map(lambda x:x**2, filter(lambda x:x%2==0, range(10))))# [0,4,16,36,64]" }, { "code": null, "e": 5280, "s": 5070, "text": "The function passed into the map function is a lambda expression that takes input x and returns its square. The list passed into the map function is a filtered list that contains the even elements from 0 to 9." }, { "code": null, "e": 5323, "s": 5280, "text": "Learn more about list comprehensions here:" }, { "code": null, "e": 5346, "s": 5323, "text": "towardsdatascience.com" }, { "code": null, "e": 5410, "s": 5346, "text": "Performance comparison of map, filter, and list comprehensions:" }, { "code": null, "e": 5433, "s": 5410, "text": "towardsdatascience.com" } ]
Collection addAll() method in Java with Examples - GeeksforGeeks
29 Nov, 2018 The addAll(Collection collection) of java.util.Collection interface is used to add the Collection ‘collection’ to this existing collection. This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false. Syntax: Collection.addAll(Collection<E> collection) Parameters: This method accepts a mandatory parameter collection of type Collection which is to be added to this collection. Return Value: This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false. Exceptions: This method throws following exceptions: UnsupportedOperationException: if the add operation is not supported by this collection ClassCastException: if the class of the specified element prevents it from being added to this collection NullPointerException: if the specified element is null and this collection does not permit null elements IllegalArgumentException: if some property of the element prevents it from being added to this collection IllegalStateException: if the element cannot be added at this time due to insertion restrictions Below examples illustrate the Collection addAll() method: Example 1: Using LinkedList Class // Java code to illustrate boolean addAll() import java.util.*;import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // A collection is created Collection<String> collect = new LinkedList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The LinkedList is: " + list); // Appending the collection to the list list.addAll(collect); // displaying the modified LinkedList System.out.println("The new linked list is: " + list); }} The LinkedList is: [] The new linked list is: [A, Computer, Portal, for, Geeks] Example 2: Using ArrayDeque Class // Java code to illustrate addAll() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Creating a new ArrayDeque Collection<String> deque = new ArrayDeque<String>(); deque.add("Welcome"); deque.add("To"); deque.add("Geeks"); deque.add("4"); deque.add("Geeks"); // Displaying the list System.out.println("The ArrayDeque is: " + de_que); // Appending the collection to the list de_que.addAll(deque); // displaying the modified ArrayDeque System.out.println("The new ArrayDeque is: " + de_que); }} The ArrayDeque is: [] The new ArrayDeque is: [Welcome, To, Geeks, 4, Geeks] Example 3: Using ArrayList Class // Java code to illustrate boolean addAll() import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty ArrayList Collection<String> list = new ArrayList<String>(); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add("A"); collect.add("Computer"); collect.add("Portal"); collect.add("for"); collect.add("Geeks"); // Displaying the list System.out.println("The ArrayList is: " + list); // Appending the collection to the list list.addAll(collect); // displaying the modified ArrayList System.out.println("The new ArrayList is: " + list); }} The ArrayList is: [] The new ArrayList is: [A, Computer, Portal, for, Geeks] Example 4: To demonstrate NullPointer Exception // Java code to illustrate boolean addAll() import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty ArrayList Collection<String> list = new ArrayList<String>(); // A collection is created Collection<String> collect = null; // Displaying the list System.out.println("The ArrayList is: " + list); try { // Appending the collection to the list list.addAll(collect); } catch (Exception e) { System.out.println("Exception: " + e); } }} The ArrayList is: [] Exception: java.lang.NullPointerException Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#addAll-java.util.Collection- Java - util package Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n29 Nov, 2018" }, { "code": null, "e": 24240, "s": 23948, "text": "The addAll(Collection collection) of java.util.Collection interface is used to add the Collection ‘collection’ to this existing collection. This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false." }, { "code": null, "e": 24248, "s": 24240, "text": "Syntax:" }, { "code": null, "e": 24293, "s": 24248, "text": "Collection.addAll(Collection<E> collection)\n" }, { "code": null, "e": 24418, "s": 24293, "text": "Parameters: This method accepts a mandatory parameter collection of type Collection which is to be added to this collection." }, { "code": null, "e": 24584, "s": 24418, "text": "Return Value: This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false." }, { "code": null, "e": 24637, "s": 24584, "text": "Exceptions: This method throws following exceptions:" }, { "code": null, "e": 24725, "s": 24637, "text": "UnsupportedOperationException: if the add operation is not supported by this collection" }, { "code": null, "e": 24831, "s": 24725, "text": "ClassCastException: if the class of the specified element prevents it from being added to this collection" }, { "code": null, "e": 24936, "s": 24831, "text": "NullPointerException: if the specified element is null and this collection does not permit null elements" }, { "code": null, "e": 25042, "s": 24936, "text": "IllegalArgumentException: if some property of the element prevents it from being added to this collection" }, { "code": null, "e": 25139, "s": 25042, "text": "IllegalStateException: if the element cannot be added at this time due to insertion restrictions" }, { "code": null, "e": 25197, "s": 25139, "text": "Below examples illustrate the Collection addAll() method:" }, { "code": null, "e": 25231, "s": 25197, "text": "Example 1: Using LinkedList Class" }, { "code": "// Java code to illustrate boolean addAll() import java.util.*;import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // A collection is created Collection<String> collect = new LinkedList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The LinkedList is: \" + list); // Appending the collection to the list list.addAll(collect); // displaying the modified LinkedList System.out.println(\"The new linked list is: \" + list); }}", "e": 26064, "s": 25231, "text": null }, { "code": null, "e": 26145, "s": 26064, "text": "The LinkedList is: []\nThe new linked list is: [A, Computer, Portal, for, Geeks]\n" }, { "code": null, "e": 26179, "s": 26145, "text": "Example 2: Using ArrayDeque Class" }, { "code": "// Java code to illustrate addAll() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Creating a new ArrayDeque Collection<String> deque = new ArrayDeque<String>(); deque.add(\"Welcome\"); deque.add(\"To\"); deque.add(\"Geeks\"); deque.add(\"4\"); deque.add(\"Geeks\"); // Displaying the list System.out.println(\"The ArrayDeque is: \" + de_que); // Appending the collection to the list de_que.addAll(deque); // displaying the modified ArrayDeque System.out.println(\"The new ArrayDeque is: \" + de_que); }}", "e": 26982, "s": 26179, "text": null }, { "code": null, "e": 27059, "s": 26982, "text": "The ArrayDeque is: []\nThe new ArrayDeque is: [Welcome, To, Geeks, 4, Geeks]\n" }, { "code": null, "e": 27092, "s": 27059, "text": "Example 3: Using ArrayList Class" }, { "code": "// Java code to illustrate boolean addAll() import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty ArrayList Collection<String> list = new ArrayList<String>(); // A collection is created Collection<String> collect = new ArrayList<String>(); collect.add(\"A\"); collect.add(\"Computer\"); collect.add(\"Portal\"); collect.add(\"for\"); collect.add(\"Geeks\"); // Displaying the list System.out.println(\"The ArrayList is: \" + list); // Appending the collection to the list list.addAll(collect); // displaying the modified ArrayList System.out.println(\"The new ArrayList is: \" + list); }}", "e": 27899, "s": 27092, "text": null }, { "code": null, "e": 27977, "s": 27899, "text": "The ArrayList is: []\nThe new ArrayList is: [A, Computer, Portal, for, Geeks]\n" }, { "code": null, "e": 28025, "s": 27977, "text": "Example 4: To demonstrate NullPointer Exception" }, { "code": "// Java code to illustrate boolean addAll() import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty ArrayList Collection<String> list = new ArrayList<String>(); // A collection is created Collection<String> collect = null; // Displaying the list System.out.println(\"The ArrayList is: \" + list); try { // Appending the collection to the list list.addAll(collect); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 28645, "s": 28025, "text": null }, { "code": null, "e": 28709, "s": 28645, "text": "The ArrayList is: []\nException: java.lang.NullPointerException\n" }, { "code": null, "e": 28817, "s": 28709, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#addAll-java.util.Collection-" }, { "code": null, "e": 28837, "s": 28817, "text": "Java - util package" }, { "code": null, "e": 28854, "s": 28837, "text": "Java-Collections" }, { "code": null, "e": 28869, "s": 28854, "text": "Java-Functions" }, { "code": null, "e": 28874, "s": 28869, "text": "Java" }, { "code": null, "e": 28879, "s": 28874, "text": "Java" }, { "code": null, "e": 28896, "s": 28879, "text": "Java-Collections" }, { "code": null, "e": 28994, "s": 28896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29009, "s": 28994, "text": "Stream In Java" }, { "code": null, "e": 29055, "s": 29009, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29076, "s": 29055, "text": "Constructors in Java" }, { "code": null, "e": 29095, "s": 29076, "text": "Exceptions in Java" }, { "code": null, "e": 29112, "s": 29095, "text": "Generics in Java" }, { "code": null, "e": 29142, "s": 29112, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29185, "s": 29142, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29214, "s": 29185, "text": "HashMap get() Method in Java" }, { "code": null, "e": 29235, "s": 29214, "text": "Introduction to Java" } ]
CSS | grid-area Property - GeeksforGeeks
08 Aug, 2019 The grid-area property is used to set a grid item size and location in a grid layout. The grid-area property is also used to set a name to a grid item. Syntax: grid-area: grid-row-start|grid-column-start|grid-row-end| grid-column-end|itemname; Property Values: grid-row-start: It sets the row on which the item is displayed first. grid-column-start: It sets the column on which the item is displayed first. grid-row-end: It specifies the row-line to stop displaying the item, or span how many rows. grid-column-end: It sets the number of columns to span. itemname: It sets a name for the grid item. Example 1: <!DOCTYPE html><html><head> <title> CSS | grid-area Property </title> <style> .item { grid-area: Area; } .grid-container { display: grid; grid-template-areas: 'Area Area Area'; grid-gap: 30px; background-color: green; padding: 20px; } .GFG { background-color: white; text-align: center; padding: 20px 0; font-size: 30px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>The grid-area Property</h2> <div class = "grid-container"> <div class = "GFG item">1</div> <div class = "GFG">2</div> <div class = "GFG">3</div> <div class = "GFG">4</div> <div class = "GFG">5</div> <div class = "GFG">6</div> </div></body></html> Output: Example 2: <!DOCTYPE html><html><head> <title> CSS grid-area property </title> <style> .GFG1 { grid-area: heading; } .GFG2 { grid-area: margin; } .GFG3 { grid-area: subtitle1; } .GFG4 { grid-area: info; } .main { display: grid; grid-gap: 30px; background-color: green; padding: 20px; grid-template-areas: 'margin heading heading heading heading heading ' 'margin subtitle1 info info info info'; } .GFG { background-color: white; text-align: center; padding: 20px 0; font-size: 30px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS grid-area Property</h2> <div class = "main"> <div class = "GFG GFG1">Heading</div> <div class = "GFG GFG2">Margin</div> <div class = "GFG GFG3">Subtitle</div> <div class = "GFG GFG4">info</div> </div> </body></html> Output: Supported Browsers: The browsers supported by grid-area property are listed below: Google Chrome 57.0 Internet Explorer 16.0 Mozilla Firefox 52.0 Safari 10.0 Opera 44.0 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 23580, "s": 23552, "text": "\n08 Aug, 2019" }, { "code": null, "e": 23732, "s": 23580, "text": "The grid-area property is used to set a grid item size and location in a grid layout. The grid-area property is also used to set a name to a grid item." }, { "code": null, "e": 23740, "s": 23732, "text": "Syntax:" }, { "code": null, "e": 23824, "s": 23740, "text": "grid-area: grid-row-start|grid-column-start|grid-row-end|\ngrid-column-end|itemname;" }, { "code": null, "e": 23841, "s": 23824, "text": "Property Values:" }, { "code": null, "e": 23911, "s": 23841, "text": "grid-row-start: It sets the row on which the item is displayed first." }, { "code": null, "e": 23987, "s": 23911, "text": "grid-column-start: It sets the column on which the item is displayed first." }, { "code": null, "e": 24079, "s": 23987, "text": "grid-row-end: It specifies the row-line to stop displaying the item, or span how many rows." }, { "code": null, "e": 24135, "s": 24079, "text": "grid-column-end: It sets the number of columns to span." }, { "code": null, "e": 24179, "s": 24135, "text": "itemname: It sets a name for the grid item." }, { "code": null, "e": 24190, "s": 24179, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | grid-area Property </title> <style> .item { grid-area: Area; } .grid-container { display: grid; grid-template-areas: 'Area Area Area'; grid-gap: 30px; background-color: green; padding: 20px; } .GFG { background-color: white; text-align: center; padding: 20px 0; font-size: 30px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>The grid-area Property</h2> <div class = \"grid-container\"> <div class = \"GFG item\">1</div> <div class = \"GFG\">2</div> <div class = \"GFG\">3</div> <div class = \"GFG\">4</div> <div class = \"GFG\">5</div> <div class = \"GFG\">6</div> </div></body></html> ", "e": 25062, "s": 24190, "text": null }, { "code": null, "e": 25070, "s": 25062, "text": "Output:" }, { "code": null, "e": 25081, "s": 25070, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS grid-area property </title> <style> .GFG1 { grid-area: heading; } .GFG2 { grid-area: margin; } .GFG3 { grid-area: subtitle1; } .GFG4 { grid-area: info; } .main { display: grid; grid-gap: 30px; background-color: green; padding: 20px; grid-template-areas: 'margin heading heading heading heading heading ' 'margin subtitle1 info info info info'; } .GFG { background-color: white; text-align: center; padding: 20px 0; font-size: 30px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS grid-area Property</h2> <div class = \"main\"> <div class = \"GFG GFG1\">Heading</div> <div class = \"GFG GFG2\">Margin</div> <div class = \"GFG GFG3\">Subtitle</div> <div class = \"GFG GFG4\">info</div> </div> </body></html> ", "e": 26174, "s": 25081, "text": null }, { "code": null, "e": 26182, "s": 26174, "text": "Output:" }, { "code": null, "e": 26265, "s": 26182, "text": "Supported Browsers: The browsers supported by grid-area property are listed below:" }, { "code": null, "e": 26284, "s": 26265, "text": "Google Chrome 57.0" }, { "code": null, "e": 26307, "s": 26284, "text": "Internet Explorer 16.0" }, { "code": null, "e": 26328, "s": 26307, "text": "Mozilla Firefox 52.0" }, { "code": null, "e": 26340, "s": 26328, "text": "Safari 10.0" }, { "code": null, "e": 26351, "s": 26340, "text": "Opera 44.0" }, { "code": null, "e": 26366, "s": 26351, "text": "CSS-Properties" }, { "code": null, "e": 26373, "s": 26366, "text": "Picked" }, { "code": null, "e": 26377, "s": 26373, "text": "CSS" }, { "code": null, "e": 26394, "s": 26377, "text": "Web Technologies" }, { "code": null, "e": 26492, "s": 26394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26554, "s": 26492, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26604, "s": 26554, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26662, "s": 26604, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26710, "s": 26662, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26760, "s": 26710, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26802, "s": 26760, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26835, "s": 26802, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26878, "s": 26835, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26940, "s": 26878, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to extract numbers from text using Python regular expression?
If we want to extract all numbers/digits individually from given text we use the following regex import re s = '12345 abcdf 67' result=re.findall(r'\d', s) print result ['1', '2', '3', '4', '5', '6', '7'] If we want to extract groups of numbers/digits from given text we use the following regex import re s = '12345 abcdf 67' result=re.findall(r'\d+', s) print result ['12345', '67']
[ { "code": null, "e": 1160, "s": 1062, "text": "If we want to extract all numbers/digits individually from given text we use the following regex" }, { "code": null, "e": 1232, "s": 1160, "text": "import re\ns = '12345 abcdf 67'\nresult=re.findall(r'\\d', s)\nprint result" }, { "code": null, "e": 1268, "s": 1232, "text": "['1', '2', '3', '4', '5', '6', '7']" }, { "code": null, "e": 1358, "s": 1268, "text": "If we want to extract groups of numbers/digits from given text we use the following regex" }, { "code": null, "e": 1431, "s": 1358, "text": "import re\ns = '12345 abcdf 67'\nresult=re.findall(r'\\d+', s)\nprint result" }, { "code": null, "e": 1447, "s": 1431, "text": "['12345', '67']" } ]
Cleaning and Preparing Data in Python | by Sergi Lehkyi | Towards Data Science
Data Science sounds like something cool and awesome. It’s pictured as something cool and awesome. It is a sexiest job of 21st century as we all know (I won’t even add the link to that article :D). All the cool terms are related to this field — Machine Learning, Deep Learning, AI, Neural Networks, algorithms, models... But all this is just a top of an iceberg. 70–80% of our work is data preprocessing, data cleaning, data transformation, data reprocessing — all these boring steps to make our data suitable for the model that will make some modern magic. And today I would like to list all the methods and functions that can help us to clean and prepare the data. So what can be wrong with our data? A lot of things actually: Irrelevant column names Outliers Duplicates Missing data Columns that have to be processed Unexpected data values For the quick overview we can use following methods and attributes of a DataFrame: df.head() # show first 5 rowsdf.tail() # last 5 rowsdf.columns # list all column namesdf.shape # get number of rows and columnsdf.info() # additional info about dataframedf.describe() # statistical description, only for numeric valuesdf['col_name'].value_counts(dropna=False) # count unique values in a column The output of at least one of these will give us first clues where we want to start our cleaning. Another way to quickly check the data is by visualizing it. We use bar plots for discrete data counts and histogram for continuous. df['col_name'].plot('hist')df.boxplot(column='col_name1', by='col_name2') Histogram and box plot can help to spot visually the outliers. The scatter plot shows relationship between 2 numeric variables. df.plot(kind='scatter', x='col1', y='col2') Visualizing data can bring some unexpected results as it gives you a perspective of what’s going on in your dataset. Kind of view from the top. Tidy data is the data obtained as a result of a process called data tidying. It is one of the important cleaning processes during big data processing and is a recognized step in the practice of data science. Tidy data sets have structure and working with them is easy; they’re easy to manipulate, model and visualize. Tidy data sets main concept is to arrange data in a way that each variable is a column and each observation (or case) is a row. Tidy data provide standards and concepts for data cleaning, and with tidy data there’s no need to start from scratch and reinvent new methods for data cleaning. Characteristics: Each variable you measure should be in one column. Each different observation of that variable should be in a different row. There should be one table for each “kind” of variable. If you have multiple tables, they should include a column in the table that allows them to be linked. (all these taken from Wikipedia) To transform our data and make it tidy we can use melting. pd.melt() # transform columns to rows There are two parameters you should be aware of: id_vars and value_vars. The id_vars represent the columns of the data you do not want to melt (i.e., keep it in its current shape), while the value_vars represent the columns you do wish to melt into rows. By default, if no value_vars are provided, all columns not set in the id_vars will be melted. new_df = pd.melt(df, id_vars = 'do not melt') The opposite operation to melting is pivoting. Here we turn unique values into separate columns. We use it when we want to transform our data from analysis shape to reporting shape, from easy-machine-readable to easy-human-readable form. df.pivot(index='date', columns='element', values='value') Although, this method cannot handle duplicate values. When this is a case we should use .pivot_table() that has an additional parameter — aggfunc, which will handle those duplicates based on a function we provide (sum, count, mean, min, max or user defined function). df.pivot_table(index='date', columns='element', values='value', aggfunc=np.mean) Sometimes we might have data stored incorrectly. For example, values for the gender groups that stored as ‘m014’, ‘f014’, ‘m1528’, ‘f1528’. You cannot tell it’s completely wrong, but it would be better to split these values into ‘gender’ and ‘age’ columns. To do this we use Python slicing sintaxis by accessing .str attribute of column of object type. df['gender'] = df.variable.str[0] df['age_group'] = df.variable.str[1:] Also data might not come in one huge file and be separated into few different chunks, so we have to be able to concatenate all that data and clean it or clean the first sample and then apply the same process on remaining parts. To do this we can use pandas .concat method, which provided with the list of dataframes will concatenate them all. By default it will store the original indexes what will result in duplicate index values. To prevent this we have to reset index of a new dataframe by passing an additional parameter ignore_index=True. concatenated = pd.concat([df1, df2], ignore_index=True) But what if we have thousands of files? It’ll be dumb to import them one by one, clean them and repeat it again. And we are not stupid, we know loops in Python. The only missing part is to find all those files for import. We can do this with glob library. So the process will be the following: write a pattern, save all files into a list, iterate over csv files, import each file and concatenate the dataframes into one. Doesn’t seem that difficult, but with the code sample it’s much better: # Import necessary modulesimport globimport pandas as pd # Write the pattern: pattern pattern = '*.csv' # Save all file matches: csv_filescsv_files = glob.glob(pattern) # Create an empty list: framesframes = [] # Iterate over csv_files for csv in csv_files: # Read csv into a DataFrame: df df = pd.read_csv(csv) # Append df to frames frames.append(df)# Concatenate frames into a single DataFrame: final_dffinal_df = pd.concat(frames) Merging is the same as SQL join operation. You combine two or more tables into one by key which is present in every table. There are three types of joins: one-to-one, one-many, many-to-many. In SQL this process is advanced, with a lot of options, modifications, where you have to explicitly specify what and how you want to join. Here, all is done for you by one function and the type of join will only depend on a data in a dataframe. If the column name to be used as a key is the same in both dataframes ‘on’ parameter is used. merged = pd.merge(left=df1, right=df2, on=None, left_on='col1', right_on='col2') It is very important to have data with correct data types as later it may play a bad joke with you and your analysis. Remember how once I didn’t convert one column to the correct data type and spent 1 hour trying to subtract float from string :D. So be careful :D. That’s a typical error in data, which can be fixed with pd.to_numeric() and with errors=’coerce’ it will convert all the err values into NaNs. To convert data we can use .astype() method on a series. Also keep in mind the ‘category’ type — it reduces size of a dataframe and makes computations faster. We can convert to any value that can be used as category — days of the week, gender, continent abbreviations — depends on a context. df['column1'] = df['column1'].astype(str) df['column1'] = df['column1'].astype('category')df['column1'] = pd.to_numeric(df['column1'], errors='coerce') Our favourite part, isn’t it? To drop duplicates we can use druuuuuuuuuums drop_duplicates() method. df = df.drop_duplicates() With missing values it is little bit more complicated. In general there are three ways to deal with missing data: leave as-is drop them fill missing values To drop missing values we can use .dropna(), but careful with it — it may delete up to 50% of your data — which is not really good. But again, depends on a context. To fill missing values we use .fillna(), careful with it as well — if we fill missing values they have to be reasonable and make sense. There is a wonderful article on handling missing data and I really have nothing to add on this part. Here is the link and don’t forget to give an author a round of applause, because that work is just amazing. We can also programmatically check our data using assert statements. It will return nothing if the result is True and error otherwise. assert 1 == 1 # returns nothing assert 1 == 2 # returns errorassert df.notnull().all().all() # returns error if at least one column has one missing value I skipped regular expressions as it deserves a separate article, but in general summarized tools I use for data preprocessing. Please, let me know if something else can be added, have a great day and use data science for good 🙂 Originally published at sergilehkyi.com.
[ { "code": null, "e": 492, "s": 172, "text": "Data Science sounds like something cool and awesome. It’s pictured as something cool and awesome. It is a sexiest job of 21st century as we all know (I won’t even add the link to that article :D). All the cool terms are related to this field — Machine Learning, Deep Learning, AI, Neural Networks, algorithms, models..." }, { "code": null, "e": 729, "s": 492, "text": "But all this is just a top of an iceberg. 70–80% of our work is data preprocessing, data cleaning, data transformation, data reprocessing — all these boring steps to make our data suitable for the model that will make some modern magic." }, { "code": null, "e": 838, "s": 729, "text": "And today I would like to list all the methods and functions that can help us to clean and prepare the data." }, { "code": null, "e": 900, "s": 838, "text": "So what can be wrong with our data? A lot of things actually:" }, { "code": null, "e": 924, "s": 900, "text": "Irrelevant column names" }, { "code": null, "e": 933, "s": 924, "text": "Outliers" }, { "code": null, "e": 944, "s": 933, "text": "Duplicates" }, { "code": null, "e": 957, "s": 944, "text": "Missing data" }, { "code": null, "e": 991, "s": 957, "text": "Columns that have to be processed" }, { "code": null, "e": 1014, "s": 991, "text": "Unexpected data values" }, { "code": null, "e": 1097, "s": 1014, "text": "For the quick overview we can use following methods and attributes of a DataFrame:" }, { "code": null, "e": 1407, "s": 1097, "text": "df.head() # show first 5 rowsdf.tail() # last 5 rowsdf.columns # list all column namesdf.shape # get number of rows and columnsdf.info() # additional info about dataframedf.describe() # statistical description, only for numeric valuesdf['col_name'].value_counts(dropna=False) # count unique values in a column" }, { "code": null, "e": 1505, "s": 1407, "text": "The output of at least one of these will give us first clues where we want to start our cleaning." }, { "code": null, "e": 1637, "s": 1505, "text": "Another way to quickly check the data is by visualizing it. We use bar plots for discrete data counts and histogram for continuous." }, { "code": null, "e": 1711, "s": 1637, "text": "df['col_name'].plot('hist')df.boxplot(column='col_name1', by='col_name2')" }, { "code": null, "e": 1839, "s": 1711, "text": "Histogram and box plot can help to spot visually the outliers. The scatter plot shows relationship between 2 numeric variables." }, { "code": null, "e": 1883, "s": 1839, "text": "df.plot(kind='scatter', x='col1', y='col2')" }, { "code": null, "e": 2027, "s": 1883, "text": "Visualizing data can bring some unexpected results as it gives you a perspective of what’s going on in your dataset. Kind of view from the top." }, { "code": null, "e": 2473, "s": 2027, "text": "Tidy data is the data obtained as a result of a process called data tidying. It is one of the important cleaning processes during big data processing and is a recognized step in the practice of data science. Tidy data sets have structure and working with them is easy; they’re easy to manipulate, model and visualize. Tidy data sets main concept is to arrange data in a way that each variable is a column and each observation (or case) is a row." }, { "code": null, "e": 2634, "s": 2473, "text": "Tidy data provide standards and concepts for data cleaning, and with tidy data there’s no need to start from scratch and reinvent new methods for data cleaning." }, { "code": null, "e": 2651, "s": 2634, "text": "Characteristics:" }, { "code": null, "e": 2702, "s": 2651, "text": "Each variable you measure should be in one column." }, { "code": null, "e": 2776, "s": 2702, "text": "Each different observation of that variable should be in a different row." }, { "code": null, "e": 2831, "s": 2776, "text": "There should be one table for each “kind” of variable." }, { "code": null, "e": 2933, "s": 2831, "text": "If you have multiple tables, they should include a column in the table that allows them to be linked." }, { "code": null, "e": 2966, "s": 2933, "text": "(all these taken from Wikipedia)" }, { "code": null, "e": 3025, "s": 2966, "text": "To transform our data and make it tidy we can use melting." }, { "code": null, "e": 3063, "s": 3025, "text": "pd.melt() # transform columns to rows" }, { "code": null, "e": 3412, "s": 3063, "text": "There are two parameters you should be aware of: id_vars and value_vars. The id_vars represent the columns of the data you do not want to melt (i.e., keep it in its current shape), while the value_vars represent the columns you do wish to melt into rows. By default, if no value_vars are provided, all columns not set in the id_vars will be melted." }, { "code": null, "e": 3458, "s": 3412, "text": "new_df = pd.melt(df, id_vars = 'do not melt')" }, { "code": null, "e": 3696, "s": 3458, "text": "The opposite operation to melting is pivoting. Here we turn unique values into separate columns. We use it when we want to transform our data from analysis shape to reporting shape, from easy-machine-readable to easy-human-readable form." }, { "code": null, "e": 3754, "s": 3696, "text": "df.pivot(index='date', columns='element', values='value')" }, { "code": null, "e": 4022, "s": 3754, "text": "Although, this method cannot handle duplicate values. When this is a case we should use .pivot_table() that has an additional parameter — aggfunc, which will handle those duplicates based on a function we provide (sum, count, mean, min, max or user defined function)." }, { "code": null, "e": 4103, "s": 4022, "text": "df.pivot_table(index='date', columns='element', values='value', aggfunc=np.mean)" }, { "code": null, "e": 4456, "s": 4103, "text": "Sometimes we might have data stored incorrectly. For example, values for the gender groups that stored as ‘m014’, ‘f014’, ‘m1528’, ‘f1528’. You cannot tell it’s completely wrong, but it would be better to split these values into ‘gender’ and ‘age’ columns. To do this we use Python slicing sintaxis by accessing .str attribute of column of object type." }, { "code": null, "e": 4528, "s": 4456, "text": "df['gender'] = df.variable.str[0] df['age_group'] = df.variable.str[1:]" }, { "code": null, "e": 5073, "s": 4528, "text": "Also data might not come in one huge file and be separated into few different chunks, so we have to be able to concatenate all that data and clean it or clean the first sample and then apply the same process on remaining parts. To do this we can use pandas .concat method, which provided with the list of dataframes will concatenate them all. By default it will store the original indexes what will result in duplicate index values. To prevent this we have to reset index of a new dataframe by passing an additional parameter ignore_index=True." }, { "code": null, "e": 5129, "s": 5073, "text": "concatenated = pd.concat([df1, df2], ignore_index=True)" }, { "code": null, "e": 5622, "s": 5129, "text": "But what if we have thousands of files? It’ll be dumb to import them one by one, clean them and repeat it again. And we are not stupid, we know loops in Python. The only missing part is to find all those files for import. We can do this with glob library. So the process will be the following: write a pattern, save all files into a list, iterate over csv files, import each file and concatenate the dataframes into one. Doesn’t seem that difficult, but with the code sample it’s much better:" }, { "code": null, "e": 6072, "s": 5622, "text": "# Import necessary modulesimport globimport pandas as pd # Write the pattern: pattern pattern = '*.csv' # Save all file matches: csv_filescsv_files = glob.glob(pattern) # Create an empty list: framesframes = [] # Iterate over csv_files for csv in csv_files: # Read csv into a DataFrame: df df = pd.read_csv(csv) # Append df to frames frames.append(df)# Concatenate frames into a single DataFrame: final_dffinal_df = pd.concat(frames)" }, { "code": null, "e": 6602, "s": 6072, "text": "Merging is the same as SQL join operation. You combine two or more tables into one by key which is present in every table. There are three types of joins: one-to-one, one-many, many-to-many. In SQL this process is advanced, with a lot of options, modifications, where you have to explicitly specify what and how you want to join. Here, all is done for you by one function and the type of join will only depend on a data in a dataframe. If the column name to be used as a key is the same in both dataframes ‘on’ parameter is used." }, { "code": null, "e": 6683, "s": 6602, "text": "merged = pd.merge(left=df1, right=df2, on=None, left_on='col1', right_on='col2')" }, { "code": null, "e": 7091, "s": 6683, "text": "It is very important to have data with correct data types as later it may play a bad joke with you and your analysis. Remember how once I didn’t convert one column to the correct data type and spent 1 hour trying to subtract float from string :D. So be careful :D. That’s a typical error in data, which can be fixed with pd.to_numeric() and with errors=’coerce’ it will convert all the err values into NaNs." }, { "code": null, "e": 7383, "s": 7091, "text": "To convert data we can use .astype() method on a series. Also keep in mind the ‘category’ type — it reduces size of a dataframe and makes computations faster. We can convert to any value that can be used as category — days of the week, gender, continent abbreviations — depends on a context." }, { "code": null, "e": 7535, "s": 7383, "text": "df['column1'] = df['column1'].astype(str) df['column1'] = df['column1'].astype('category')df['column1'] = pd.to_numeric(df['column1'], errors='coerce')" }, { "code": null, "e": 7636, "s": 7535, "text": "Our favourite part, isn’t it? To drop duplicates we can use druuuuuuuuuums drop_duplicates() method." }, { "code": null, "e": 7662, "s": 7636, "text": "df = df.drop_duplicates()" }, { "code": null, "e": 7776, "s": 7662, "text": "With missing values it is little bit more complicated. In general there are three ways to deal with missing data:" }, { "code": null, "e": 7788, "s": 7776, "text": "leave as-is" }, { "code": null, "e": 7798, "s": 7788, "text": "drop them" }, { "code": null, "e": 7818, "s": 7798, "text": "fill missing values" }, { "code": null, "e": 7983, "s": 7818, "text": "To drop missing values we can use .dropna(), but careful with it — it may delete up to 50% of your data — which is not really good. But again, depends on a context." }, { "code": null, "e": 8119, "s": 7983, "text": "To fill missing values we use .fillna(), careful with it as well — if we fill missing values they have to be reasonable and make sense." }, { "code": null, "e": 8328, "s": 8119, "text": "There is a wonderful article on handling missing data and I really have nothing to add on this part. Here is the link and don’t forget to give an author a round of applause, because that work is just amazing." }, { "code": null, "e": 8463, "s": 8328, "text": "We can also programmatically check our data using assert statements. It will return nothing if the result is True and error otherwise." }, { "code": null, "e": 8617, "s": 8463, "text": "assert 1 == 1 # returns nothing assert 1 == 2 # returns errorassert df.notnull().all().all() # returns error if at least one column has one missing value" }, { "code": null, "e": 8845, "s": 8617, "text": "I skipped regular expressions as it deserves a separate article, but in general summarized tools I use for data preprocessing. Please, let me know if something else can be added, have a great day and use data science for good 🙂" } ]
Normal Equation in Python: The Closed-Form Solution for Linear Regression | by Suraj Verma | Towards Data Science
In this article, we will implement the Normal Equation which is the closed-form solution for the Linear Regression algorithm where we can find the optimal value of theta in just one step without using the Gradient Descent algorithm. We will first recap with Gradient Descent Algorithm, then talk about calculating theta using a formula called Normal Equation and finally, see the Normal Equation in Action and plot predictions for our randomly generated data. Machine Learning from scratch series — Part 1: Linear Regression from scratch in Python Part 2: Locally Weighted Linear Regression in Python Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression Part 4: Polynomial Regression From Scratch in Python medium.com towardsdatascience.com We have, X →Input data (Training Data) y →Target variable theta →The parameter y_hat →Prediction/hypothesis (dot product of theta and X). Loss Function →MSE loss or mean squared error loss (y_hat-y)2 m →the number of training examples. n →number of features First, we initialize the parameter theta randomly or with all zeros. Then, Calculate the prediction/hypothesis y_hat using the equation 1 above.Then use the prediction/hypothesis y_hat to calculate MSE loss like this — (y_hat-y)2.Then take the partial derivative(gradient) of the MSE loss with respect to the parameter theta .Finally use this partial derivative(gradient) to update the parameter theta like this — theta := theta -lr*gradient , where lr is the learning rate.Repeat steps 1 to 4 until we reach an optimal value for the parameter theta . Calculate the prediction/hypothesis y_hat using the equation 1 above. Then use the prediction/hypothesis y_hat to calculate MSE loss like this — (y_hat-y)2. Then take the partial derivative(gradient) of the MSE loss with respect to the parameter theta . Finally use this partial derivative(gradient) to update the parameter theta like this — theta := theta -lr*gradient , where lr is the learning rate. Repeat steps 1 to 4 until we reach an optimal value for the parameter theta . Gradient Descent is an iterative algorithm meaning that you need to take multiple steps to get to the Global optimum (to find the optimal parameters) but it turns out that for the special case of Linear Regression, there is a way to solve for the optimal values of the parameter theta to just jump in one step to the Global optimum without needing to use an iterative algorithm and this algorithm is called the Normal Equation. It works only for Linear Regression and not any other algorithm. Normal Equation is the Closed-form solution for the Linear Regression algorithm which means that we can obtain the optimal parameters by just using a formula that includes a few matrix multiplications and inversions. To calculate theta , we take the partial derivative of the MSE loss function (equation 2) with respect to theta and set it equal to zero. Then, do a little bit of linear algebra to get the value of theta. This is the Normal Equation — If you know about the matrix derivatives along with a few properties of matrices, you should be able to derive the Normal Equation for yourself. For reference — Derivation of the Normal Equation for linear regression You might think what if X is a non-invertible matrix, which usually happens if you have redundant features i.e your features are linearly dependent, probably because you have the same features repeated twice. One thing you can do is go and find out which features are repeated and fix them or you can use the np.pinv function in NumPy which will also give you the right answer. Calculate theta using the Normal Equation.Use the theta to make predictions. Calculate theta using the Normal Equation. Use the theta to make predictions. Check the shapes of X and y so that the equation matches up. Let’s take the following randomly generated data as a motivating example to understand the Normal Equation. import numpy as npnp.random.seed(42)X = np.random.randn(500,1)y = 2*X + 1 + 1.2*np.random.randn(500,1)X.shape, y.shape>>((500, 1), (500,)) Here, n =1 which means the matrix X has only 1 column and m =500 means X has 500 rows. X is a (500x1) matrix and y is a vector of length 500. Let’s write the code to calculate theta using the Normal Equation. See comments (#). def find_theta(X, y): m = X.shape[0] # Number of training examples. # Appending a cloumn of ones in X to add the bias term. X = np.append(X, np.ones((m,1)), axis=1) # reshaping y to (m,1) y = y.reshape(m,1) # The Normal Equation theta = np.dot(np.linalg.inv(np.dot(X.T, X)), np.dot(X.T, y)) return theta See comments (#). def predict(X): # Appending a cloumn of ones in X to add the bias term. X = np.append(X, np.ones((X.shape[0],1)), axis=1) # preds is y_hat which is the dot product of X and theta. preds = np.dot(X, theta) return preds See comments (#). # Getting the Value of theta using the find_theta function.theta = find_theta(X, y)theta>>array([[1.90949642], [1.0388102 ]]# Getting the predictions on X using the predict function.preds = predict(X)# Plotting the predictions.fig = plt.figure(figsize=(8,6))plt.plot(X, y, 'b.')plt.plot(X, preds, 'c-')plt.xlabel('X - Input')plt.ylabel('y - target / true') The cyan line shows the predictions for all the values of X . We found the optimal values of theta in just one step, and the theta we found is the Global Minimum of the MSE loss function for the given data. If the algorithm you want to use is Linear Regression and exactly Linear Regression and, If n (number of features) is small. If m (number of training examples) is small i.e. around 20,000. Normal Equation is a good algorithm to consider to build your machine learning model. For questions, comments, concerns, talk to me in the response section. More articles on ML from scratch are coming soon. Machine Learning from scratch series — Part 1: Linear Regression from scratch in Python Part 2: Locally Weighted Linear Regression in Python Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression Part 4: Polynomial Regression From Scratch in Python
[ { "code": null, "e": 405, "s": 172, "text": "In this article, we will implement the Normal Equation which is the closed-form solution for the Linear Regression algorithm where we can find the optimal value of theta in just one step without using the Gradient Descent algorithm." }, { "code": null, "e": 632, "s": 405, "text": "We will first recap with Gradient Descent Algorithm, then talk about calculating theta using a formula called Normal Equation and finally, see the Normal Equation in Action and plot predictions for our randomly generated data." }, { "code": null, "e": 671, "s": 632, "text": "Machine Learning from scratch series —" }, { "code": null, "e": 720, "s": 671, "text": "Part 1: Linear Regression from scratch in Python" }, { "code": null, "e": 773, "s": 720, "text": "Part 2: Locally Weighted Linear Regression in Python" }, { "code": null, "e": 858, "s": 773, "text": "Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression" }, { "code": null, "e": 911, "s": 858, "text": "Part 4: Polynomial Regression From Scratch in Python" }, { "code": null, "e": 922, "s": 911, "text": "medium.com" }, { "code": null, "e": 945, "s": 922, "text": "towardsdatascience.com" }, { "code": null, "e": 954, "s": 945, "text": "We have," }, { "code": null, "e": 984, "s": 954, "text": "X →Input data (Training Data)" }, { "code": null, "e": 1003, "s": 984, "text": "y →Target variable" }, { "code": null, "e": 1024, "s": 1003, "text": "theta →The parameter" }, { "code": null, "e": 1083, "s": 1024, "text": "y_hat →Prediction/hypothesis (dot product of theta and X)." }, { "code": null, "e": 1145, "s": 1083, "text": "Loss Function →MSE loss or mean squared error loss (y_hat-y)2" }, { "code": null, "e": 1181, "s": 1145, "text": "m →the number of training examples." }, { "code": null, "e": 1203, "s": 1181, "text": "n →number of features" }, { "code": null, "e": 1278, "s": 1203, "text": "First, we initialize the parameter theta randomly or with all zeros. Then," }, { "code": null, "e": 1755, "s": 1278, "text": "Calculate the prediction/hypothesis y_hat using the equation 1 above.Then use the prediction/hypothesis y_hat to calculate MSE loss like this — (y_hat-y)2.Then take the partial derivative(gradient) of the MSE loss with respect to the parameter theta .Finally use this partial derivative(gradient) to update the parameter theta like this — theta := theta -lr*gradient , where lr is the learning rate.Repeat steps 1 to 4 until we reach an optimal value for the parameter theta ." }, { "code": null, "e": 1825, "s": 1755, "text": "Calculate the prediction/hypothesis y_hat using the equation 1 above." }, { "code": null, "e": 1912, "s": 1825, "text": "Then use the prediction/hypothesis y_hat to calculate MSE loss like this — (y_hat-y)2." }, { "code": null, "e": 2009, "s": 1912, "text": "Then take the partial derivative(gradient) of the MSE loss with respect to the parameter theta ." }, { "code": null, "e": 2158, "s": 2009, "text": "Finally use this partial derivative(gradient) to update the parameter theta like this — theta := theta -lr*gradient , where lr is the learning rate." }, { "code": null, "e": 2236, "s": 2158, "text": "Repeat steps 1 to 4 until we reach an optimal value for the parameter theta ." }, { "code": null, "e": 2729, "s": 2236, "text": "Gradient Descent is an iterative algorithm meaning that you need to take multiple steps to get to the Global optimum (to find the optimal parameters) but it turns out that for the special case of Linear Regression, there is a way to solve for the optimal values of the parameter theta to just jump in one step to the Global optimum without needing to use an iterative algorithm and this algorithm is called the Normal Equation. It works only for Linear Regression and not any other algorithm." }, { "code": null, "e": 2946, "s": 2729, "text": "Normal Equation is the Closed-form solution for the Linear Regression algorithm which means that we can obtain the optimal parameters by just using a formula that includes a few matrix multiplications and inversions." }, { "code": null, "e": 3151, "s": 2946, "text": "To calculate theta , we take the partial derivative of the MSE loss function (equation 2) with respect to theta and set it equal to zero. Then, do a little bit of linear algebra to get the value of theta." }, { "code": null, "e": 3181, "s": 3151, "text": "This is the Normal Equation —" }, { "code": null, "e": 3326, "s": 3181, "text": "If you know about the matrix derivatives along with a few properties of matrices, you should be able to derive the Normal Equation for yourself." }, { "code": null, "e": 3398, "s": 3326, "text": "For reference — Derivation of the Normal Equation for linear regression" }, { "code": null, "e": 3776, "s": 3398, "text": "You might think what if X is a non-invertible matrix, which usually happens if you have redundant features i.e your features are linearly dependent, probably because you have the same features repeated twice. One thing you can do is go and find out which features are repeated and fix them or you can use the np.pinv function in NumPy which will also give you the right answer." }, { "code": null, "e": 3853, "s": 3776, "text": "Calculate theta using the Normal Equation.Use the theta to make predictions." }, { "code": null, "e": 3896, "s": 3853, "text": "Calculate theta using the Normal Equation." }, { "code": null, "e": 3931, "s": 3896, "text": "Use the theta to make predictions." }, { "code": null, "e": 3992, "s": 3931, "text": "Check the shapes of X and y so that the equation matches up." }, { "code": null, "e": 4100, "s": 3992, "text": "Let’s take the following randomly generated data as a motivating example to understand the Normal Equation." }, { "code": null, "e": 4239, "s": 4100, "text": "import numpy as npnp.random.seed(42)X = np.random.randn(500,1)y = 2*X + 1 + 1.2*np.random.randn(500,1)X.shape, y.shape>>((500, 1), (500,))" }, { "code": null, "e": 4381, "s": 4239, "text": "Here, n =1 which means the matrix X has only 1 column and m =500 means X has 500 rows. X is a (500x1) matrix and y is a vector of length 500." }, { "code": null, "e": 4448, "s": 4381, "text": "Let’s write the code to calculate theta using the Normal Equation." }, { "code": null, "e": 4466, "s": 4448, "text": "See comments (#)." }, { "code": null, "e": 4811, "s": 4466, "text": "def find_theta(X, y): m = X.shape[0] # Number of training examples. # Appending a cloumn of ones in X to add the bias term. X = np.append(X, np.ones((m,1)), axis=1) # reshaping y to (m,1) y = y.reshape(m,1) # The Normal Equation theta = np.dot(np.linalg.inv(np.dot(X.T, X)), np.dot(X.T, y)) return theta" }, { "code": null, "e": 4829, "s": 4811, "text": "See comments (#)." }, { "code": null, "e": 5074, "s": 4829, "text": "def predict(X): # Appending a cloumn of ones in X to add the bias term. X = np.append(X, np.ones((X.shape[0],1)), axis=1) # preds is y_hat which is the dot product of X and theta. preds = np.dot(X, theta) return preds" }, { "code": null, "e": 5092, "s": 5074, "text": "See comments (#)." }, { "code": null, "e": 5456, "s": 5092, "text": "# Getting the Value of theta using the find_theta function.theta = find_theta(X, y)theta>>array([[1.90949642], [1.0388102 ]]# Getting the predictions on X using the predict function.preds = predict(X)# Plotting the predictions.fig = plt.figure(figsize=(8,6))plt.plot(X, y, 'b.')plt.plot(X, preds, 'c-')plt.xlabel('X - Input')plt.ylabel('y - target / true')" }, { "code": null, "e": 5518, "s": 5456, "text": "The cyan line shows the predictions for all the values of X ." }, { "code": null, "e": 5663, "s": 5518, "text": "We found the optimal values of theta in just one step, and the theta we found is the Global Minimum of the MSE loss function for the given data." }, { "code": null, "e": 5752, "s": 5663, "text": "If the algorithm you want to use is Linear Regression and exactly Linear Regression and," }, { "code": null, "e": 5788, "s": 5752, "text": "If n (number of features) is small." }, { "code": null, "e": 5852, "s": 5788, "text": "If m (number of training examples) is small i.e. around 20,000." }, { "code": null, "e": 5938, "s": 5852, "text": "Normal Equation is a good algorithm to consider to build your machine learning model." }, { "code": null, "e": 6059, "s": 5938, "text": "For questions, comments, concerns, talk to me in the response section. More articles on ML from scratch are coming soon." }, { "code": null, "e": 6098, "s": 6059, "text": "Machine Learning from scratch series —" }, { "code": null, "e": 6147, "s": 6098, "text": "Part 1: Linear Regression from scratch in Python" }, { "code": null, "e": 6200, "s": 6147, "text": "Part 2: Locally Weighted Linear Regression in Python" }, { "code": null, "e": 6285, "s": 6200, "text": "Part 3: Normal Equation Using Python: The Closed-Form Solution for Linear Regression" } ]
JavaScript | Date - GeeksforGeeks
12 Oct, 2021 The Date object in JavaScript is used to represent a moment of time. This time value is since 1 January 1970 UTC (Coordinated Universal Time). We can create a date using the Date object by calling the new Date() constructor as shown in the below syntax.Syntax: new Date(); new Date(value); new Date(dateString); new Date(year, month, day, hours, minutes, seconds, milliseconds); Parameters: All of the parameters as shown in the above syntax are described below: value : This value is the number of milliseconds since January 1, 1970, 00:00:00 UTC. dateString : This represents a date format. year : This is represented by integer values which ranging from years 1900 to 1999. month : This is represented by integer values which ranging from 0 for January to 11 for December. day : This is an optional parameter. This is represented by integer value for the day of the month. hours : This is optional. This is represented by integer value for the hour of the day. minutes : This is optional. This is represented by integer value for the minute of a time. seconds : This is optional. This is represented by integer value for the second of a time. milliseconds : This is optional. This is represented by integer value for the millisecond of a time. Return Values: It returns the present date and time if nothing as the parameter is given otherwise it return the date format and time in which parameter is given.Let’s see JavaScript programs on Date object. Example 1: If nothing as the parameter is given, it returns present date and time. javascript <script> // If nothing as parameter is given, // it represent the present date and time. var A = new Date(); // Printing present date and time. document.write(A);</script> Output: Wed Mar 21 2018 20:44:40 GMT+0530 (India Standard Time) Example 2: When any integer value is taken as the parameter then it given the number of milliseconds since January 1, 1970, 00:00:00 UTC. javascript <script> // Parameter as integer value give the number of // milliseconds since January 1, 1970, 00:00:00 UTC. var A = new Date(32549); document.write(A);</script> Output: Thu Jan 01 1970 05:30:32 GMT+0530 (India Standard Time) Example 3: When any dataString is given as the parameter then it return the same as the parameter including day name. javascript <script> // When any dataString is given as the parameter // then it return the same as the parameter // including day name. var A = new Date('June 22, 1985 07:19:35'); document.write(A);</script> Output: Sat Jun 22 1985 07:19:35 GMT+0530 (India Standard Time) Example 4: When some numbers are taken as the parameter then they are considered as year, month, day, hours, minutes, seconds, milliseconds respectively. javascript <script> // When some numbers are taken as the parameter // then they are considered as year, month, day, // hours, minutes, seconds, milliseconds // respectively. var A = new Date(1996, 10, 13, 5, 30, 22); document.write(A);</script> Output: Wed Nov 13 1996 05:30:22 GMT+0530 (India Standard Time) Errors and Exceptions: To check this you have to check in console. Example 1: Any integer number should be taken as the parameter not any name otherwise it gives error. javascript <script> // Any integer number should be taken // as the parameter not any name. var A = new Date(gfg); document.write(A);</script> Output: Error: gfg is not defined example 2: Any integer number should be take as the parameter not any other number e.g- complex number. javascript <script> // Any integer number should be take as // the parameter not any other number // e.g- complex number. var A = new Date(1 + 5i); document.write(A);</script> Output: Error: Invalid or unexpected token Example 3: Any integer number should be take as the parameter not any other number e.g- complex number. javascript <script> // Any integer number should be taken // as the dateString not word. var A = new Date("geeksforgeeks"); document.write(A);</script> Output: Invalid Date Application: It has many application such as for getting the exact current date and time. Below program prints the current date and time using the Date() object. javascript <script> // If nothing as parameter is given, it // represent the present date and time. var A = new Date(); // Printing present date and time. document.write(A);</script> Output: Wed Mar 21 2018 20:44:40 GMT+0530 (India Standard Time) Supported Browsers: The browsers supported by JavaScript Date are listed below: Google Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 3 and above Opera 3 and above Safari 1 and above ysachin2314 javascript-date javascript-functions JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Hide or show elements in HTML using display property JavaScript | console.log() with Examples How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 29667, "s": 29639, "text": "\n12 Oct, 2021" }, { "code": null, "e": 29930, "s": 29667, "text": "The Date object in JavaScript is used to represent a moment of time. This time value is since 1 January 1970 UTC (Coordinated Universal Time). We can create a date using the Date object by calling the new Date() constructor as shown in the below syntax.Syntax: " }, { "code": null, "e": 30048, "s": 29930, "text": "new Date();\nnew Date(value);\nnew Date(dateString);\nnew Date(year, month, day, hours, minutes, seconds, milliseconds);" }, { "code": null, "e": 30134, "s": 30048, "text": "Parameters: All of the parameters as shown in the above syntax are described below: " }, { "code": null, "e": 30220, "s": 30134, "text": "value : This value is the number of milliseconds since January 1, 1970, 00:00:00 UTC." }, { "code": null, "e": 30264, "s": 30220, "text": "dateString : This represents a date format." }, { "code": null, "e": 30348, "s": 30264, "text": "year : This is represented by integer values which ranging from years 1900 to 1999." }, { "code": null, "e": 30447, "s": 30348, "text": "month : This is represented by integer values which ranging from 0 for January to 11 for December." }, { "code": null, "e": 30547, "s": 30447, "text": "day : This is an optional parameter. This is represented by integer value for the day of the month." }, { "code": null, "e": 30635, "s": 30547, "text": "hours : This is optional. This is represented by integer value for the hour of the day." }, { "code": null, "e": 30726, "s": 30635, "text": "minutes : This is optional. This is represented by integer value for the minute of a time." }, { "code": null, "e": 30817, "s": 30726, "text": "seconds : This is optional. This is represented by integer value for the second of a time." }, { "code": null, "e": 30918, "s": 30817, "text": "milliseconds : This is optional. This is represented by integer value for the millisecond of a time." }, { "code": null, "e": 31128, "s": 30918, "text": "Return Values: It returns the present date and time if nothing as the parameter is given otherwise it return the date format and time in which parameter is given.Let’s see JavaScript programs on Date object. " }, { "code": null, "e": 31213, "s": 31128, "text": "Example 1: If nothing as the parameter is given, it returns present date and time. " }, { "code": null, "e": 31224, "s": 31213, "text": "javascript" }, { "code": "<script> // If nothing as parameter is given, // it represent the present date and time. var A = new Date(); // Printing present date and time. document.write(A);</script>", "e": 31402, "s": 31224, "text": null }, { "code": null, "e": 31412, "s": 31402, "text": "Output: " }, { "code": null, "e": 31468, "s": 31412, "text": "Wed Mar 21 2018 20:44:40 GMT+0530 (India Standard Time)" }, { "code": null, "e": 31608, "s": 31468, "text": "Example 2: When any integer value is taken as the parameter then it given the number of milliseconds since January 1, 1970, 00:00:00 UTC. " }, { "code": null, "e": 31619, "s": 31608, "text": "javascript" }, { "code": "<script> // Parameter as integer value give the number of // milliseconds since January 1, 1970, 00:00:00 UTC. var A = new Date(32549); document.write(A);</script>", "e": 31788, "s": 31619, "text": null }, { "code": null, "e": 31798, "s": 31788, "text": "Output: " }, { "code": null, "e": 31854, "s": 31798, "text": "Thu Jan 01 1970 05:30:32 GMT+0530 (India Standard Time)" }, { "code": null, "e": 31974, "s": 31854, "text": "Example 3: When any dataString is given as the parameter then it return the same as the parameter including day name. " }, { "code": null, "e": 31985, "s": 31974, "text": "javascript" }, { "code": "<script> // When any dataString is given as the parameter // then it return the same as the parameter // including day name. var A = new Date('June 22, 1985 07:19:35'); document.write(A);</script>", "e": 32188, "s": 31985, "text": null }, { "code": null, "e": 32198, "s": 32188, "text": "Output: " }, { "code": null, "e": 32254, "s": 32198, "text": "Sat Jun 22 1985 07:19:35 GMT+0530 (India Standard Time)" }, { "code": null, "e": 32410, "s": 32254, "text": "Example 4: When some numbers are taken as the parameter then they are considered as year, month, day, hours, minutes, seconds, milliseconds respectively. " }, { "code": null, "e": 32421, "s": 32410, "text": "javascript" }, { "code": "<script> // When some numbers are taken as the parameter // then they are considered as year, month, day, // hours, minutes, seconds, milliseconds // respectively. var A = new Date(1996, 10, 13, 5, 30, 22); document.write(A);</script>", "e": 32663, "s": 32421, "text": null }, { "code": null, "e": 32673, "s": 32663, "text": "Output: " }, { "code": null, "e": 32729, "s": 32673, "text": "Wed Nov 13 1996 05:30:22 GMT+0530 (India Standard Time)" }, { "code": null, "e": 32798, "s": 32729, "text": "Errors and Exceptions: To check this you have to check in console. " }, { "code": null, "e": 32901, "s": 32798, "text": "Example 1: Any integer number should be taken as the parameter not any name otherwise it gives error. " }, { "code": null, "e": 32912, "s": 32901, "text": "javascript" }, { "code": "<script> // Any integer number should be taken // as the parameter not any name. var A = new Date(gfg); document.write(A);</script>", "e": 33049, "s": 32912, "text": null }, { "code": null, "e": 33059, "s": 33049, "text": "Output: " }, { "code": null, "e": 33085, "s": 33059, "text": "Error: gfg is not defined" }, { "code": null, "e": 33191, "s": 33085, "text": "example 2: Any integer number should be take as the parameter not any other number e.g- complex number. " }, { "code": null, "e": 33202, "s": 33191, "text": "javascript" }, { "code": "<script> // Any integer number should be take as // the parameter not any other number // e.g- complex number. var A = new Date(1 + 5i); document.write(A);</script>", "e": 33373, "s": 33202, "text": null }, { "code": null, "e": 33383, "s": 33373, "text": "Output: " }, { "code": null, "e": 33418, "s": 33383, "text": "Error: Invalid or unexpected token" }, { "code": null, "e": 33524, "s": 33418, "text": "Example 3: Any integer number should be take as the parameter not any other number e.g- complex number. " }, { "code": null, "e": 33535, "s": 33524, "text": "javascript" }, { "code": "<script> // Any integer number should be taken // as the dateString not word. var A = new Date(\"geeksforgeeks\"); document.write(A);</script>", "e": 33682, "s": 33535, "text": null }, { "code": null, "e": 33692, "s": 33682, "text": "Output: " }, { "code": null, "e": 33705, "s": 33692, "text": "Invalid Date" }, { "code": null, "e": 33869, "s": 33705, "text": "Application: It has many application such as for getting the exact current date and time. Below program prints the current date and time using the Date() object. " }, { "code": null, "e": 33880, "s": 33869, "text": "javascript" }, { "code": "<script> // If nothing as parameter is given, it // represent the present date and time. var A = new Date(); // Printing present date and time. document.write(A);</script>", "e": 34058, "s": 33880, "text": null }, { "code": null, "e": 34068, "s": 34058, "text": "Output: " }, { "code": null, "e": 34124, "s": 34068, "text": "Wed Mar 21 2018 20:44:40 GMT+0530 (India Standard Time)" }, { "code": null, "e": 34206, "s": 34124, "text": "Supported Browsers: The browsers supported by JavaScript Date are listed below: " }, { "code": null, "e": 34232, "s": 34206, "text": "Google Chrome 1 and above" }, { "code": null, "e": 34250, "s": 34232, "text": "Edge 12 and above" }, { "code": null, "e": 34270, "s": 34250, "text": "Firefox 1 and above" }, { "code": null, "e": 34300, "s": 34270, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 34318, "s": 34300, "text": "Opera 3 and above" }, { "code": null, "e": 34337, "s": 34318, "text": "Safari 1 and above" }, { "code": null, "e": 34351, "s": 34339, "text": "ysachin2314" }, { "code": null, "e": 34367, "s": 34351, "text": "javascript-date" }, { "code": null, "e": 34388, "s": 34367, "text": "javascript-functions" }, { "code": null, "e": 34399, "s": 34388, "text": "JavaScript" }, { "code": null, "e": 34497, "s": 34399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34506, "s": 34497, "text": "Comments" }, { "code": null, "e": 34519, "s": 34506, "text": "Old Comments" }, { "code": null, "e": 34580, "s": 34519, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34625, "s": 34580, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34697, "s": 34625, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34766, "s": 34697, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 34793, "s": 34766, "text": "File uploading in React.js" }, { "code": null, "e": 34845, "s": 34793, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 34891, "s": 34845, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 34944, "s": 34891, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 34985, "s": 34944, "text": "JavaScript | console.log() with Examples" } ]
How to wait until an element no longer exists in Selenium?
We can wait until an element no longer exists in Selenium webdriver. This can be achieved with synchronization in Selenium. We shall add an explicit wait criteria where we shall stop or wait till the element no longer exists. Timeout exception is thrown once the explicit wait time has elapsed and the expected behavior of the element is still not available on the page. To check if an element no longer exists on the page, we can take the help of the expected condition invisibilityOfElementLocated. To implement explicit wait conditions, we have to take help of the WebDriverWait and ExpectedCondition class. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class ElementInvisibleWait{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); // identify element and click() driver.findElement(By.xpath("//*[text()='Library']")).click(); // explicit wait of invisibility condition WebDriverWait w = new WebDriverWait(driver,5); // invisibilityOfElementLocated condition w.until(ExpectedConditions. invisibilityOfElementLocated(By.xpath("//*[@class='mui-btn']"))); // get page title of next page System.out.println("Page title after click:" + driver.getTitle()); driver.close() } }
[ { "code": null, "e": 1288, "s": 1062, "text": "We can wait until an element no longer exists in Selenium webdriver. This can be achieved with synchronization in Selenium. We shall add an explicit wait criteria where we shall stop or wait till the element no longer exists." }, { "code": null, "e": 1563, "s": 1288, "text": "Timeout exception is thrown once the explicit wait time has elapsed and the expected behavior of the element is still not available on the page. To check if an element no longer exists on the page, we can take the help of the expected condition invisibilityOfElementLocated." }, { "code": null, "e": 1673, "s": 1563, "text": "To implement explicit wait conditions, we have to take help of the WebDriverWait and ExpectedCondition class." }, { "code": null, "e": 1694, "s": 1673, "text": "Code Implementation." }, { "code": null, "e": 2864, "s": 1694, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\nimport org.openqa.selenium.support.ui.WebDriverWait;\npublic class ElementInvisibleWait{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);\n // identify element and click()\n driver.findElement(By.xpath(\"//*[text()='Library']\")).click();\n // explicit wait of invisibility condition\n WebDriverWait w = new WebDriverWait(driver,5);\n // invisibilityOfElementLocated condition\n w.until(ExpectedConditions.\n invisibilityOfElementLocated(By.xpath(\"//*[@class='mui-btn']\")));\n // get page title of next page\n System.out.println(\"Page title after click:\" + driver.getTitle());\n driver.close()\n }\n}" } ]
Next.js - Environment Variables
Next.js, has support for publishing environment variables in node which we can use in connecting to server, database etc. For this, we need to create .env.local file in root directory. We can also create .env.production. Create .env.local in root directory with the following contents. DB_HOST=localhost DB_USER=tutorialspoint DB_PASS=nextjs Create a page named env.js with following contents in pages/posts directory where we'll use the environment variables using process.env. import Head from 'next/head' import Container from '../../components/container' export default function FirstPost(props) { return ( <> <Container> <Head> <title>Environment Variables</title> </Head> <h1>Database Credentials</h1> <p>Host: {props.host}</p> <p>Username: {props.username}</p> <p>Password: {props.password}</p> </Container> </> ) } export async function getStaticProps() { // Connect to Database using DB properties return { props: { host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS } } } Now start the server. Next.JS will detect .env.local and show follwing message on console. npm run dev > nextjs@1.0.0 dev D:\Node\nextjs > next ready - started server on http://localhost:3000 info - Loaded env from D:\Node\nextjs\.env.local event - compiled successfully wait - compiling... event - compiled successfully event - build page: /posts/env wait - compiling... event - compiled successfully Open localhost:3000/posts/env in a browser and you will see the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2328, "s": 2107, "text": "Next.js, has support for publishing environment variables in node which we can use in connecting to server, database etc. For this, we need to create .env.local file in root directory. We can also create .env.production." }, { "code": null, "e": 2393, "s": 2328, "text": "Create .env.local in root directory with the following contents." }, { "code": null, "e": 2450, "s": 2393, "text": "DB_HOST=localhost\nDB_USER=tutorialspoint\nDB_PASS=nextjs\n" }, { "code": null, "e": 2587, "s": 2450, "text": "Create a page named env.js with following contents in pages/posts directory where we'll use the environment variables using process.env." }, { "code": null, "e": 3313, "s": 2587, "text": "import Head from 'next/head'\nimport Container from '../../components/container'\n\nexport default function FirstPost(props) {\n return (\n <>\n <Container>\n <Head>\n <title>Environment Variables</title>\n </Head>\n <h1>Database Credentials</h1>\n <p>Host: {props.host}</p>\n <p>Username: {props.username}</p>\n <p>Password: {props.password}</p>\n </Container>\n </>\t \n )\n}\n\nexport async function getStaticProps() {\n // Connect to Database using DB properties\n return {\n props: { \n host: process.env.DB_HOST,\n username: process.env.DB_USER,\n password: process.env.DB_PASS\n }\n }\n}" }, { "code": null, "e": 3336, "s": 3313, "text": " Now start the server." }, { "code": null, "e": 3405, "s": 3336, "text": "Next.JS will detect .env.local and show follwing message on console." }, { "code": null, "e": 3722, "s": 3405, "text": "npm run dev\n\n> nextjs@1.0.0 dev D:\\Node\\nextjs\n> next\n\nready - started server on http://localhost:3000\ninfo - Loaded env from D:\\Node\\nextjs\\.env.local\nevent - compiled successfully\nwait - compiling...\nevent - compiled successfully\nevent - build page: /posts/env\nwait - compiling...\nevent - compiled successfully\n" }, { "code": null, "e": 3804, "s": 3722, "text": "Open localhost:3000/posts/env in a browser and you will see the following output." }, { "code": null, "e": 3811, "s": 3804, "text": " Print" }, { "code": null, "e": 3822, "s": 3811, "text": " Add Notes" } ]
How to read data from a file using FileInputStream?
The FileInputStream class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images. To read the contents of a file using this class − First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read. FileInputStream inputStream = new FileInputStream("file_path"); or, File file = new File("file_path"); FileInputStream inputStream = new FileInputStream(file); Then read the contents of the specified file using either of the variants of read() method −int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached.int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached. int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format). This method returns -1 if the end of the file is reached. int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array. This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array. This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. Assume we have the following image in the directory D:/images Following program reads contents of the above image using the FileInputStream. import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FileInputStreamExample { public static void main(String args[]) throws IOException { //Creating a File object File file = new File("D:/images/javafx.jpg"); //Creating a FileInputStream object FileInputStream inputStream = new FileInputStream(file); //Creating a byte array byte bytes[] = new byte[(int) file.length()]; //Reading data into the byte array int numOfBytes = inputStream.read(bytes); System.out.println("Data copied successfully..."); } } Data copied successfully...
[ { "code": null, "e": 1222, "s": 1062, "text": "The FileInputStream class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images." }, { "code": null, "e": 1272, "s": 1222, "text": "To read the contents of a file using this class −" }, { "code": null, "e": 1414, "s": 1272, "text": "First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read." }, { "code": null, "e": 1574, "s": 1414, "text": "FileInputStream inputStream = new FileInputStream(\"file_path\");\nor,\nFile file = new File(\"file_path\");\nFileInputStream inputStream = new FileInputStream(file);" }, { "code": null, "e": 2403, "s": 1574, "text": "Then read the contents of the specified file using either of the variants of read() method −int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached.int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 2585, "s": 2403, "text": "int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached." }, { "code": null, "e": 2710, "s": 2585, "text": "int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format)." }, { "code": null, "e": 2768, "s": 2710, "text": "This method returns -1 if the end of the file is reached." }, { "code": null, "e": 3017, "s": 2768, "text": "int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 3155, "s": 3017, "text": "int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array." }, { "code": null, "e": 3267, "s": 3155, "text": "This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 3464, "s": 3267, "text": "int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array." }, { "code": null, "e": 3576, "s": 3464, "text": "This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 3638, "s": 3576, "text": "Assume we have the following image in the directory D:/images" }, { "code": null, "e": 3717, "s": 3638, "text": "Following program reads contents of the above image using the FileInputStream." }, { "code": null, "e": 4322, "s": 3717, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\npublic class FileInputStreamExample {\n public static void main(String args[]) throws IOException {\n //Creating a File object\n File file = new File(\"D:/images/javafx.jpg\");\n //Creating a FileInputStream object\n FileInputStream inputStream = new FileInputStream(file);\n //Creating a byte array\n byte bytes[] = new byte[(int) file.length()];\n //Reading data into the byte array\n int numOfBytes = inputStream.read(bytes);\n System.out.println(\"Data copied successfully...\");\n }\n}" }, { "code": null, "e": 4350, "s": 4322, "text": "Data copied successfully..." } ]
Ionic - Lists
Lists are one of the most popular elements of any web or mobile application. They are usually used for displaying various information. They can be combined with other HTML elements to create different menus, tabs or to break the monotony of pure text files. Ionic framework offers different list types to make their usage easy. Every list is created with two elements. When you want to create a basic list your <ul> tag needs to have the list class assigned, and your <li> tag will use the item class. Another interesting thing is that you do not even need to use <ul>, <ol> and <li> tags for your lists. You can use any other elements, but the important thing is to add list and item classes appropriately. <div class = "list"> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> </div> The above code will produce the following screen − When you need a list to fill your own container, you can add the list-insets after your list class. This will add some margin to it and it will adjust the list size to your container. <div class = "list list-inset"> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> </div> The above code will produce the following screen − Dividers are used for organizing some elements into logical groups. Ionic gives us item-divider class for this. Again, like with all the other Ionic elements, we just need to add the item-divider class after the item class. Item dividers are useful as a list header, since they have stronger styling than the other list items by default. <div class = "list"> <div class = "item item-divider">Item Divider 1</div> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> <div class = "item item-divider">Item Divider 2</div> <div class = "item">Item 4</div> <div class = "item">Item 5</div> <div class = "item">Item 6</div> </div> The above code will produce the following screen − We already showed you how to add icons to your buttons. When adding icons to the list items, you need to choose what side you want to place them. There are item-icon-left and item-icon-right classes for this. You can also combine those two classes, if you want to have your Icons on both the sides. Finally, there is the item-note class to add a text note to your item. <div class = "list"> <div class = "item item-icon-left"> <i class = "icon ion-home"></i> Left side Icon </div> <div class = "item item-icon-right"> <i class = "icon ion-star"></i> Right side Icon </div> <div class = "item item-icon-left item-icon-right"> <i class = "icon ion-home"></i> <i class = "icon ion-star"></i> Both sides Icons </div> <div class = "item item-icon-left"> <i class = "icon ion-home"></i> <span class = "text-note">Text note</span> </div> </div> The above code will produce the following screen − Avatars and thumbnails are similar. The main difference is that avatars are smaller than thumbnails. These thumbnails are covering most of the full height of the list item, while avatars are medium sized circle images. The classes that are used are item-avatar and item-thumbnail. You can also choose which side you want to place your avatars and thumbnails as shown in the thumbnail code example below. <div class = "list"> <div class = "item item-avatar"> <img src = "my-image.png"> <h3>Avatar</h3> </div> <div class = "item item-thumbnail-left"> <img src = "my-image.png"> <h3>Thumbnail</h3> </div> </div> The above code will produce the following screen − 16 Lectures 2.5 hours Frahaan Hussain 185 Lectures 46.5 hours Nikhil Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2791, "s": 2463, "text": "Lists are one of the most popular elements of any web or mobile application. They are usually used for displaying various information. They can be combined with other HTML elements to create different menus, tabs or to break the monotony of pure text files. Ionic framework offers different list types to make their usage easy." }, { "code": null, "e": 3171, "s": 2791, "text": "Every list is created with two elements. When you want to create a basic list your <ul> tag needs to have the list class assigned, and your <li> tag will use the item class. Another interesting thing is that you do not even need to use <ul>, <ol> and <li> tags for your lists. You can use any other elements, but the important thing is to add list and item classes appropriately." }, { "code": null, "e": 3307, "s": 3171, "text": "<div class = \"list\">\n <div class = \"item\">Item 1</div>\n <div class = \"item\">Item 2</div>\n <div class = \"item\">Item 3</div>\n</div>" }, { "code": null, "e": 3358, "s": 3307, "text": "The above code will produce the following screen −" }, { "code": null, "e": 3542, "s": 3358, "text": "When you need a list to fill your own container, you can add the list-insets after your list class. This will add some margin to it and it will adjust the list size to your container." }, { "code": null, "e": 3689, "s": 3542, "text": "<div class = \"list list-inset\">\n <div class = \"item\">Item 1</div>\n <div class = \"item\">Item 2</div>\n <div class = \"item\">Item 3</div>\n</div>" }, { "code": null, "e": 3740, "s": 3689, "text": "The above code will produce the following screen −" }, { "code": null, "e": 4078, "s": 3740, "text": "Dividers are used for organizing some elements into logical groups. Ionic gives us item-divider class for this. Again, like with all the other Ionic elements, we just need to add the item-divider class after the item class. Item dividers are useful as a list header, since they have stronger styling than the other list items by default." }, { "code": null, "e": 4437, "s": 4078, "text": "<div class = \"list\">\n <div class = \"item item-divider\">Item Divider 1</div>\n <div class = \"item\">Item 1</div>\n <div class = \"item\">Item 2</div>\n <div class = \"item\">Item 3</div>\n\n <div class = \"item item-divider\">Item Divider 2</div>\n <div class = \"item\">Item 4</div>\n <div class = \"item\">Item 5</div>\n <div class = \"item\">Item 6</div>\n</div>" }, { "code": null, "e": 4488, "s": 4437, "text": "The above code will produce the following screen −" }, { "code": null, "e": 4858, "s": 4488, "text": "We already showed you how to add icons to your buttons. When adding icons to the list items, you need to choose what side you want to place them. There are item-icon-left and item-icon-right classes for this. You can also combine those two classes, if you want to have your Icons on both the sides. Finally, there is the item-note class to add a text note to your item." }, { "code": null, "e": 5410, "s": 4858, "text": "<div class = \"list\">\n <div class = \"item item-icon-left\">\n <i class = \"icon ion-home\"></i>\n Left side Icon\n </div>\n\n <div class = \"item item-icon-right\">\n <i class = \"icon ion-star\"></i>\n Right side Icon\n </div>\n\n <div class = \"item item-icon-left item-icon-right\">\n <i class = \"icon ion-home\"></i>\n <i class = \"icon ion-star\"></i>\n Both sides Icons\n </div>\n \n <div class = \"item item-icon-left\">\n <i class = \"icon ion-home\"></i>\n <span class = \"text-note\">Text note</span>\n </div>\n</div>" }, { "code": null, "e": 5461, "s": 5410, "text": "The above code will produce the following screen −" }, { "code": null, "e": 5865, "s": 5461, "text": "Avatars and thumbnails are similar. The main difference is that avatars are smaller than thumbnails. These thumbnails are covering most of the full height of the list item, while avatars are medium sized circle images. The classes that are used are item-avatar and item-thumbnail. You can also choose which side you want to place your avatars and thumbnails as shown in the thumbnail code example below." }, { "code": null, "e": 6107, "s": 5865, "text": "<div class = \"list\">\n <div class = \"item item-avatar\">\n <img src = \"my-image.png\">\n <h3>Avatar</h3>\n </div>\n\n <div class = \"item item-thumbnail-left\">\n <img src = \"my-image.png\">\n <h3>Thumbnail</h3>\n </div>\n</div>" }, { "code": null, "e": 6158, "s": 6107, "text": "The above code will produce the following screen −" }, { "code": null, "e": 6193, "s": 6158, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6210, "s": 6193, "text": " Frahaan Hussain" }, { "code": null, "e": 6247, "s": 6210, "text": "\n 185 Lectures \n 46.5 hours \n" }, { "code": null, "e": 6263, "s": 6247, "text": " Nikhil Agarwal" }, { "code": null, "e": 6270, "s": 6263, "text": " Print" }, { "code": null, "e": 6281, "s": 6270, "text": " Add Notes" } ]
GOCC15: Google's Online Challenge for Internship (India) - GeeksforGeeks
22 Jul, 2021 I came to know about the opportunity through https://careers.google.com/jobs/results/ Google’s website. Applied for the same with my resume. After two weeks got a mail Invite participating in the coding round. The mail had a unique ID and got the passkey(for login) on the day of the coding round1 (29th Aug 2020). The slot was open from 15:00 to 17:00 IST. A coding round was conducted on the HackerEarth platform. The test duration was 60 minutes consisting of two coding questions, every 30 points. I partially solved 2nd one, the solution didn’t suffice for test cases with large inputs. A Special String: You are given a string S consisting of lowercase Latin alphabets a-z. Find the minimum number of characters that must be changed to make S special. A string S is said to be special if and only if for all (S[i], S[j] ) where (1 ≤ I ≤ N/2) and (N/2 + 1 ≤ j ≤ N) one of the following conditions is true S[i] > S[j] S[i] < S[j] S[i] = S[j] S[i] represents the ith character of string S (1 based Indexing ). Input Format: The first line contains an integer T denoting the number of test cases. The first line of each test case contains an integer N denoting the length of S. The second line of each test case contains a string S. Output format: Print an integer denoting the minimum number of changes required for each test case in a new line. Constraints 1 ≤ T ≤ 5 1 ≤ N ≤ 103 N is even Example : Input: 1 6 aababc Output: 2 Explanation: Change S[4] = ‘d’ (1 based indexing) Change S[5] = ‘d’ New string = ‘aabddc’ Now all pair (S[i],S[j]) satisfy the second condition, S[i] < S[j] Generating Sequence: You are given two strings A of length N and B of length M. These strings contain lowercase English alphabets. You are also given an integer K. You can change the character of x in string A to any other character y. The cost of this conversion is abs( ASCII(x)- ASCII(y) ). Find the minimum cost required such that the length of the longest common subsequence (LCS) of A and B is at least K. Note: A subsequence of A string can be obtained by deleting zero or more characters in A. The longest common subsequence of two strings of A and B is a subsequence of A and B and has the maximum length among all strings that are a subsequence of A and B that would be multiple subsequences for two provided strings for example an LCS of vera and eats is ea. Input Format: The first line contains an integer T denoting the number of test cases for each test case. The first line of each test case contains three space-separated integers N, M, and K. The next line of each test case contains a string A. The next line of each test case contains a string B. Output format: For each test case, print the minimum cost required in a new line. Constraints 1 ≤ T ≤ 10 1 ≤ N, M ≤ 200 0 ≤ K ≤ min( N, M ) Example: Input: 2 5 4 3 abcba acyx 3 3 3 abc abc Output: 22 0 Google Marketing Internship Interview Experiences Google Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Microsoft Interview Experience for Internship (Via Engage) OLX Interview Experience (On-Campus) Zoho Interview Experience (Off-Campus ) 2022 Zoho Corporation (Internship cum Offer Experience ) Difference Between ON Page and OFF Page SEO Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 24994, "s": 24966, "text": "\n22 Jul, 2021" }, { "code": null, "e": 25353, "s": 24994, "text": "I came to know about the opportunity through https://careers.google.com/jobs/results/ Google’s website. Applied for the same with my resume. After two weeks got a mail Invite participating in the coding round. The mail had a unique ID and got the passkey(for login) on the day of the coding round1 (29th Aug 2020). The slot was open from 15:00 to 17:00 IST. " }, { "code": null, "e": 25587, "s": 25353, "text": "A coding round was conducted on the HackerEarth platform. The test duration was 60 minutes consisting of two coding questions, every 30 points. I partially solved 2nd one, the solution didn’t suffice for test cases with large inputs." }, { "code": null, "e": 25906, "s": 25587, "text": "A Special String: You are given a string S consisting of lowercase Latin alphabets a-z. Find the minimum number of characters that must be changed to make S special. A string S is said to be special if and only if for all (S[i], S[j] ) where (1 ≤ I ≤ N/2) and (N/2 + 1 ≤ j ≤ N) one of the following conditions is true " }, { "code": null, "e": 25918, "s": 25906, "text": "S[i] > S[j]" }, { "code": null, "e": 25930, "s": 25918, "text": "S[i] < S[j]" }, { "code": null, "e": 25942, "s": 25930, "text": "S[i] = S[j]" }, { "code": null, "e": 26009, "s": 25942, "text": "S[i] represents the ith character of string S (1 based Indexing )." }, { "code": null, "e": 26023, "s": 26009, "text": "Input Format:" }, { "code": null, "e": 26095, "s": 26023, "text": "The first line contains an integer T denoting the number of test cases." }, { "code": null, "e": 26176, "s": 26095, "text": "The first line of each test case contains an integer N denoting the length of S." }, { "code": null, "e": 26231, "s": 26176, "text": "The second line of each test case contains a string S." }, { "code": null, "e": 26345, "s": 26231, "text": "Output format: Print an integer denoting the minimum number of changes required for each test case in a new line." }, { "code": null, "e": 26358, "s": 26345, "text": "Constraints " }, { "code": null, "e": 26368, "s": 26358, "text": "1 ≤ T ≤ 5" }, { "code": null, "e": 26381, "s": 26368, "text": "1 ≤ N ≤ 103 " }, { "code": null, "e": 26391, "s": 26381, "text": "N is even" }, { "code": null, "e": 26401, "s": 26391, "text": "Example :" }, { "code": null, "e": 26439, "s": 26401, "text": "Input: 1\n 6\n aababc \nOutput: 2" }, { "code": null, "e": 26596, "s": 26439, "text": "Explanation: Change S[4] = ‘d’ (1 based indexing) Change S[5] = ‘d’ New string = ‘aabddc’ Now all pair (S[i],S[j]) satisfy the second condition, S[i] < S[j]" }, { "code": null, "e": 27009, "s": 26596, "text": "Generating Sequence: You are given two strings A of length N and B of length M. These strings contain lowercase English alphabets. You are also given an integer K. You can change the character of x in string A to any other character y. The cost of this conversion is abs( ASCII(x)- ASCII(y) ). Find the minimum cost required such that the length of the longest common subsequence (LCS) of A and B is at least K. " }, { "code": null, "e": 27016, "s": 27009, "text": "Note: " }, { "code": null, "e": 27100, "s": 27016, "text": "A subsequence of A string can be obtained by deleting zero or more characters in A." }, { "code": null, "e": 27368, "s": 27100, "text": "The longest common subsequence of two strings of A and B is a subsequence of A and B and has the maximum length among all strings that are a subsequence of A and B that would be multiple subsequences for two provided strings for example an LCS of vera and eats is ea." }, { "code": null, "e": 27382, "s": 27368, "text": "Input Format:" }, { "code": null, "e": 27473, "s": 27382, "text": "The first line contains an integer T denoting the number of test cases for each test case." }, { "code": null, "e": 27559, "s": 27473, "text": "The first line of each test case contains three space-separated integers N, M, and K." }, { "code": null, "e": 27612, "s": 27559, "text": "The next line of each test case contains a string A." }, { "code": null, "e": 27665, "s": 27612, "text": "The next line of each test case contains a string B." }, { "code": null, "e": 27747, "s": 27665, "text": "Output format: For each test case, print the minimum cost required in a new line." }, { "code": null, "e": 27760, "s": 27747, "text": "Constraints " }, { "code": null, "e": 27771, "s": 27760, "text": "1 ≤ T ≤ 10" }, { "code": null, "e": 27786, "s": 27771, "text": "1 ≤ N, M ≤ 200" }, { "code": null, "e": 27806, "s": 27786, "text": "0 ≤ K ≤ min( N, M )" }, { "code": null, "e": 27815, "s": 27806, "text": "Example:" }, { "code": null, "e": 27897, "s": 27815, "text": "Input: 2\n 5 4 3\n abcba\n acyx\n 3 3 3\n abc\n abc\nOutput: 22\n 0" }, { "code": null, "e": 27904, "s": 27897, "text": "Google" }, { "code": null, "e": 27914, "s": 27904, "text": "Marketing" }, { "code": null, "e": 27925, "s": 27914, "text": "Internship" }, { "code": null, "e": 27947, "s": 27925, "text": "Interview Experiences" }, { "code": null, "e": 27954, "s": 27947, "text": "Google" }, { "code": null, "e": 28052, "s": 27954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28061, "s": 28052, "text": "Comments" }, { "code": null, "e": 28074, "s": 28061, "text": "Old Comments" }, { "code": null, "e": 28133, "s": 28074, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 28170, "s": 28133, "text": "OLX Interview Experience (On-Campus)" }, { "code": null, "e": 28215, "s": 28170, "text": "Zoho Interview Experience (Off-Campus ) 2022" }, { "code": null, "e": 28267, "s": 28215, "text": "Zoho Corporation (Internship cum Offer Experience )" }, { "code": null, "e": 28311, "s": 28267, "text": "Difference Between ON Page and OFF Page SEO" }, { "code": null, "e": 28338, "s": 28311, "text": "Amazon Interview Questions" }, { "code": null, "e": 28398, "s": 28338, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 28448, "s": 28398, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 28486, "s": 28448, "text": "Amazon Interview Experience for SDE-1" } ]
java.time.LocalDate.format() Method Example
The java.time.LocalDate.format(DateTimeFormatter formatter) method formats this date using the specified formatter. Following is the declaration for java.time.LocalDate.format(DateTimeFormatter formatter) method. public String format(DateTimeFormatter formatter) formatter − the formatter to use, not null. the formatted date string, not null. DateTimeException − if an error occurs during printing. The following example shows the usage of java.time.LocalDate.format(DateTimeFormatter formatter) method. package com.tutorialspoint; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class LocalDateDemo { public static void main(String[] args) { LocalDate date = LocalDate.parse("2017-02-03"); System.out.println(date); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY"); System.out.println(formatter.format(date)); } } Let us compile and run the above program, this will produce the following result − 2017-02-03 03/02/2017 Print Add Notes Bookmark this page
[ { "code": null, "e": 2031, "s": 1915, "text": "The java.time.LocalDate.format(DateTimeFormatter formatter) method formats this date using the specified formatter." }, { "code": null, "e": 2128, "s": 2031, "text": "Following is the declaration for java.time.LocalDate.format(DateTimeFormatter formatter) method." }, { "code": null, "e": 2179, "s": 2128, "text": "public String format(DateTimeFormatter formatter)\n" }, { "code": null, "e": 2223, "s": 2179, "text": "formatter − the formatter to use, not null." }, { "code": null, "e": 2260, "s": 2223, "text": "the formatted date string, not null." }, { "code": null, "e": 2316, "s": 2260, "text": "DateTimeException − if an error occurs during printing." }, { "code": null, "e": 2421, "s": 2316, "text": "The following example shows the usage of java.time.LocalDate.format(DateTimeFormatter formatter) method." }, { "code": null, "e": 2822, "s": 2421, "text": "package com.tutorialspoint;\n\nimport java.time.LocalDate;\nimport java.time.format.DateTimeFormatter;\n\npublic class LocalDateDemo {\n public static void main(String[] args) {\n\n LocalDate date = LocalDate.parse(\"2017-02-03\");\n System.out.println(date); \n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/YYYY\");\n System.out.println(formatter.format(date)); \n }\n}" }, { "code": null, "e": 2905, "s": 2822, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 2928, "s": 2905, "text": "2017-02-03\n03/02/2017\n" }, { "code": null, "e": 2935, "s": 2928, "text": " Print" }, { "code": null, "e": 2946, "s": 2935, "text": " Add Notes" } ]
Arithmetic Progression - GeeksforGeeks
29 Apr, 2021 A sequence of numbers is called an Arithmetic progression if the difference between any two consecutive terms is always the same. In simple terms, it means that the next number in the series is calculated by adding a fixed number to the previous number in the series. For example, 2, 4, 6, 8, 10 is an AP because difference between any two consecutive terms in the series (common difference) is same (4 – 2 = 6 – 4 = 8 – 6 = 10 – 8 = 2). Fact about Arithmetic Progression : Initial term: In an arithmetic progression, the first number in the series is called the initial term.Common difference: The value by which consecutive terms increase or decrease is called the common difference.The behavior of the arithmetic progression depends on the common difference d. If the common difference is:positive, then the members (terms) will grow towards positive infinity or negative, then the members (terms) will grow towards negative infinity. Initial term: In an arithmetic progression, the first number in the series is called the initial term. Common difference: The value by which consecutive terms increase or decrease is called the common difference. The behavior of the arithmetic progression depends on the common difference d. If the common difference is:positive, then the members (terms) will grow towards positive infinity or negative, then the members (terms) will grow towards negative infinity. Formula of nth term of an A.P : If ‘a’ is the initial term and ‘d’ is the common difference.Thus, the explicit formula is Formula of sum of nth term of A.P: How we check whether a series is arithmetic progression or not? Naive solution. The idea is to sort the given array or series. After sorting, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible. Below is the implementation of this approach: Naive solution. The idea is to sort the given array or series. After sorting, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible. Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to check if a given array// can form arithmetic progression#include <bits/stdc++.h>using namespace std; // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionbool checkIsAP(int arr[], int n){ if (n == 1) return true; // Sort array sort(arr, arr + n); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true;} // Driven Programint main(){ int arr[] = { 20, 15, 5, 0, 10 }; int n = sizeof(arr) / sizeof(arr[0]); (checkIsAP(arr, n)) ? (cout << "Yes" << endl) : (cout << "No" << endl); return 0;} // Java program to check if a given array// can form arithmetic progressionimport java.util.Arrays; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static boolean checkIsAP(int arr[], int n) { if (n == 1) return true; // Sort array Arrays.sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } // driver code public static void main(String[] args) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if (checkIsAP(arr, n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Anant Agarwal. # Python3 program to check if a given# array can form arithmetic progression # Returns true if a permutation of arr[0..n-1]# can form arithmetic progressiondef checkIsAP(arr, n): if (n == 1): return True # Sort array arr.sort() # After sorting, difference between # consecutive elements must be same. d = arr[1] - arr[0] for i in range(2, n): if (arr[i] - arr[i-1] != d): return False return True # Driver codearr = [ 20, 15, 5, 0, 10 ]n = len(arr)print("Yes") if(checkIsAP(arr, n)) else print("No") # This code is contributed by Anant Agarwal. // C# program to check if a given array// can form arithmetic progressionusing System; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static bool checkIsAP(int[] arr, int n) { if (n == 1) return true; // Sort array Array.Sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } // Driver Code public static void Main() { int[] arr = { 20, 15, 5, 0, 10 }; int n = arr.Length; if (checkIsAP(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m. <?php// PHP program to check if// a given array can form// arithmetic progression // Returns true if a permutation// of arr[0..n-1] can form// arithmetic progressionfunction checkIsAP($arr, $n){ if ($n == 1) return true; // Sort array sort($arr); // After sorting, difference // between consecutive elements // must be same. $d = $arr[1] - $arr[0]; for ($i = 2; $i < $n; $i++) if ($arr[$i] - $arr[$i - 1] != $d) return false; return true;} // Driver Code$arr = array(20, 15, 5, 0, 10);$n = count($arr); if(checkIsAP($arr, $n))echo "Yes";elseecho "No"; // This code is contributed// by Sam007?> <script>// Javascript program to check if a given array// can form arithmetic progression// Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionfunction compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; }}function checkIsAP( arr, n){ if (n == 1) return true; // Sort array arr.sort(compare); // After sorting, difference between // consecutive elements must be same. let d = arr[1] - arr[0]; for (let i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true;} // Driven Programlet arr = [ 20, 15, 5, 0, 10 ];let n = arr.length;(checkIsAP(arr, n)) ? document.write("Yes <br>") : document.write("No <br>"); </script> Output: Output: Yes Time Complexity: O(n Log n). Efficient solutions Set 1(Use Hashing)Set 2(Use Counting Sort) Time Complexity: O(n Log n). Efficient solutions Set 1(Use Hashing)Set 2(Use Counting Sort) Set 1(Use Hashing) Set 2(Use Counting Sort) Basic Program related to Arithmetic Progression Program for sum of arithmetic series Program to print Arithmetic Progression series Longest arithmetic progression with the given common difference Check whether Arithmetic Progression can be formed from the given array Find the missing number in Arithmetic Progression Find N Arithmetic Means between A and B Sum of the numbers upto N that are divisible by 2 or 5 Find First element in AP which is multiple of given prime More problems related to Arithmetic Progression Sum of first n terms of a given series 3, 6, 11, ..... Ratio of mth and nth terms of an A. P. with given ratio of sums Probability for three randomly chosen numbers to be in AP Print all triplets in sorted array that form AP Program for N-th term of Arithmetic Progression series Sum of Arithmetic Geometric Sequence Count of AP (Arithmetic Progression) Subsequences in an array Recent Articles on Arithmetic Progression! rohitsingh07052 arithmetic progression series Mathematical Mathematical series 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 Program for factorial of a number Operators in C / C++ Sieve of Eratosthenes Euclidean algorithms (Basic and Extended) Program for Decimal to Binary Conversion
[ { "code": null, "e": 25416, "s": 25388, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25856, "s": 25416, "text": "A sequence of numbers is called an Arithmetic progression if the difference between any two consecutive terms is always the same. In simple terms, it means that the next number in the series is calculated by adding a fixed number to the previous number in the series. For example, 2, 4, 6, 8, 10 is an AP because difference between any two consecutive terms in the series (common difference) is same (4 – 2 = 6 – 4 = 8 – 6 = 10 – 8 = 2). " }, { "code": null, "e": 25894, "s": 25856, "text": "Fact about Arithmetic Progression : " }, { "code": null, "e": 26358, "s": 25894, "text": "Initial term: In an arithmetic progression, the first number in the series is called the initial term.Common difference: The value by which consecutive terms increase or decrease is called the common difference.The behavior of the arithmetic progression depends on the common difference d. If the common difference is:positive, then the members (terms) will grow towards positive infinity or negative, then the members (terms) will grow towards negative infinity." }, { "code": null, "e": 26461, "s": 26358, "text": "Initial term: In an arithmetic progression, the first number in the series is called the initial term." }, { "code": null, "e": 26571, "s": 26461, "text": "Common difference: The value by which consecutive terms increase or decrease is called the common difference." }, { "code": null, "e": 26824, "s": 26571, "text": "The behavior of the arithmetic progression depends on the common difference d. If the common difference is:positive, then the members (terms) will grow towards positive infinity or negative, then the members (terms) will grow towards negative infinity." }, { "code": null, "e": 26948, "s": 26824, "text": "Formula of nth term of an A.P : If ‘a’ is the initial term and ‘d’ is the common difference.Thus, the explicit formula is " }, { "code": null, "e": 26985, "s": 26948, "text": "Formula of sum of nth term of A.P: " }, { "code": null, "e": 27050, "s": 26985, "text": "How we check whether a series is arithmetic progression or not? " }, { "code": null, "e": 27308, "s": 27050, "text": "Naive solution. The idea is to sort the given array or series. After sorting, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible. Below is the implementation of this approach: " }, { "code": null, "e": 27566, "s": 27308, "text": "Naive solution. The idea is to sort the given array or series. After sorting, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible. Below is the implementation of this approach: " }, { "code": null, "e": 27570, "s": 27566, "text": "C++" }, { "code": null, "e": 27575, "s": 27570, "text": "Java" }, { "code": null, "e": 27583, "s": 27575, "text": "Python3" }, { "code": null, "e": 27586, "s": 27583, "text": "C#" }, { "code": null, "e": 27590, "s": 27586, "text": "PHP" }, { "code": null, "e": 27601, "s": 27590, "text": "Javascript" }, { "code": "// C++ program to check if a given array// can form arithmetic progression#include <bits/stdc++.h>using namespace std; // Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionbool checkIsAP(int arr[], int n){ if (n == 1) return true; // Sort array sort(arr, arr + n); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true;} // Driven Programint main(){ int arr[] = { 20, 15, 5, 0, 10 }; int n = sizeof(arr) / sizeof(arr[0]); (checkIsAP(arr, n)) ? (cout << \"Yes\" << endl) : (cout << \"No\" << endl); return 0;}", "e": 28330, "s": 27601, "text": null }, { "code": "// Java program to check if a given array// can form arithmetic progressionimport java.util.Arrays; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static boolean checkIsAP(int arr[], int n) { if (n == 1) return true; // Sort array Arrays.sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } // driver code public static void main(String[] args) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if (checkIsAP(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Anant Agarwal.", "e": 29236, "s": 28330, "text": null }, { "code": "# Python3 program to check if a given# array can form arithmetic progression # Returns true if a permutation of arr[0..n-1]# can form arithmetic progressiondef checkIsAP(arr, n): if (n == 1): return True # Sort array arr.sort() # After sorting, difference between # consecutive elements must be same. d = arr[1] - arr[0] for i in range(2, n): if (arr[i] - arr[i-1] != d): return False return True # Driver codearr = [ 20, 15, 5, 0, 10 ]n = len(arr)print(\"Yes\") if(checkIsAP(arr, n)) else print(\"No\") # This code is contributed by Anant Agarwal.", "e": 29826, "s": 29236, "text": null }, { "code": "// C# program to check if a given array// can form arithmetic progressionusing System; class GFG { // Returns true if a permutation of // arr[0..n-1] can form arithmetic // progression static bool checkIsAP(int[] arr, int n) { if (n == 1) return true; // Sort array Array.Sort(arr); // After sorting, difference between // consecutive elements must be same. int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true; } // Driver Code public static void Main() { int[] arr = { 20, 15, 5, 0, 10 }; int n = arr.Length; if (checkIsAP(arr, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.", "e": 30691, "s": 29826, "text": null }, { "code": "<?php// PHP program to check if// a given array can form// arithmetic progression // Returns true if a permutation// of arr[0..n-1] can form// arithmetic progressionfunction checkIsAP($arr, $n){ if ($n == 1) return true; // Sort array sort($arr); // After sorting, difference // between consecutive elements // must be same. $d = $arr[1] - $arr[0]; for ($i = 2; $i < $n; $i++) if ($arr[$i] - $arr[$i - 1] != $d) return false; return true;} // Driver Code$arr = array(20, 15, 5, 0, 10);$n = count($arr); if(checkIsAP($arr, $n))echo \"Yes\";elseecho \"No\"; // This code is contributed// by Sam007?>", "e": 31383, "s": 30691, "text": null }, { "code": "<script>// Javascript program to check if a given array// can form arithmetic progression// Returns true if a permutation of arr[0..n-1]// can form arithmetic progressionfunction compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; }}function checkIsAP( arr, n){ if (n == 1) return true; // Sort array arr.sort(compare); // After sorting, difference between // consecutive elements must be same. let d = arr[1] - arr[0]; for (let i = 2; i < n; i++) if (arr[i] - arr[i - 1] != d) return false; return true;} // Driven Programlet arr = [ 20, 15, 5, 0, 10 ];let n = arr.length;(checkIsAP(arr, n)) ? document.write(\"Yes <br>\") : document.write(\"No <br>\"); </script>", "e": 32166, "s": 31383, "text": null }, { "code": null, "e": 32176, "s": 32166, "text": "Output: " }, { "code": null, "e": 32186, "s": 32176, "text": "Output: " }, { "code": null, "e": 32190, "s": 32186, "text": "Yes" }, { "code": null, "e": 32283, "s": 32190, "text": "Time Complexity: O(n Log n). Efficient solutions Set 1(Use Hashing)Set 2(Use Counting Sort)" }, { "code": null, "e": 32314, "s": 32283, "text": "Time Complexity: O(n Log n). " }, { "code": null, "e": 32377, "s": 32314, "text": "Efficient solutions Set 1(Use Hashing)Set 2(Use Counting Sort)" }, { "code": null, "e": 32396, "s": 32377, "text": "Set 1(Use Hashing)" }, { "code": null, "e": 32421, "s": 32396, "text": "Set 2(Use Counting Sort)" }, { "code": null, "e": 32471, "s": 32421, "text": "Basic Program related to Arithmetic Progression " }, { "code": null, "e": 32508, "s": 32471, "text": "Program for sum of arithmetic series" }, { "code": null, "e": 32555, "s": 32508, "text": "Program to print Arithmetic Progression series" }, { "code": null, "e": 32619, "s": 32555, "text": "Longest arithmetic progression with the given common difference" }, { "code": null, "e": 32691, "s": 32619, "text": "Check whether Arithmetic Progression can be formed from the given array" }, { "code": null, "e": 32741, "s": 32691, "text": "Find the missing number in Arithmetic Progression" }, { "code": null, "e": 32781, "s": 32741, "text": "Find N Arithmetic Means between A and B" }, { "code": null, "e": 32836, "s": 32781, "text": "Sum of the numbers upto N that are divisible by 2 or 5" }, { "code": null, "e": 32894, "s": 32836, "text": "Find First element in AP which is multiple of given prime" }, { "code": null, "e": 32944, "s": 32894, "text": "More problems related to Arithmetic Progression " }, { "code": null, "e": 32999, "s": 32944, "text": "Sum of first n terms of a given series 3, 6, 11, ....." }, { "code": null, "e": 33063, "s": 32999, "text": "Ratio of mth and nth terms of an A. P. with given ratio of sums" }, { "code": null, "e": 33121, "s": 33063, "text": "Probability for three randomly chosen numbers to be in AP" }, { "code": null, "e": 33169, "s": 33121, "text": "Print all triplets in sorted array that form AP" }, { "code": null, "e": 33224, "s": 33169, "text": "Program for N-th term of Arithmetic Progression series" }, { "code": null, "e": 33261, "s": 33224, "text": "Sum of Arithmetic Geometric Sequence" }, { "code": null, "e": 33323, "s": 33261, "text": "Count of AP (Arithmetic Progression) Subsequences in an array" }, { "code": null, "e": 33367, "s": 33323, "text": "Recent Articles on Arithmetic Progression! " }, { "code": null, "e": 33383, "s": 33367, "text": "rohitsingh07052" }, { "code": null, "e": 33406, "s": 33383, "text": "arithmetic progression" }, { "code": null, "e": 33413, "s": 33406, "text": "series" }, { "code": null, "e": 33426, "s": 33413, "text": "Mathematical" }, { "code": null, "e": 33439, "s": 33426, "text": "Mathematical" }, { "code": null, "e": 33446, "s": 33439, "text": "series" }, { "code": null, "e": 33544, "s": 33446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33553, "s": 33544, "text": "Comments" }, { "code": null, "e": 33566, "s": 33553, "text": "Old Comments" }, { "code": null, "e": 33608, "s": 33566, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 33632, "s": 33608, "text": "Merge two sorted arrays" }, { "code": null, "e": 33675, "s": 33632, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33689, "s": 33675, "text": "Prime Numbers" }, { "code": null, "e": 33738, "s": 33689, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33772, "s": 33738, "text": "Program for factorial of a number" }, { "code": null, "e": 33793, "s": 33772, "text": "Operators in C / C++" }, { "code": null, "e": 33815, "s": 33793, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33857, "s": 33815, "text": "Euclidean algorithms (Basic and Extended)" } ]
R - While Loop
The While loop executes the same code again and again until a stop condition is met. The basic syntax for creating a while loop in R is − while (test_expression) { statement } Here key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. v <- c("Hello","while loop") cnt <- 2 while (cnt < 7) { print(v) cnt = cnt + 1 } When the above code is compiled and executed, it produces the following result − [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" [1] "Hello" "while loop" 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2487, "s": 2402, "text": "The While loop executes the same code again and again until a stop condition is met." }, { "code": null, "e": 2540, "s": 2487, "text": "The basic syntax for creating a while loop in R is −" }, { "code": null, "e": 2582, "s": 2540, "text": "while (test_expression) {\n statement\n}\n" }, { "code": null, "e": 2799, "s": 2582, "text": "Here key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed." }, { "code": null, "e": 2887, "s": 2799, "text": "v <- c(\"Hello\",\"while loop\")\ncnt <- 2\n\nwhile (cnt < 7) {\n print(v)\n cnt = cnt + 1\n}" }, { "code": null, "e": 2969, "s": 2887, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3100, "s": 2969, "text": "[1] \"Hello\" \"while loop\"\n[1] \"Hello\" \"while loop\"\n[1] \"Hello\" \"while loop\"\n[1] \"Hello\" \"while loop\"\n[1] \"Hello\" \"while loop\"\n" }, { "code": null, "e": 3133, "s": 3100, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3148, "s": 3133, "text": " Nishant Malik" }, { "code": null, "e": 3183, "s": 3148, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3198, "s": 3183, "text": " Nishant Malik" }, { "code": null, "e": 3233, "s": 3198, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3248, "s": 3233, "text": " Nishant Malik" }, { "code": null, "e": 3281, "s": 3248, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3295, "s": 3281, "text": " Asif Hussain" }, { "code": null, "e": 3330, "s": 3295, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3345, "s": 3330, "text": " Nishant Malik" }, { "code": null, "e": 3380, "s": 3345, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3394, "s": 3380, "text": " Asif Hussain" }, { "code": null, "e": 3401, "s": 3394, "text": " Print" }, { "code": null, "e": 3412, "s": 3401, "text": " Add Notes" } ]
Implementing Web Scraping in Python with BeautifulSoup - GeeksforGeeks
15 May, 2021 There are mainly two ways to extract data from a website: Use the API of the website (if it exists). For example, Facebook has the Facebook Graph API which allows retrieval of data posted on Facebook. Access the HTML of the webpage and extract useful information/data from it. This technique is called web scraping or web harvesting or web data extraction. This article discusses the steps involved in web scraping using the implementation of a Web Scraping framework of Python called Beautiful Soup. Steps involved in web scraping: Send an HTTP request to the URL of the webpage you want to access. The server responds to the request by returning the HTML content of the webpage. For this task, we will use a third-party HTTP library for python-requests.Once we have accessed the HTML content, we are left with the task of parsing the data. Since most of the HTML data is nested, we cannot extract data simply through string processing. One needs a parser which can create a nested/tree structure of the HTML data. There are many HTML parser libraries available but the most advanced one is html5lib.Now, all we need to do is navigating and searching the parse tree that we created, i.e. tree traversal. For this task, we will be using another third-party python library, Beautiful Soup. It is a Python library for pulling data out of HTML and XML files. Send an HTTP request to the URL of the webpage you want to access. The server responds to the request by returning the HTML content of the webpage. For this task, we will use a third-party HTTP library for python-requests. Once we have accessed the HTML content, we are left with the task of parsing the data. Since most of the HTML data is nested, we cannot extract data simply through string processing. One needs a parser which can create a nested/tree structure of the HTML data. There are many HTML parser libraries available but the most advanced one is html5lib. Now, all we need to do is navigating and searching the parse tree that we created, i.e. tree traversal. For this task, we will be using another third-party python library, Beautiful Soup. It is a Python library for pulling data out of HTML and XML files. Step 1: Installing the required third-party libraries Easiest way to install external libraries in python is to use pip. pip is a package management system used to install and manage software packages written in Python.All you need to do is: pip install requests pip install html5lib pip install bs4 Another way is to download them manually from these links:requestshtml5libbeautifulsoup4 requests html5lib beautifulsoup4 Step 2: Accessing the HTML content from webpage import requestsURL = "https://www.geeksforgeeks.org/data-structures/"r = requests.get(URL)print(r.content) Let us try to understand this piece of code. First of all import the requests library. Then, specify the URL of the webpage you want to scrape. Send a HTTP request to the specified URL and save the response from server in a response object called r. Now, as print r.content to get the raw HTML content of the webpage. It is of ‘string’ type. Step 3: Parsing the HTML content #This will not run on online IDEimport requestsfrom bs4 import BeautifulSoup URL = "http://www.values.com/inspirational-quotes"r = requests.get(URL) soup = BeautifulSoup(r.content, 'html5lib') # If this line causes an error, run 'pip install html5lib' or install html5libprint(soup.prettify()) A really nice thing about the BeautifulSoup library is that it is built on the top of the HTML parsing libraries like html5lib, lxml, html.parser, etc. So BeautifulSoup object and specify the parser library can be created at the same time. In the example above, soup = BeautifulSoup(r.content, 'html5lib') We create a BeautifulSoup object by passing two arguments: r.content : It is the raw HTML content. html5lib : Specifying the HTML parser we want to use. Now soup.prettify() is printed, it gives the visual representation of the parse tree created from the raw HTML content. Step 4: Searching and navigating through the parse tree Now, we would like to extract some useful data from the HTML content. The soup object contains all the data in the nested structure which could be programmatically extracted. In our example, we are scraping a webpage consisting of some quotes. So, we would like to create a program to save those quotes (and all relevant information about them). #Python program to scrape website #and save quotes from websiteimport requestsfrom bs4 import BeautifulSoupimport csv URL = "http://www.values.com/inspirational-quotes"r = requests.get(URL) soup = BeautifulSoup(r.content, 'html5lib') quotes=[] # a list to store quotes table = soup.find('div', attrs = {'id':'all_quotes'}) for row in table.findAll('div', attrs = {'class':'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}): quote = {} quote['theme'] = row.h5.text quote['url'] = row.a['href'] quote['img'] = row.img['src'] quote['lines'] = row.img['alt'].split(" #")[0] quote['author'] = row.img['alt'].split(" #")[1] quotes.append(quote) filename = 'inspirational_quotes.csv'with open(filename, 'w', newline='') as f: w = csv.DictWriter(f,['theme','url','img','lines','author']) w.writeheader() for quote in quotes: w.writerow(quote) Before moving on, we recommend you to go through the HTML content of the webpage which we printed using soup.prettify() method and try to find a pattern or a way to navigate to the quotes. It is noticed that all the quotes are inside a div container whose id is ‘all_quotes’. So, we find that div element (termed as table in above code) using find() method :table = soup.find('div', attrs = {'id':'all_quotes'}) The first argument is the HTML tag you want to search and second argument is a dictionary type element to specify the additional attributes associated with that tag. find() method returns the first matching element. You can try to print table.prettify() to get a sense of what this piece of code does. table = soup.find('div', attrs = {'id':'all_quotes'}) The first argument is the HTML tag you want to search and second argument is a dictionary type element to specify the additional attributes associated with that tag. find() method returns the first matching element. You can try to print table.prettify() to get a sense of what this piece of code does. Now, in the table element, one can notice that each quote is inside a div container whose class is quote. So, we iterate through each div container whose class is quote.Here, we use findAll() method which is similar to find method in terms of arguments but it returns a list of all matching elements. Each quote is now iterated using a variable called row.Here is one sample row HTML content for better understanding:Now consider this piece of code:for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}): quote = {} quote['theme'] = row.h5.text quote['url'] = row.a['href'] quote['img'] = row.img['src'] quote['lines'] = row.img['alt'].split(" #")[0] quote['author'] = row.img['alt'].split(" #")[1] quotes.append(quote)We create a dictionary to save all information about a quote. The nested structure can be accessed using dot notation. To access the text inside an HTML element, we use .text :quote['theme'] = row.h5.textWe can add, remove, modify and access a tag’s attributes. This is done by treating the tag as a dictionary:quote['url'] = row.a['href']Lastly, all the quotes are appended to the list called quotes. for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}): quote = {} quote['theme'] = row.h5.text quote['url'] = row.a['href'] quote['img'] = row.img['src'] quote['lines'] = row.img['alt'].split(" #")[0] quote['author'] = row.img['alt'].split(" #")[1] quotes.append(quote) We create a dictionary to save all information about a quote. The nested structure can be accessed using dot notation. To access the text inside an HTML element, we use .text : quote['theme'] = row.h5.text We can add, remove, modify and access a tag’s attributes. This is done by treating the tag as a dictionary: quote['url'] = row.a['href'] Lastly, all the quotes are appended to the list called quotes. Finally, we would like to save all our data in some CSV file.filename = 'inspirational_quotes.csv' with open(filename, 'w', newline='') as f: w = csv.DictWriter(f,['theme','url','img','lines','author']) w.writeheader() for quote in quotes: w.writerow(quote)Here we create a CSV file called inspirational_quotes.csv and save all the quotes in it for any further use. filename = 'inspirational_quotes.csv' with open(filename, 'w', newline='') as f: w = csv.DictWriter(f,['theme','url','img','lines','author']) w.writeheader() for quote in quotes: w.writerow(quote) Here we create a CSV file called inspirational_quotes.csv and save all the quotes in it for any further use. So, this was a simple example of how to create a web scraper in Python. From here, you can try to scrap any other website of your choice. In case of any queries, post them below in comments section. YouTubeGeeksforGeeks501K subscribersWeb Scraping Using Python | 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:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=O6nnVHPjcJU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Note : Web Scraping is considered as illegal in many cases. It may also cause your IP to be blocked permanently by a website. This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. the_galaxy_hunter Shamiul Hasan GBlog Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar Top 10 Angular Libraries For Web Developers Supervised and Unsupervised learning A Freshers Guide To Programming SDE SHEET - A Complete Guide for SDE Preparation XML parsing in Python Working with zip files in Python Python | Simple GUI calculator using Tkinter Simple Chat Room using Python
[ { "code": null, "e": 25140, "s": 25112, "text": "\n15 May, 2021" }, { "code": null, "e": 25198, "s": 25140, "text": "There are mainly two ways to extract data from a website:" }, { "code": null, "e": 25341, "s": 25198, "text": "Use the API of the website (if it exists). For example, Facebook has the Facebook Graph API which allows retrieval of data posted on Facebook." }, { "code": null, "e": 25497, "s": 25341, "text": "Access the HTML of the webpage and extract useful information/data from it. This technique is called web scraping or web harvesting or web data extraction." }, { "code": null, "e": 25641, "s": 25497, "text": "This article discusses the steps involved in web scraping using the implementation of a Web Scraping framework of Python called Beautiful Soup." }, { "code": null, "e": 25673, "s": 25641, "text": "Steps involved in web scraping:" }, { "code": null, "e": 26496, "s": 25673, "text": "Send an HTTP request to the URL of the webpage you want to access. The server responds to the request by returning the HTML content of the webpage. For this task, we will use a third-party HTTP library for python-requests.Once we have accessed the HTML content, we are left with the task of parsing the data. Since most of the HTML data is nested, we cannot extract data simply through string processing. One needs a parser which can create a nested/tree structure of the HTML data. There are many HTML parser libraries available but the most advanced one is html5lib.Now, all we need to do is navigating and searching the parse tree that we created, i.e. tree traversal. For this task, we will be using another third-party python library, Beautiful Soup. It is a Python library for pulling data out of HTML and XML files." }, { "code": null, "e": 26719, "s": 26496, "text": "Send an HTTP request to the URL of the webpage you want to access. The server responds to the request by returning the HTML content of the webpage. For this task, we will use a third-party HTTP library for python-requests." }, { "code": null, "e": 27066, "s": 26719, "text": "Once we have accessed the HTML content, we are left with the task of parsing the data. Since most of the HTML data is nested, we cannot extract data simply through string processing. One needs a parser which can create a nested/tree structure of the HTML data. There are many HTML parser libraries available but the most advanced one is html5lib." }, { "code": null, "e": 27321, "s": 27066, "text": "Now, all we need to do is navigating and searching the parse tree that we created, i.e. tree traversal. For this task, we will be using another third-party python library, Beautiful Soup. It is a Python library for pulling data out of HTML and XML files." }, { "code": null, "e": 27375, "s": 27321, "text": "Step 1: Installing the required third-party libraries" }, { "code": null, "e": 27563, "s": 27375, "text": "Easiest way to install external libraries in python is to use pip. pip is a package management system used to install and manage software packages written in Python.All you need to do is:" }, { "code": null, "e": 27621, "s": 27563, "text": "pip install requests\npip install html5lib\npip install bs4" }, { "code": null, "e": 27710, "s": 27621, "text": "Another way is to download them manually from these links:requestshtml5libbeautifulsoup4" }, { "code": null, "e": 27719, "s": 27710, "text": "requests" }, { "code": null, "e": 27728, "s": 27719, "text": "html5lib" }, { "code": null, "e": 27743, "s": 27728, "text": "beautifulsoup4" }, { "code": null, "e": 27791, "s": 27743, "text": "Step 2: Accessing the HTML content from webpage" }, { "code": "import requestsURL = \"https://www.geeksforgeeks.org/data-structures/\"r = requests.get(URL)print(r.content)", "e": 27898, "s": 27791, "text": null }, { "code": null, "e": 27943, "s": 27898, "text": "Let us try to understand this piece of code." }, { "code": null, "e": 27985, "s": 27943, "text": "First of all import the requests library." }, { "code": null, "e": 28042, "s": 27985, "text": "Then, specify the URL of the webpage you want to scrape." }, { "code": null, "e": 28148, "s": 28042, "text": "Send a HTTP request to the specified URL and save the response from server in a response object called r." }, { "code": null, "e": 28240, "s": 28148, "text": "Now, as print r.content to get the raw HTML content of the webpage. It is of ‘string’ type." }, { "code": null, "e": 28273, "s": 28240, "text": "Step 3: Parsing the HTML content" }, { "code": "#This will not run on online IDEimport requestsfrom bs4 import BeautifulSoup URL = \"http://www.values.com/inspirational-quotes\"r = requests.get(URL) soup = BeautifulSoup(r.content, 'html5lib') # If this line causes an error, run 'pip install html5lib' or install html5libprint(soup.prettify())", "e": 28569, "s": 28273, "text": null }, { "code": null, "e": 28810, "s": 28569, "text": "A really nice thing about the BeautifulSoup library is that it is built on the top of the HTML parsing libraries like html5lib, lxml, html.parser, etc. So BeautifulSoup object and specify the parser library can be created at the same time." }, { "code": null, "e": 28832, "s": 28810, "text": "In the example above," }, { "code": null, "e": 28876, "s": 28832, "text": "soup = BeautifulSoup(r.content, 'html5lib')" }, { "code": null, "e": 28935, "s": 28876, "text": "We create a BeautifulSoup object by passing two arguments:" }, { "code": null, "e": 28975, "s": 28935, "text": "r.content : It is the raw HTML content." }, { "code": null, "e": 29029, "s": 28975, "text": "html5lib : Specifying the HTML parser we want to use." }, { "code": null, "e": 29149, "s": 29029, "text": "Now soup.prettify() is printed, it gives the visual representation of the parse tree created from the raw HTML content." }, { "code": null, "e": 29205, "s": 29149, "text": "Step 4: Searching and navigating through the parse tree" }, { "code": null, "e": 29551, "s": 29205, "text": "Now, we would like to extract some useful data from the HTML content. The soup object contains all the data in the nested structure which could be programmatically extracted. In our example, we are scraping a webpage consisting of some quotes. So, we would like to create a program to save those quotes (and all relevant information about them)." }, { "code": "#Python program to scrape website #and save quotes from websiteimport requestsfrom bs4 import BeautifulSoupimport csv URL = \"http://www.values.com/inspirational-quotes\"r = requests.get(URL) soup = BeautifulSoup(r.content, 'html5lib') quotes=[] # a list to store quotes table = soup.find('div', attrs = {'id':'all_quotes'}) for row in table.findAll('div', attrs = {'class':'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}): quote = {} quote['theme'] = row.h5.text quote['url'] = row.a['href'] quote['img'] = row.img['src'] quote['lines'] = row.img['alt'].split(\" #\")[0] quote['author'] = row.img['alt'].split(\" #\")[1] quotes.append(quote) filename = 'inspirational_quotes.csv'with open(filename, 'w', newline='') as f: w = csv.DictWriter(f,['theme','url','img','lines','author']) w.writeheader() for quote in quotes: w.writerow(quote)", "e": 30479, "s": 29551, "text": null }, { "code": null, "e": 30668, "s": 30479, "text": "Before moving on, we recommend you to go through the HTML content of the webpage which we printed using soup.prettify() method and try to find a pattern or a way to navigate to the quotes." }, { "code": null, "e": 31193, "s": 30668, "text": "It is noticed that all the quotes are inside a div container whose id is ‘all_quotes’. So, we find that div element (termed as table in above code) using find() method :table = soup.find('div', attrs = {'id':'all_quotes'}) The first argument is the HTML tag you want to search and second argument is a dictionary type element to specify the additional attributes associated with that tag. find() method returns the first matching element. You can try to print table.prettify() to get a sense of what this piece of code does." }, { "code": null, "e": 31248, "s": 31193, "text": "table = soup.find('div', attrs = {'id':'all_quotes'}) " }, { "code": null, "e": 31550, "s": 31248, "text": "The first argument is the HTML tag you want to search and second argument is a dictionary type element to specify the additional attributes associated with that tag. find() method returns the first matching element. You can try to print table.prettify() to get a sense of what this piece of code does." }, { "code": null, "e": 32769, "s": 31550, "text": "Now, in the table element, one can notice that each quote is inside a div container whose class is quote. So, we iterate through each div container whose class is quote.Here, we use findAll() method which is similar to find method in terms of arguments but it returns a list of all matching elements. Each quote is now iterated using a variable called row.Here is one sample row HTML content for better understanding:Now consider this piece of code:for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):\n quote = {}\n quote['theme'] = row.h5.text\n quote['url'] = row.a['href']\n quote['img'] = row.img['src']\n quote['lines'] = row.img['alt'].split(\" #\")[0]\n quote['author'] = row.img['alt'].split(\" #\")[1]\n quotes.append(quote)We create a dictionary to save all information about a quote. The nested structure can be accessed using dot notation. To access the text inside an HTML element, we use .text :quote['theme'] = row.h5.textWe can add, remove, modify and access a tag’s attributes. This is done by treating the tag as a dictionary:quote['url'] = row.a['href']Lastly, all the quotes are appended to the list called quotes." }, { "code": null, "e": 33138, "s": 32769, "text": "for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):\n quote = {}\n quote['theme'] = row.h5.text\n quote['url'] = row.a['href']\n quote['img'] = row.img['src']\n quote['lines'] = row.img['alt'].split(\" #\")[0]\n quote['author'] = row.img['alt'].split(\" #\")[1]\n quotes.append(quote)" }, { "code": null, "e": 33315, "s": 33138, "text": "We create a dictionary to save all information about a quote. The nested structure can be accessed using dot notation. To access the text inside an HTML element, we use .text :" }, { "code": null, "e": 33344, "s": 33315, "text": "quote['theme'] = row.h5.text" }, { "code": null, "e": 33452, "s": 33344, "text": "We can add, remove, modify and access a tag’s attributes. This is done by treating the tag as a dictionary:" }, { "code": null, "e": 33481, "s": 33452, "text": "quote['url'] = row.a['href']" }, { "code": null, "e": 33544, "s": 33481, "text": "Lastly, all the quotes are appended to the list called quotes." }, { "code": null, "e": 33930, "s": 33544, "text": "Finally, we would like to save all our data in some CSV file.filename = 'inspirational_quotes.csv'\nwith open(filename, 'w', newline='') as f:\n w = csv.DictWriter(f,['theme','url','img','lines','author'])\n w.writeheader()\n for quote in quotes:\n w.writerow(quote)Here we create a CSV file called inspirational_quotes.csv and save all the quotes in it for any further use." }, { "code": null, "e": 34147, "s": 33930, "text": "filename = 'inspirational_quotes.csv'\nwith open(filename, 'w', newline='') as f:\n w = csv.DictWriter(f,['theme','url','img','lines','author'])\n w.writeheader()\n for quote in quotes:\n w.writerow(quote)" }, { "code": null, "e": 34256, "s": 34147, "text": "Here we create a CSV file called inspirational_quotes.csv and save all the quotes in it for any further use." }, { "code": null, "e": 34456, "s": 34256, "text": "So, this was a simple example of how to create a web scraper in Python. From here, you can try to scrap any other website of your choice. In case of any queries, post them below in comments section." }, { "code": null, "e": 35280, "s": 34456, "text": "YouTubeGeeksforGeeks501K subscribersWeb Scraping Using Python | 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:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=O6nnVHPjcJU\" 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": 35406, "s": 35280, "text": "Note : Web Scraping is considered as illegal in many cases. It may also cause your IP to be blocked permanently by a website." }, { "code": null, "e": 35698, "s": 35406, "text": "This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 35823, "s": 35698, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 35841, "s": 35823, "text": "the_galaxy_hunter" }, { "code": null, "e": 35855, "s": 35841, "text": "Shamiul Hasan" }, { "code": null, "e": 35861, "s": 35855, "text": "GBlog" }, { "code": null, "e": 35869, "s": 35861, "text": "Project" }, { "code": null, "e": 35876, "s": 35869, "text": "Python" }, { "code": null, "e": 35974, "s": 35876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36016, "s": 35974, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 36041, "s": 36016, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 36085, "s": 36041, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 36122, "s": 36085, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 36154, "s": 36122, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 36203, "s": 36154, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 36225, "s": 36203, "text": "XML parsing in Python" }, { "code": null, "e": 36258, "s": 36225, "text": "Working with zip files in Python" }, { "code": null, "e": 36303, "s": 36258, "text": "Python | Simple GUI calculator using Tkinter" } ]
Program to find the sum of all digits of given number in Python
Suppose we have a number num, we have to find the sum of its digits. We have to solve it without using strings. So, if the input is like num = 512, then the output will be 8, as 8 = 5 + 1 + 2. tput will be 8, as 8 = 5 + 1 + 2. To solve this, we will follow these steps − sum:= 0 while num is not same as 0, dosum := sum + (num mod 10)num:= quotient of num/10 sum := sum + (num mod 10) num:= quotient of num/10 return sum Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, num): sum=0 while(num!=0): sum = sum+int(num%10) num=int(num/10) return sum ob = Solution() print(ob.solve(512)) 512 8
[ { "code": null, "e": 1174, "s": 1062, "text": "Suppose we have a number num, we have to find the sum of its digits. We have to solve it without using strings." }, { "code": null, "e": 1255, "s": 1174, "text": "So, if the input is like num = 512, then the output will be 8, as 8 = 5 + 1 + 2." }, { "code": null, "e": 1333, "s": 1255, "text": "tput will be 8, as 8 = 5 + 1 + 2.\nTo solve this, we will follow these steps −" }, { "code": null, "e": 1341, "s": 1333, "text": "sum:= 0" }, { "code": null, "e": 1421, "s": 1341, "text": "while num is not same as 0, dosum := sum + (num mod 10)num:= quotient of num/10" }, { "code": null, "e": 1447, "s": 1421, "text": "sum := sum + (num mod 10)" }, { "code": null, "e": 1472, "s": 1447, "text": "num:= quotient of num/10" }, { "code": null, "e": 1483, "s": 1472, "text": "return sum" }, { "code": null, "e": 1553, "s": 1483, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1564, "s": 1553, "text": " Live Demo" }, { "code": null, "e": 1748, "s": 1564, "text": "class Solution:\n def solve(self, num):\n sum=0\n while(num!=0):\n sum = sum+int(num%10)\n num=int(num/10)\n return sum\nob = Solution()\nprint(ob.solve(512))" }, { "code": null, "e": 1752, "s": 1748, "text": "512" }, { "code": null, "e": 1754, "s": 1752, "text": "8" } ]
SQL — Substring with Negative Indexing | by Deepak Khandelwal | Towards Data Science
In this post, I have discussed about one of the very important string related operations in SQL — SUBSTR with the application of negative indexing. SUBSTR is used to extract the certain part of the given string from a given position. I have used SQLite-implementation of SUBSTR to illustrate the use of negative indexing. I have used movielens database to write the various queries of SUBSTR. This database has the four tables — links, movies, ratings, tags. We are interested in movies table. The first 20 rows of the table are as follows Now we will go through the details of SUBSTR operator and it parameters.SUBSTR accepts three parameters as shown in Table 1. The last parameter — Z, is optional. Both Y and Z parameters can take positive and negative index values. Furthermore, Z is optional, Therefore we have the following six possibilities ╔══════════╦══════════╗║ Y ║ Z ║╠══════════╬══════════╣║ Positive ║ - ║║ Negative ║ - ║║ Positive ║ Positive ║║ Positive ║ Negative ║║ Negative ║ Positive ║║ Negative ║ Negative ║╚══════════╩══════════╝ Now we will write queries for each of the six aforementioned possibilities. Before that, we should know how negative indexing works in SUBSTR. The positive indexing starts from number 1 which will be the leftmost character and the negative indexing starts from number -1 which will be the rightmost character in the string as shown in figure 3. The following table contains the details of how the six combinations of Y and Z are evaluated. Now we will perform some queries where we can use to get the desired result. Query 1: Write a query to remove movie release year from movie title and display only titles. SELECT TRIM(SUBSTR(TRIM(title), -6, (SELECT 6-MAX(LENGTH(title)) FROM movies)))FROM movies In the query 1, we have the following values for X, Y, Z1. X = TRIM(title) We have trimmed the title column of the movie table to eliminate any possibility of having spaces at both the ends of movie title.2. Y = -6Why -6? Because we have the following structure for all the movie titles —<title><space>(<four digit movie release year>). We have last 6 characters as ‘(‘, ‘<digit>’, ‘<digit>’, ‘<digit>’, ‘<digit>’, ‘)’ . 3. Z = (SELECT 6-MAX(LENGTH(title)) FROM movies) Since the titles’s lengths vary and we have to make sure that each of the title should appear in the result in its entirety. We have handled the case having maximum title length, it will work for the rest of cases. We can break down this operation into the following steps — First, lengths of all the movie titles are calculated — LENGTH(title). It results in a table containing the length of each and every movie title.Second, maximum length is calculated — MAX(LENGTH(title)) . It results in maximum length of title which is 158.Third, 6-MAX(LENGTH(title)) results in 6–158 = -152.Hence we have Z as -152. Here, both Y and Z have negative values. It starts reading from -6th character which is ‘(’, then it reads, absolute value of -152 which is 152, characters preceding ‘(’ excluding ‘(’ character. Since 152 is the maximum length a title can have in the movie table, it will extract titles for all the movies. For example, ‘Jimmy Hollywood (1994)’ will result in ‘Jimmy Hollywood ’ and after trimming ‘Jimmy Hollywood’ . Query 2: Write a query to remove title from movie title and display only year. Similarly, We can extract the movie release year from the title column. SELECT TRIM(SUBSTR(TRIM(title), -5, 4))FROM movies In this query, Extraction of movie release year starts from -5th character which is first digit of movie release year, then 4 characters following that are fetched including the -5th character. Now we can leverage the power of negative indexing to perform some specific operations. For example — we can group by the result of query 2 on movie release year and can get the count of movies released in each year. Query 3: Write a query to find out the release years of the movie Mission Impossible. SELECT TRIM(SUBSTR(TRIM(title), -5, 4))FROM moviesWHERE title LIKE "Mission: Impossible%" At last, one point I want to highlight is that the above operations could be performed using regular expressions in much more elegant and efficient way, but in this article, I have tried to show application of negative indexing in SUBSTR.
[ { "code": null, "e": 320, "s": 172, "text": "In this post, I have discussed about one of the very important string related operations in SQL — SUBSTR with the application of negative indexing." }, { "code": null, "e": 494, "s": 320, "text": "SUBSTR is used to extract the certain part of the given string from a given position. I have used SQLite-implementation of SUBSTR to illustrate the use of negative indexing." }, { "code": null, "e": 712, "s": 494, "text": "I have used movielens database to write the various queries of SUBSTR. This database has the four tables — links, movies, ratings, tags. We are interested in movies table. The first 20 rows of the table are as follows" }, { "code": null, "e": 874, "s": 712, "text": "Now we will go through the details of SUBSTR operator and it parameters.SUBSTR accepts three parameters as shown in Table 1. The last parameter — Z, is optional." }, { "code": null, "e": 1021, "s": 874, "text": "Both Y and Z parameters can take positive and negative index values. Furthermore, Z is optional, Therefore we have the following six possibilities" }, { "code": null, "e": 1252, "s": 1021, "text": "╔══════════╦══════════╗║ Y ║ Z ║╠══════════╬══════════╣║ Positive ║ - ║║ Negative ║ - ║║ Positive ║ Positive ║║ Positive ║ Negative ║║ Negative ║ Positive ║║ Negative ║ Negative ║╚══════════╩══════════╝" }, { "code": null, "e": 1597, "s": 1252, "text": "Now we will write queries for each of the six aforementioned possibilities. Before that, we should know how negative indexing works in SUBSTR. The positive indexing starts from number 1 which will be the leftmost character and the negative indexing starts from number -1 which will be the rightmost character in the string as shown in figure 3." }, { "code": null, "e": 1692, "s": 1597, "text": "The following table contains the details of how the six combinations of Y and Z are evaluated." }, { "code": null, "e": 1769, "s": 1692, "text": "Now we will perform some queries where we can use to get the desired result." }, { "code": null, "e": 1863, "s": 1769, "text": "Query 1: Write a query to remove movie release year from movie title and display only titles." }, { "code": null, "e": 1990, "s": 1863, "text": "SELECT TRIM(SUBSTR(TRIM(title), -6, (SELECT 6-MAX(LENGTH(title)) FROM movies)))FROM movies" }, { "code": null, "e": 2411, "s": 1990, "text": "In the query 1, we have the following values for X, Y, Z1. X = TRIM(title) We have trimmed the title column of the movie table to eliminate any possibility of having spaces at both the ends of movie title.2. Y = -6Why -6? Because we have the following structure for all the movie titles —<title><space>(<four digit movie release year>). We have last 6 characters as ‘(‘, ‘<digit>’, ‘<digit>’, ‘<digit>’, ‘<digit>’, ‘)’ ." }, { "code": null, "e": 3486, "s": 2411, "text": "3. Z = (SELECT 6-MAX(LENGTH(title)) FROM movies) Since the titles’s lengths vary and we have to make sure that each of the title should appear in the result in its entirety. We have handled the case having maximum title length, it will work for the rest of cases. We can break down this operation into the following steps — First, lengths of all the movie titles are calculated — LENGTH(title). It results in a table containing the length of each and every movie title.Second, maximum length is calculated — MAX(LENGTH(title)) . It results in maximum length of title which is 158.Third, 6-MAX(LENGTH(title)) results in 6–158 = -152.Hence we have Z as -152. Here, both Y and Z have negative values. It starts reading from -6th character which is ‘(’, then it reads, absolute value of -152 which is 152, characters preceding ‘(’ excluding ‘(’ character. Since 152 is the maximum length a title can have in the movie table, it will extract titles for all the movies. For example, ‘Jimmy Hollywood (1994)’ will result in ‘Jimmy Hollywood ’ and after trimming ‘Jimmy Hollywood’ ." }, { "code": null, "e": 3565, "s": 3486, "text": "Query 2: Write a query to remove title from movie title and display only year." }, { "code": null, "e": 3637, "s": 3565, "text": "Similarly, We can extract the movie release year from the title column." }, { "code": null, "e": 3688, "s": 3637, "text": "SELECT TRIM(SUBSTR(TRIM(title), -5, 4))FROM movies" }, { "code": null, "e": 3882, "s": 3688, "text": "In this query, Extraction of movie release year starts from -5th character which is first digit of movie release year, then 4 characters following that are fetched including the -5th character." }, { "code": null, "e": 4099, "s": 3882, "text": "Now we can leverage the power of negative indexing to perform some specific operations. For example — we can group by the result of query 2 on movie release year and can get the count of movies released in each year." }, { "code": null, "e": 4185, "s": 4099, "text": "Query 3: Write a query to find out the release years of the movie Mission Impossible." }, { "code": null, "e": 4275, "s": 4185, "text": "SELECT TRIM(SUBSTR(TRIM(title), -5, 4))FROM moviesWHERE title LIKE \"Mission: Impossible%\"" } ]
Predict Customer Churn using PySpark Machine Learning | by Marvin Lüthe | Towards Data Science
Predicting customer churn is a challenging and common problem that data scientists encounter these days. The ability to predict that a particular customer is at a high risk of churning, while there is still time to do something about it, represents a huge additional potential revenue source for every customer-facing business. In this post, I will guide you through the creation of a machine learning solution which will be able to predict customer churn. This solution will be realized with Apache Spark. Apache Spark is a popular distributed data processing engine which can be deployed in a variety of ways, providing native bindings for Java, Scala, Python and R. It provides a stack of libraries including Spark SQL, Spark Streaming, MLlib for machine learning and GraphX for graph processing. For this project, we will focus on the machine learning library MLlib. We will use the Python API for Spark known as PySpark. If you read this article, you will learn how to: load large datasets into Spark and manipulate them using Spark SQL and Spark Dataframes to engineer relevant features for predicting customer churn, use the machine learning APIs within Spark ML to build and tune models. Imagine you are working on the data team for a popular digital music service similar to Spotify. Let’s call it Sparkify. The users stream their favorite songs every day either using the free tier that places advertisements between the songs or using the premium subscription model where they stream music as free but pay a monthly flat rate. The users can upgrade, downgrade and cancel the service at any time. Every time the user interacts with the service like playing songs, logging out or liking a song with a thumbs-up, it generates data. All this data contains the key insights for keeping the users happy and helping the business thrive. It’s our job on the data team to predict which users are at risk to cancel their accounts. If we can accurately identify these users before they leave, our business can offer them discount and incentives, potentially saving our business millions in revenue. I used IBM Watson Studio (Default Spark Python 3.6 XS, one driver, two executors, Spark Version 2.3) to work on this project. The interaction with PySpark dataframes is not as convenient as it is with pandas dataframes. This is why I recommend installing and importing pixiedust: !pip install --upgrade pixiedustimport pixiedust pixiedustis an open-source Python helper library that works as an add-on to Jupyter notebooks and strongly improves the way we can interact with PySpark dataframes. import numpy as npimport pandas as pd%matplotlib inlineimport matplotlib.pyplot as pltimport datetimefrom sklearn.metrics import f1_score, recall_score, precision_scorefrom pyspark.sql import SparkSessionimport pyspark.sql.functions as Ffrom pyspark.sql.types import IntegerType, DoubleType, DateType, FloatTypefrom pyspark.ml.feature import VectorAssembler, MinMaxScalerfrom pyspark.ml import Pipelinefrom pyspark.ml.evaluation import BinaryClassificationEvaluatorfrom pyspark.ml.tuning import ParamGridBuilder, CrossValidatorfrom pyspark.ml.classification import LogisticRegression, DecisionTreeClassifier, GBTClassifier, LinearSVC Create a Spark session and read in the Sparkify dataset: # create a Spark sessionspark = SparkSession \ .builder \ .appName("Sparkify") \ .getOrCreate()# read in datasetdf = spark.read.json('medium-sparkify-event-data.json') pixiedustnow comes in handy and we can display the first entries of the dataframe. display(df) Have a peek at the schema: df.printSchema() The dataset holds information about how the users interact with the streaming platform, which songs they listened, which page they visited, their account status, etc. Any of the user interactions are stored with a UNIX timestamp which makes it possible to analyze changes in user behaviour over time. We will take advantage of that piece of information during the feature engineering process later. Next, we will perform EDA by doing basic manipulations within PySpark. In order to understand how the users interact with the music service, we might want to see which pages they view the most. df.groupBy('page').count().sort(F.desc('count')).show() We can clearly see that “NextSong” is the most popular page view which makes perfect sense for a music service. However, there are many other page views which are going to be important for engineering relevant features from this raw dataset. We take the page “Cancellation Confirmation”, counting 99 visits, to create the label for the machine learning models. flag_cancellation_event = F.udf(lambda x: 1 if x == 'Cancellation Confirmation' else 0, IntegerType())df = df.withColumn('label', flag_cancellation_event('page')) Based on the UNIX timestamp ts we can calculate statistics by hour. get_hour = F.udf(lambda x: datetime.datetime.fromtimestamp(x / 1000.0).hour, IntegerType())df = df.withColumn('hour', get_hour(df.ts)) Since matplotlib does not work with PySpark dataframes we convert it back to a pandas dataframe and plot the user activity by hour. # Count the events per hoursongs_by_hour = df.groupBy('hour').count().orderBy(df.hour)songs_by_hour_pd = songs_by_hour.toPandas()songs_by_hour_pd.hour = pd.to_numeric(songs_by_hour_pd.hour)# Plot the events per hour aggregationplt.scatter(songs_by_hour_pd['hour'], songs_by_hour_pd['count'])plt.xlim(-1, 24)plt.ylim(0, 1.2 * max(songs_by_hour_pd['count']))plt.xlabel('Hour')plt.ylabel('Events'); Feature engineering plays a key role in big data analytics. Machine learning and data mining algorithms cannot work without data. Little can be achieved if there are few features to represent the underlying data objects, and the quality of results of those algorithms largely depends on the quality of the available features.Accordingly, we start building out the features we find promising to train the model on. To this end, we create a new PySpark dataframe feature_df from scratch, each row representing a user. We will create features from the dataframe df and join those sequentially to the dataframe feature_df. Based on the column label in df we can separate the churned users from the rest. churned_collect = df.where(df.label==1).select('userId').collect()churned_users = set([int(row.userId) for row in churned_collect])all_collect = df.select('userId').collect()all_users = set([int(row.userId) for row in all_collect])feature_df = spark.createDataFrame(all_users, IntegerType()).withColumnRenamed('value', 'userId') # Create label columncreate_churn = F.udf(lambda x: 1 if x in churned_users else 0, IntegerType())feature_df = feature_df.withColumn('label', create_churn('userId')) # Create binary gender columnconvert_gender = F.udf(lambda x: 1 if x == 'M' else 0, IntegerType())df = df.withColumn('GenderBinary', convert_gender('Gender'))# Add gender as featurefeature_df = feature_df.join(df.select(['userId', 'GenderBinary']), 'userId') \ .dropDuplicates(subset=['userId']) \ .sort('userId')convert_level = F.udf(lambda x: 1 if x == 'free' else 0, IntegerType())df = df.withColumn('LevelBinary', convert_level('Level'))# Add customer level as featurefeature_df = feature_df.join(df.select(['userId', 'ts', 'LevelBinary']), 'userId') \ .sort(F.desc('ts')) \ .dropDuplicates(subset=['userId']) \ .drop('ts') Every time the users interact with the platform, it generates data. This means that we know exactly what each of the users experienced during the period of this data extract. My approach is to divide the pages into categories: Neutral pages: “Cancel”, “Home”, “Logout”, “Save Settings”, “About”, “Settings” Negative pages: “Thumbs Down”, “Roll Advert”, “Help”, “Error” Positive pages: “Add to Playlist”, “Add Friend”, “NextSong”, “Thumbs Up” Downgrade pages: “Submit Downgrade”, “Downgrade” Upgrade pages: “Submit Upgrade”, “Upgrade” The reasoning behind this approach is that we can count how often a user had an interaction e.g. with a positive page. We could have done this for every page separately but this would result in a much higher feature space. Let’s put this into code: # Create a dictonary which maps page views and PySpark dataframes pages = {}pages['neutralPages'] = df.filter((df.page == 'Cancel') | (df.page == 'Home') | (df.page == 'Logout') \ | (df.page == 'Save Settings') | (df.page == 'About') | (df.page == 'Settings'))pages['negativePages'] = df.filter((df.page == 'Thumbs Down') | (df.page == 'Roll Advert') | (df.page == 'Help') \ | (df.page == 'Error'))pages['positivePages'] = df.filter((df.page == 'Add to Playlist') | (df.page == 'Add Friend') | (df.page == 'NextSong') \ | (df.page == 'Thumbs Up'))pages['downgradePages'] = df.filter((df.page == 'Submit Downgrade') | (df.page == 'Downgrade'))pages['upgradePages'] = df.filter((df.page == 'Upgrade') | (df.page == 'Submit Upgrade'))# Loop through page views and aggregate the counts by userfor key, value in pages.items(): value_df = value.select('userId') \ .groupBy('userId') \ .agg({'userId':'count'}) \ .withColumnRenamed('count(userId)', key) # Add page view aggregations as features feature_df = feature_df.join(value_df, 'userId', 'left').sort('userId') \ .fillna({key:'0'}) Next, we will calculate how many days the users interacted with the platform: # Create dataframe with users and date countsdateCount_df = df.select('userId', 'date') \ .groupby('userId') \ .agg(F.countDistinct('date')) \ .withColumnRenamed('count(DISTINCT date)', 'dateCount')# Add date count as featurefeature_df = feature_df.join(dateCount_df, 'userId', 'left').sort('userId') \ .fillna({'dateCount':'1'}) These page view features are absolute values counting the number of occurrences. However, this can lead to misleading results if some users signed up at the end of the data extract while others used the platform from the very beginning. For this purpose, we will make the aggregated results comparable by dividing them through the user-specific time window, obtaining counts/day. I skip the code at this place, the full code is available on GitHub. Another promising feature is how the user interactions change over time. First, we calculate the number of user interactions per day. Second, we fit one linear regression model per user using numpy.polyfit. We will take the slopes of these lines, remove outliers and plug the scaled slopes as features into the classification algorithms. # Create dataframe with users and their activity per dayactivity_df = df.select('userId', 'date') \ .groupby('userID', 'date') \ .count()# initialize slopesslopes = []for user in all_users: # Create pandas dataframe for slope calculation activity_pandas = activity_df.filter(activity_df['userID'] == user).sort(F.asc('date')).toPandas() if activity_pandas.shape[0]==1: slopes.append(0) continue # Fit a line through the user activity counts and retrieve its slope slope = np.polyfit(activity_pandas.index, activity_pandas['count'], 1)[0] slopes.append(slope) As a final step for the feature engineering process we will iterate over the created features and scale them using MinMaxScaler. Afterwards, we put the features into one vector so that we can plug it into the pyspark.ml algorithms. # UDF for converting column type from vector to double typeunlist = F.udf(lambda x: round(float(list(x)[0]),3), DoubleType())# Iterate over columns to be scaledfor i in ['neutralPagesNormalized', 'negativePagesNormalized', 'positivePagesNormalized', 'downgradePagesNormalized', 'upgradePagesNormalized', 'dateCountNormalized', 'hourAvg', 'UserActiveTime', 'Slope']: # VectorAssembler Transformation - Convert column to vector type assembler = VectorAssembler(inputCols=[i],outputCol=i+"_Vect") # MinMaxScaler Transformation scaler = MinMaxScaler(inputCol=i+"_Vect", outputCol=i+"_Scaled") # Pipeline of VectorAssembler and MinMaxScaler pipeline = Pipeline(stages=[assembler, scaler]) # Fitting pipeline on dataframe feature_df = pipeline.fit(feature_df).transform(feature_df) \ .withColumn(i+"_Scaled", unlist(i+"_Scaled")).drop(i+"_Vect")# Merge columns to one feature vectorassembler = VectorAssembler(inputCols=['neutralPagesNormalized_Scaled', 'negativePagesNormalized_Scaled', 'positivePagesNormalized_Scaled', 'downgradePagesNormalized_Scaled', 'upgradePagesNormalized_Scaled', 'dateCountNormalized_Scaled', 'hourAvg_Scaled', 'UserActiveTime_Scaled', 'Slope_Scaled', 'LevelBinary', 'GenderBinary'], outputCol='features')feature_df = assembler.transform(feature_df) Following the schema of feature_df: The features column holds the combined features vector for each user: After the creation of features, we can move on and split the full dataset into training and testing. We will test out several common machine learning methods used for classification tasks. The accuracy of the models will be evaluated and parameters tuned accordingly. Based on the F1-Score, Precision and Recall we will determine the winning model. Split the features dataframe into training and testing and check for class imbalance. train, test = feature_df.randomSplit([0.7, 0.3], seed = 42)plt.hist(feature_df.toPandas()['label'])plt.show() It is crucial to check for potential class imbalance in the data. It is extremely common in practice and many classification learning algorithms have low predictive accuracy for the infrequent class. Spark’s MLlib supports tools for model selection such as CrossValidator. This requires the following: Estimator: algorithm or pipeline Set of parameters: parameter grid to search over Evaluator: metric to measure how well a fitted model does on the test dataset. The estimators and parameters will be set for each classifier specifically. For evaluation, we take the BinaryClassificationEvaluator which supports the “areaUnderROC” and the “areaUnderPR”. Since we have a class imbalance in the data, we take the “areaUnderPR” as our evaluation metric because the PR curve is more informative in this case (cf. http://pages.cs.wisc.edu/~jdavis/davisgoadrichcamera2.pdf). Since the class BinaryClassificationEvaluator from pyspark.ml.evaluation only provides the metrics “areaUnderPR” and “areaUnderROC”, we will compute the F1-Score, Precision and Recall with sklearn. evaluator = BinaryClassificationEvaluator(metricName = 'areaUnderPR') Logistic Regression Logistic regression is basically a linear regression model which explains the relationship between dependent variables and one or more nominal, ordinal, interval or ratio-level independent variables with only difference being, the output for linear regression is a number that has its real meaning (a label) while the output of a logistic regression is a number that represents the probability of the event happening (i.e. the probability of a customer deleting its account). Before instantiating the logistic regression object we calculate a balancing ratio to account for the class imbalance. We use the weightCol parameter to over-/under-sample training instances according to the pre-calculated ratios. We want to “under-sample” the negative class and “over-sample” the positive class. The logistic loss objective function should treat the negative class (label == 0) with lower weight. # Calculate a balancing ratio to account for the class imbalancebalancing_ratio = train.filter(train['label']==0).count()/train.count()train=train.withColumn("classWeights", F.when(train.label == 1,balancing_ratio).otherwise(1-balancing_ratio))# Create a logistic regression objectlr = LogisticRegression(featuresCol = 'features', labelCol = 'label', weightCol="classWeights") For logistic regression, pyspark.ml supports extracting a trainingSummaryof the model over the training set. This does not work with a fitted CrossValidator object which is why we take it from a fitted model without parameter tuning. lrModel = lr.fit(train)trainingSummary = lrModel.summary We can use it to plot the threshold-Recall curve, threshold-Precision curve, Recall-Precision curve and threshold-F-Measure curve to examine how our model performs. This threshold is a prediction threshold which determines the predicted class based on the probabilities that the model outputs. Model optimization includes tuning this threshold. # Plot the threshold-recall curvetr = trainingSummary.recallByThreshold.toPandas()plt.plot(tr['threshold'], tr['recall'])plt.xlabel('Threshold')plt.ylabel('Recall')plt.show() # Plot the threshold-precision curvetp = trainingSummary.precisionByThreshold.toPandas()plt.plot(tp['threshold'], tp['precision'])plt.xlabel('Threshold')plt.ylabel('Precision')plt.show() # Plot the recall-precision curvepr = trainingSummary.pr.toPandas()plt.plot(pr['recall'], pr['precision'])plt.xlabel('Recall')plt.ylabel('Precision')plt.show() # Plot the threshold-F-Measure curvefm = trainingSummary.fMeasureByThreshold.toPandas()plt.plot(fm['threshold'], fm['F-Measure'])plt.xlabel('Threshold')plt.ylabel('F-1 Score')plt.show() As we increase the prediction threshold the Recall starts dropping while the Precision score improves. It is common practice to visualize competing metrics against one another. Let’s use Cross Validation to tune our logistic regression model: # Create ParamGrid for Cross ValidationparamGrid = (ParamGridBuilder() .addGrid(lr.regParam, [0.01, 0.5, 2.0]) .addGrid(lr.elasticNetParam, [0.0, 0.5, 1.0]) .addGrid(lr.maxIter, [1, 5, 10]) .build())cv = CrossValidator(estimator=lr, estimatorParamMaps=paramGrid, evaluator=evaluator, numFolds=5)# Run cross validationscvModel = cv.fit(train)predictions = cvModel.transform(test)predictions_pandas = predictions.toPandas()print('Test Area Under PR: ', evaluator.evaluate(predictions))# Calculate and print f1, recall and precision scoresf1 = f1_score(predictions_pandas.label, predictions_pandas.prediction)recall = recall_score(predictions_pandas.label, predictions_pandas.prediction)precision = precision_score(predictions_pandas.label, predictions_pandas.prediction)print('F1-Score: {}, Recall: {}, Precision: {}'.format(f1, recall, precision)) After parameter tuning, the logistic regression shows the following performance: F1-Score: 0.66 Recall: 0.84 Precision: 0.54 Gradient-Boosted Trees are a popular classification method using ensembles of decision trees. Boosting algorithms are generally good choices for class imbalanced data. It is supported by PySpark’s MLlib, so let’s try it on our dataset: gbt = GBTClassifier()# Create ParamGrid for Cross ValidationparamGrid = (ParamGridBuilder() .addGrid(gbt.maxDepth, [2, 4, 6]) .addGrid(gbt.maxBins, [20, 60]) .addGrid(gbt.maxIter, [10, 20]) .build())cv = CrossValidator(estimator=gbt, estimatorParamMaps=paramGrid, evaluator=evaluator, numFolds=5)# Run cross validationscvModel = cv.fit(train)predictions = cvModel.transform(test)predictions_pandas = predictions.toPandas()print('Test Area Under PR: ', evaluator.evaluate(predictions))# Calculate and print f1, recall and precision scoresf1 = f1_score(predictions_pandas.label, predictions_pandas.prediction)recall = recall_score(predictions_pandas.label, predictions_pandas.prediction)precision = precision_score(predictions_pandas.label, predictions_pandas.prediction)print('F1-Score: {}, Recall: {}, Precision: {}'.format(f1, recall, precision)) After parameter tuning, the Gradient-Boosted Tree Classifier shows the following performance: F1-Score: 0.58 Recall: 0.56 Precision: 0.61 Decision trees are a popular family of classification and regression methods. dt = DecisionTreeClassifier(featuresCol = 'features', labelCol = 'label')# Create ParamGrid for Cross ValidationparamGrid = (ParamGridBuilder() .addGrid(dt.maxDepth, [2, 4, 6]) .addGrid(dt.maxBins, [20, 60]) .addGrid(dt.impurity, ['gini', 'entropy']) .build())cv = CrossValidator(estimator=dt, estimatorParamMaps=paramGrid, evaluator=evaluator, numFolds=5)# Run cross validationscvModel = cv.fit(train)predictions = cvModel.transform(test)predictions_pandas = predictions.toPandas()print('Test Area Under PR: ', evaluator.evaluate(predictions))# Calculate and print f1, recall and precision scoresf1 = f1_score(predictions_pandas.label, predictions_pandas.prediction)recall = recall_score(predictions_pandas.label, predictions_pandas.prediction)precision = precision_score(predictions_pandas.label, predictions_pandas.prediction)print('F1-Score: {}, Recall: {}, Precision: {}'.format(f1, recall, precision)) After parameter tuning, the Decision Tree Classifier shows the following performance: F1-Score: 0.56 Recall: 0.60 Precision: 0.52 The goal of this project was to exploit the capabilities of Apache Spark’s analytics engine for large-scale data processing to detect customers who are about to stop using Sparkify’s music streaming service. We applied the typical steps of the data science process like gaining understanding about the data, data preparation, modeling and evaluation. The logistic regression model shows the highest performance (F1-Score: 0.66, Recall: 0.84, Precision: 0.54). We are able to recall 84% of the churning customers and can provide them with special offers to keep them from deleting their Sparkify accounts. However, we need to consider a moderate Precision score of 54%. This means that, from all the customers which will receive special offers, 46% of those customers were actually satisfied with the service and would not need any special treatment. The source code for this post can be found on GitHub. I look forward to hearing any feedback or questions.
[ { "code": null, "e": 499, "s": 171, "text": "Predicting customer churn is a challenging and common problem that data scientists encounter these days. The ability to predict that a particular customer is at a high risk of churning, while there is still time to do something about it, represents a huge additional potential revenue source for every customer-facing business." }, { "code": null, "e": 1097, "s": 499, "text": "In this post, I will guide you through the creation of a machine learning solution which will be able to predict customer churn. This solution will be realized with Apache Spark. Apache Spark is a popular distributed data processing engine which can be deployed in a variety of ways, providing native bindings for Java, Scala, Python and R. It provides a stack of libraries including Spark SQL, Spark Streaming, MLlib for machine learning and GraphX for graph processing. For this project, we will focus on the machine learning library MLlib. We will use the Python API for Spark known as PySpark." }, { "code": null, "e": 1146, "s": 1097, "text": "If you read this article, you will learn how to:" }, { "code": null, "e": 1295, "s": 1146, "text": "load large datasets into Spark and manipulate them using Spark SQL and Spark Dataframes to engineer relevant features for predicting customer churn," }, { "code": null, "e": 1367, "s": 1295, "text": "use the machine learning APIs within Spark ML to build and tune models." }, { "code": null, "e": 2270, "s": 1367, "text": "Imagine you are working on the data team for a popular digital music service similar to Spotify. Let’s call it Sparkify. The users stream their favorite songs every day either using the free tier that places advertisements between the songs or using the premium subscription model where they stream music as free but pay a monthly flat rate. The users can upgrade, downgrade and cancel the service at any time. Every time the user interacts with the service like playing songs, logging out or liking a song with a thumbs-up, it generates data. All this data contains the key insights for keeping the users happy and helping the business thrive. It’s our job on the data team to predict which users are at risk to cancel their accounts. If we can accurately identify these users before they leave, our business can offer them discount and incentives, potentially saving our business millions in revenue." }, { "code": null, "e": 2550, "s": 2270, "text": "I used IBM Watson Studio (Default Spark Python 3.6 XS, one driver, two executors, Spark Version 2.3) to work on this project. The interaction with PySpark dataframes is not as convenient as it is with pandas dataframes. This is why I recommend installing and importing pixiedust:" }, { "code": null, "e": 2599, "s": 2550, "text": "!pip install --upgrade pixiedustimport pixiedust" }, { "code": null, "e": 2764, "s": 2599, "text": "pixiedustis an open-source Python helper library that works as an add-on to Jupyter notebooks and strongly improves the way we can interact with PySpark dataframes." }, { "code": null, "e": 3398, "s": 2764, "text": "import numpy as npimport pandas as pd%matplotlib inlineimport matplotlib.pyplot as pltimport datetimefrom sklearn.metrics import f1_score, recall_score, precision_scorefrom pyspark.sql import SparkSessionimport pyspark.sql.functions as Ffrom pyspark.sql.types import IntegerType, DoubleType, DateType, FloatTypefrom pyspark.ml.feature import VectorAssembler, MinMaxScalerfrom pyspark.ml import Pipelinefrom pyspark.ml.evaluation import BinaryClassificationEvaluatorfrom pyspark.ml.tuning import ParamGridBuilder, CrossValidatorfrom pyspark.ml.classification import LogisticRegression, DecisionTreeClassifier, GBTClassifier, LinearSVC" }, { "code": null, "e": 3455, "s": 3398, "text": "Create a Spark session and read in the Sparkify dataset:" }, { "code": null, "e": 3632, "s": 3455, "text": "# create a Spark sessionspark = SparkSession \\ .builder \\ .appName(\"Sparkify\") \\ .getOrCreate()# read in datasetdf = spark.read.json('medium-sparkify-event-data.json')" }, { "code": null, "e": 3715, "s": 3632, "text": "pixiedustnow comes in handy and we can display the first entries of the dataframe." }, { "code": null, "e": 3727, "s": 3715, "text": "display(df)" }, { "code": null, "e": 3754, "s": 3727, "text": "Have a peek at the schema:" }, { "code": null, "e": 3771, "s": 3754, "text": "df.printSchema()" }, { "code": null, "e": 4170, "s": 3771, "text": "The dataset holds information about how the users interact with the streaming platform, which songs they listened, which page they visited, their account status, etc. Any of the user interactions are stored with a UNIX timestamp which makes it possible to analyze changes in user behaviour over time. We will take advantage of that piece of information during the feature engineering process later." }, { "code": null, "e": 4241, "s": 4170, "text": "Next, we will perform EDA by doing basic manipulations within PySpark." }, { "code": null, "e": 4364, "s": 4241, "text": "In order to understand how the users interact with the music service, we might want to see which pages they view the most." }, { "code": null, "e": 4420, "s": 4364, "text": "df.groupBy('page').count().sort(F.desc('count')).show()" }, { "code": null, "e": 4781, "s": 4420, "text": "We can clearly see that “NextSong” is the most popular page view which makes perfect sense for a music service. However, there are many other page views which are going to be important for engineering relevant features from this raw dataset. We take the page “Cancellation Confirmation”, counting 99 visits, to create the label for the machine learning models." }, { "code": null, "e": 4944, "s": 4781, "text": "flag_cancellation_event = F.udf(lambda x: 1 if x == 'Cancellation Confirmation' else 0, IntegerType())df = df.withColumn('label', flag_cancellation_event('page'))" }, { "code": null, "e": 5012, "s": 4944, "text": "Based on the UNIX timestamp ts we can calculate statistics by hour." }, { "code": null, "e": 5147, "s": 5012, "text": "get_hour = F.udf(lambda x: datetime.datetime.fromtimestamp(x / 1000.0).hour, IntegerType())df = df.withColumn('hour', get_hour(df.ts))" }, { "code": null, "e": 5279, "s": 5147, "text": "Since matplotlib does not work with PySpark dataframes we convert it back to a pandas dataframe and plot the user activity by hour." }, { "code": null, "e": 5675, "s": 5279, "text": "# Count the events per hoursongs_by_hour = df.groupBy('hour').count().orderBy(df.hour)songs_by_hour_pd = songs_by_hour.toPandas()songs_by_hour_pd.hour = pd.to_numeric(songs_by_hour_pd.hour)# Plot the events per hour aggregationplt.scatter(songs_by_hour_pd['hour'], songs_by_hour_pd['count'])plt.xlim(-1, 24)plt.ylim(0, 1.2 * max(songs_by_hour_pd['count']))plt.xlabel('Hour')plt.ylabel('Events');" }, { "code": null, "e": 6089, "s": 5675, "text": "Feature engineering plays a key role in big data analytics. Machine learning and data mining algorithms cannot work without data. Little can be achieved if there are few features to represent the underlying data objects, and the quality of results of those algorithms largely depends on the quality of the available features.Accordingly, we start building out the features we find promising to train the model on." }, { "code": null, "e": 6294, "s": 6089, "text": "To this end, we create a new PySpark dataframe feature_df from scratch, each row representing a user. We will create features from the dataframe df and join those sequentially to the dataframe feature_df." }, { "code": null, "e": 6375, "s": 6294, "text": "Based on the column label in df we can separate the churned users from the rest." }, { "code": null, "e": 6704, "s": 6375, "text": "churned_collect = df.where(df.label==1).select('userId').collect()churned_users = set([int(row.userId) for row in churned_collect])all_collect = df.select('userId').collect()all_users = set([int(row.userId) for row in all_collect])feature_df = spark.createDataFrame(all_users, IntegerType()).withColumnRenamed('value', 'userId')" }, { "code": null, "e": 6870, "s": 6704, "text": "# Create label columncreate_churn = F.udf(lambda x: 1 if x in churned_users else 0, IntegerType())feature_df = feature_df.withColumn('label', create_churn('userId'))" }, { "code": null, "e": 7513, "s": 6870, "text": "# Create binary gender columnconvert_gender = F.udf(lambda x: 1 if x == 'M' else 0, IntegerType())df = df.withColumn('GenderBinary', convert_gender('Gender'))# Add gender as featurefeature_df = feature_df.join(df.select(['userId', 'GenderBinary']), 'userId') \\ .dropDuplicates(subset=['userId']) \\ .sort('userId')convert_level = F.udf(lambda x: 1 if x == 'free' else 0, IntegerType())df = df.withColumn('LevelBinary', convert_level('Level'))# Add customer level as featurefeature_df = feature_df.join(df.select(['userId', 'ts', 'LevelBinary']), 'userId') \\ .sort(F.desc('ts')) \\ .dropDuplicates(subset=['userId']) \\ .drop('ts')" }, { "code": null, "e": 7740, "s": 7513, "text": "Every time the users interact with the platform, it generates data. This means that we know exactly what each of the users experienced during the period of this data extract. My approach is to divide the pages into categories:" }, { "code": null, "e": 7820, "s": 7740, "text": "Neutral pages: “Cancel”, “Home”, “Logout”, “Save Settings”, “About”, “Settings”" }, { "code": null, "e": 7882, "s": 7820, "text": "Negative pages: “Thumbs Down”, “Roll Advert”, “Help”, “Error”" }, { "code": null, "e": 7955, "s": 7882, "text": "Positive pages: “Add to Playlist”, “Add Friend”, “NextSong”, “Thumbs Up”" }, { "code": null, "e": 8004, "s": 7955, "text": "Downgrade pages: “Submit Downgrade”, “Downgrade”" }, { "code": null, "e": 8047, "s": 8004, "text": "Upgrade pages: “Submit Upgrade”, “Upgrade”" }, { "code": null, "e": 8270, "s": 8047, "text": "The reasoning behind this approach is that we can count how often a user had an interaction e.g. with a positive page. We could have done this for every page separately but this would result in a much higher feature space." }, { "code": null, "e": 8296, "s": 8270, "text": "Let’s put this into code:" }, { "code": null, "e": 9427, "s": 8296, "text": "# Create a dictonary which maps page views and PySpark dataframes pages = {}pages['neutralPages'] = df.filter((df.page == 'Cancel') | (df.page == 'Home') | (df.page == 'Logout') \\ | (df.page == 'Save Settings') | (df.page == 'About') | (df.page == 'Settings'))pages['negativePages'] = df.filter((df.page == 'Thumbs Down') | (df.page == 'Roll Advert') | (df.page == 'Help') \\ | (df.page == 'Error'))pages['positivePages'] = df.filter((df.page == 'Add to Playlist') | (df.page == 'Add Friend') | (df.page == 'NextSong') \\ | (df.page == 'Thumbs Up'))pages['downgradePages'] = df.filter((df.page == 'Submit Downgrade') | (df.page == 'Downgrade'))pages['upgradePages'] = df.filter((df.page == 'Upgrade') | (df.page == 'Submit Upgrade'))# Loop through page views and aggregate the counts by userfor key, value in pages.items(): value_df = value.select('userId') \\ .groupBy('userId') \\ .agg({'userId':'count'}) \\ .withColumnRenamed('count(userId)', key) # Add page view aggregations as features feature_df = feature_df.join(value_df, 'userId', 'left').sort('userId') \\ .fillna({key:'0'})" }, { "code": null, "e": 9505, "s": 9427, "text": "Next, we will calculate how many days the users interacted with the platform:" }, { "code": null, "e": 9851, "s": 9505, "text": "# Create dataframe with users and date countsdateCount_df = df.select('userId', 'date') \\ .groupby('userId') \\ .agg(F.countDistinct('date')) \\ .withColumnRenamed('count(DISTINCT date)', 'dateCount')# Add date count as featurefeature_df = feature_df.join(dateCount_df, 'userId', 'left').sort('userId') \\ .fillna({'dateCount':'1'})" }, { "code": null, "e": 10300, "s": 9851, "text": "These page view features are absolute values counting the number of occurrences. However, this can lead to misleading results if some users signed up at the end of the data extract while others used the platform from the very beginning. For this purpose, we will make the aggregated results comparable by dividing them through the user-specific time window, obtaining counts/day. I skip the code at this place, the full code is available on GitHub." }, { "code": null, "e": 10638, "s": 10300, "text": "Another promising feature is how the user interactions change over time. First, we calculate the number of user interactions per day. Second, we fit one linear regression model per user using numpy.polyfit. We will take the slopes of these lines, remove outliers and plug the scaled slopes as features into the classification algorithms." }, { "code": null, "e": 11235, "s": 10638, "text": "# Create dataframe with users and their activity per dayactivity_df = df.select('userId', 'date') \\ .groupby('userID', 'date') \\ .count()# initialize slopesslopes = []for user in all_users: # Create pandas dataframe for slope calculation activity_pandas = activity_df.filter(activity_df['userID'] == user).sort(F.asc('date')).toPandas() if activity_pandas.shape[0]==1: slopes.append(0) continue # Fit a line through the user activity counts and retrieve its slope slope = np.polyfit(activity_pandas.index, activity_pandas['count'], 1)[0] slopes.append(slope)" }, { "code": null, "e": 11467, "s": 11235, "text": "As a final step for the feature engineering process we will iterate over the created features and scale them using MinMaxScaler. Afterwards, we put the features into one vector so that we can plug it into the pyspark.ml algorithms." }, { "code": null, "e": 12837, "s": 11467, "text": "# UDF for converting column type from vector to double typeunlist = F.udf(lambda x: round(float(list(x)[0]),3), DoubleType())# Iterate over columns to be scaledfor i in ['neutralPagesNormalized', 'negativePagesNormalized', 'positivePagesNormalized', 'downgradePagesNormalized', 'upgradePagesNormalized', 'dateCountNormalized', 'hourAvg', 'UserActiveTime', 'Slope']: # VectorAssembler Transformation - Convert column to vector type assembler = VectorAssembler(inputCols=[i],outputCol=i+\"_Vect\") # MinMaxScaler Transformation scaler = MinMaxScaler(inputCol=i+\"_Vect\", outputCol=i+\"_Scaled\") # Pipeline of VectorAssembler and MinMaxScaler pipeline = Pipeline(stages=[assembler, scaler]) # Fitting pipeline on dataframe feature_df = pipeline.fit(feature_df).transform(feature_df) \\ .withColumn(i+\"_Scaled\", unlist(i+\"_Scaled\")).drop(i+\"_Vect\")# Merge columns to one feature vectorassembler = VectorAssembler(inputCols=['neutralPagesNormalized_Scaled', 'negativePagesNormalized_Scaled', 'positivePagesNormalized_Scaled', 'downgradePagesNormalized_Scaled', 'upgradePagesNormalized_Scaled', 'dateCountNormalized_Scaled', 'hourAvg_Scaled', 'UserActiveTime_Scaled', 'Slope_Scaled', 'LevelBinary', 'GenderBinary'], outputCol='features')feature_df = assembler.transform(feature_df)" }, { "code": null, "e": 12873, "s": 12837, "text": "Following the schema of feature_df:" }, { "code": null, "e": 12943, "s": 12873, "text": "The features column holds the combined features vector for each user:" }, { "code": null, "e": 13292, "s": 12943, "text": "After the creation of features, we can move on and split the full dataset into training and testing. We will test out several common machine learning methods used for classification tasks. The accuracy of the models will be evaluated and parameters tuned accordingly. Based on the F1-Score, Precision and Recall we will determine the winning model." }, { "code": null, "e": 13378, "s": 13292, "text": "Split the features dataframe into training and testing and check for class imbalance." }, { "code": null, "e": 13488, "s": 13378, "text": "train, test = feature_df.randomSplit([0.7, 0.3], seed = 42)plt.hist(feature_df.toPandas()['label'])plt.show()" }, { "code": null, "e": 13688, "s": 13488, "text": "It is crucial to check for potential class imbalance in the data. It is extremely common in practice and many classification learning algorithms have low predictive accuracy for the infrequent class." }, { "code": null, "e": 13790, "s": 13688, "text": "Spark’s MLlib supports tools for model selection such as CrossValidator. This requires the following:" }, { "code": null, "e": 13823, "s": 13790, "text": "Estimator: algorithm or pipeline" }, { "code": null, "e": 13872, "s": 13823, "text": "Set of parameters: parameter grid to search over" }, { "code": null, "e": 13951, "s": 13872, "text": "Evaluator: metric to measure how well a fitted model does on the test dataset." }, { "code": null, "e": 14027, "s": 13951, "text": "The estimators and parameters will be set for each classifier specifically." }, { "code": null, "e": 14357, "s": 14027, "text": "For evaluation, we take the BinaryClassificationEvaluator which supports the “areaUnderROC” and the “areaUnderPR”. Since we have a class imbalance in the data, we take the “areaUnderPR” as our evaluation metric because the PR curve is more informative in this case (cf. http://pages.cs.wisc.edu/~jdavis/davisgoadrichcamera2.pdf)." }, { "code": null, "e": 14555, "s": 14357, "text": "Since the class BinaryClassificationEvaluator from pyspark.ml.evaluation only provides the metrics “areaUnderPR” and “areaUnderROC”, we will compute the F1-Score, Precision and Recall with sklearn." }, { "code": null, "e": 14625, "s": 14555, "text": "evaluator = BinaryClassificationEvaluator(metricName = 'areaUnderPR')" }, { "code": null, "e": 14645, "s": 14625, "text": "Logistic Regression" }, { "code": null, "e": 15121, "s": 14645, "text": "Logistic regression is basically a linear regression model which explains the relationship between dependent variables and one or more nominal, ordinal, interval or ratio-level independent variables with only difference being, the output for linear regression is a number that has its real meaning (a label) while the output of a logistic regression is a number that represents the probability of the event happening (i.e. the probability of a customer deleting its account)." }, { "code": null, "e": 15536, "s": 15121, "text": "Before instantiating the logistic regression object we calculate a balancing ratio to account for the class imbalance. We use the weightCol parameter to over-/under-sample training instances according to the pre-calculated ratios. We want to “under-sample” the negative class and “over-sample” the positive class. The logistic loss objective function should treat the negative class (label == 0) with lower weight." }, { "code": null, "e": 15913, "s": 15536, "text": "# Calculate a balancing ratio to account for the class imbalancebalancing_ratio = train.filter(train['label']==0).count()/train.count()train=train.withColumn(\"classWeights\", F.when(train.label == 1,balancing_ratio).otherwise(1-balancing_ratio))# Create a logistic regression objectlr = LogisticRegression(featuresCol = 'features', labelCol = 'label', weightCol=\"classWeights\")" }, { "code": null, "e": 16147, "s": 15913, "text": "For logistic regression, pyspark.ml supports extracting a trainingSummaryof the model over the training set. This does not work with a fitted CrossValidator object which is why we take it from a fitted model without parameter tuning." }, { "code": null, "e": 16204, "s": 16147, "text": "lrModel = lr.fit(train)trainingSummary = lrModel.summary" }, { "code": null, "e": 16549, "s": 16204, "text": "We can use it to plot the threshold-Recall curve, threshold-Precision curve, Recall-Precision curve and threshold-F-Measure curve to examine how our model performs. This threshold is a prediction threshold which determines the predicted class based on the probabilities that the model outputs. Model optimization includes tuning this threshold." }, { "code": null, "e": 16724, "s": 16549, "text": "# Plot the threshold-recall curvetr = trainingSummary.recallByThreshold.toPandas()plt.plot(tr['threshold'], tr['recall'])plt.xlabel('Threshold')plt.ylabel('Recall')plt.show()" }, { "code": null, "e": 16911, "s": 16724, "text": "# Plot the threshold-precision curvetp = trainingSummary.precisionByThreshold.toPandas()plt.plot(tp['threshold'], tp['precision'])plt.xlabel('Threshold')plt.ylabel('Precision')plt.show()" }, { "code": null, "e": 17071, "s": 16911, "text": "# Plot the recall-precision curvepr = trainingSummary.pr.toPandas()plt.plot(pr['recall'], pr['precision'])plt.xlabel('Recall')plt.ylabel('Precision')plt.show()" }, { "code": null, "e": 17257, "s": 17071, "text": "# Plot the threshold-F-Measure curvefm = trainingSummary.fMeasureByThreshold.toPandas()plt.plot(fm['threshold'], fm['F-Measure'])plt.xlabel('Threshold')plt.ylabel('F-1 Score')plt.show()" }, { "code": null, "e": 17434, "s": 17257, "text": "As we increase the prediction threshold the Recall starts dropping while the Precision score improves. It is common practice to visualize competing metrics against one another." }, { "code": null, "e": 17500, "s": 17434, "text": "Let’s use Cross Validation to tune our logistic regression model:" }, { "code": null, "e": 18395, "s": 17500, "text": "# Create ParamGrid for Cross ValidationparamGrid = (ParamGridBuilder() .addGrid(lr.regParam, [0.01, 0.5, 2.0]) .addGrid(lr.elasticNetParam, [0.0, 0.5, 1.0]) .addGrid(lr.maxIter, [1, 5, 10]) .build())cv = CrossValidator(estimator=lr, estimatorParamMaps=paramGrid, evaluator=evaluator, numFolds=5)# Run cross validationscvModel = cv.fit(train)predictions = cvModel.transform(test)predictions_pandas = predictions.toPandas()print('Test Area Under PR: ', evaluator.evaluate(predictions))# Calculate and print f1, recall and precision scoresf1 = f1_score(predictions_pandas.label, predictions_pandas.prediction)recall = recall_score(predictions_pandas.label, predictions_pandas.prediction)precision = precision_score(predictions_pandas.label, predictions_pandas.prediction)print('F1-Score: {}, Recall: {}, Precision: {}'.format(f1, recall, precision))" }, { "code": null, "e": 18476, "s": 18395, "text": "After parameter tuning, the logistic regression shows the following performance:" }, { "code": null, "e": 18491, "s": 18476, "text": "F1-Score: 0.66" }, { "code": null, "e": 18504, "s": 18491, "text": "Recall: 0.84" }, { "code": null, "e": 18520, "s": 18504, "text": "Precision: 0.54" }, { "code": null, "e": 18756, "s": 18520, "text": "Gradient-Boosted Trees are a popular classification method using ensembles of decision trees. Boosting algorithms are generally good choices for class imbalanced data. It is supported by PySpark’s MLlib, so let’s try it on our dataset:" }, { "code": null, "e": 19652, "s": 18756, "text": "gbt = GBTClassifier()# Create ParamGrid for Cross ValidationparamGrid = (ParamGridBuilder() .addGrid(gbt.maxDepth, [2, 4, 6]) .addGrid(gbt.maxBins, [20, 60]) .addGrid(gbt.maxIter, [10, 20]) .build())cv = CrossValidator(estimator=gbt, estimatorParamMaps=paramGrid, evaluator=evaluator, numFolds=5)# Run cross validationscvModel = cv.fit(train)predictions = cvModel.transform(test)predictions_pandas = predictions.toPandas()print('Test Area Under PR: ', evaluator.evaluate(predictions))# Calculate and print f1, recall and precision scoresf1 = f1_score(predictions_pandas.label, predictions_pandas.prediction)recall = recall_score(predictions_pandas.label, predictions_pandas.prediction)precision = precision_score(predictions_pandas.label, predictions_pandas.prediction)print('F1-Score: {}, Recall: {}, Precision: {}'.format(f1, recall, precision))" }, { "code": null, "e": 19746, "s": 19652, "text": "After parameter tuning, the Gradient-Boosted Tree Classifier shows the following performance:" }, { "code": null, "e": 19761, "s": 19746, "text": "F1-Score: 0.58" }, { "code": null, "e": 19774, "s": 19761, "text": "Recall: 0.56" }, { "code": null, "e": 19790, "s": 19774, "text": "Precision: 0.61" }, { "code": null, "e": 19868, "s": 19790, "text": "Decision trees are a popular family of classification and regression methods." }, { "code": null, "e": 20824, "s": 19868, "text": "dt = DecisionTreeClassifier(featuresCol = 'features', labelCol = 'label')# Create ParamGrid for Cross ValidationparamGrid = (ParamGridBuilder() .addGrid(dt.maxDepth, [2, 4, 6]) .addGrid(dt.maxBins, [20, 60]) .addGrid(dt.impurity, ['gini', 'entropy']) .build())cv = CrossValidator(estimator=dt, estimatorParamMaps=paramGrid, evaluator=evaluator, numFolds=5)# Run cross validationscvModel = cv.fit(train)predictions = cvModel.transform(test)predictions_pandas = predictions.toPandas()print('Test Area Under PR: ', evaluator.evaluate(predictions))# Calculate and print f1, recall and precision scoresf1 = f1_score(predictions_pandas.label, predictions_pandas.prediction)recall = recall_score(predictions_pandas.label, predictions_pandas.prediction)precision = precision_score(predictions_pandas.label, predictions_pandas.prediction)print('F1-Score: {}, Recall: {}, Precision: {}'.format(f1, recall, precision))" }, { "code": null, "e": 20910, "s": 20824, "text": "After parameter tuning, the Decision Tree Classifier shows the following performance:" }, { "code": null, "e": 20925, "s": 20910, "text": "F1-Score: 0.56" }, { "code": null, "e": 20938, "s": 20925, "text": "Recall: 0.60" }, { "code": null, "e": 20954, "s": 20938, "text": "Precision: 0.52" }, { "code": null, "e": 21162, "s": 20954, "text": "The goal of this project was to exploit the capabilities of Apache Spark’s analytics engine for large-scale data processing to detect customers who are about to stop using Sparkify’s music streaming service." }, { "code": null, "e": 21305, "s": 21162, "text": "We applied the typical steps of the data science process like gaining understanding about the data, data preparation, modeling and evaluation." }, { "code": null, "e": 21804, "s": 21305, "text": "The logistic regression model shows the highest performance (F1-Score: 0.66, Recall: 0.84, Precision: 0.54). We are able to recall 84% of the churning customers and can provide them with special offers to keep them from deleting their Sparkify accounts. However, we need to consider a moderate Precision score of 54%. This means that, from all the customers which will receive special offers, 46% of those customers were actually satisfied with the service and would not need any special treatment." } ]
Categorical Data. Strategies for working with discrete... | by Dipanjan (DJ) Sarkar | Towards Data Science
We covered various feature engineering strategies for dealing with structured continuous numeric data in the previous article in this series. In this article, we will look at another type of structured data, which is discrete in nature and is popularly termed as categorical data. Dealing with numeric data is often easier than categorical data given that we do not have to deal with additional complexities of the semantics pertaining to each category value in any data attribute which is of a categorical type. We will use a hands-on approach to discuss several encoding schemes for dealing with categorical data and also a couple of popular techniques for dealing with large scale feature explosion, often known as the “curse of dimensionality”. I’m sure by now you must realize the motivation and the importance of feature engineering, we do stress on the same in detail in ‘Part 1’ of this series. Do check it out for a quick refresher if necessary. In short, machine learning algorithms cannot work directly with categorical data and you do need to do some amount of engineering and transformations on this data before you can start modeling on your data. Let’s get an idea about categorical data representations before diving into feature engineering strategies. Typically, any data attribute which is categorical in nature represents discrete values which belong to a specific finite set of categories or classes. These are also often known as classes or labels in the context of attributes or variables which are to be predicted by a model (popularly known as response variables). These discrete values can be text or numeric in nature (or even unstructured data like images!). There are two major classes of categorical data, nominal and ordinal. In any nominal categorical data attribute, there is no concept of ordering amongst the values of that attribute. Consider a simple example of weather categories, as depicted in the following figure. We can see that we have six major classes or categories in this particular scenario without any concept or notion of order (windy doesn’t always occur before sunny nor is it smaller or bigger than sunny). Similarly movie, music and video game genres, country names, food and cuisine types are other examples of nominal categorical attributes. Ordinal categorical attributes have some sense or notion of order amongst its values. For instance look at the following figure for shirt sizes. It is quite evident that order or in this case ‘size’ matters when thinking about shirts (S is smaller than M which is smaller than L and so on). Shoe sizes, education level and employment roles are some other examples of ordinal categorical attributes. Having a decent idea about categorical data, let’s now look at some feature engineering strategies. While a lot of advancements have been made in various machine learning frameworks to accept complex categorical data types like text labels. Typically any standard workflow in feature engineering involves some form of transformation of these categorical values into numeric labels and then applying some encoding scheme on these values. We load up the necessary essentials before getting started. import pandas as pdimport numpy as np Nominal attributes consist of discrete categorical values with no notion or sense of order amongst them. The idea here is to transform these attributes into a more representative numerical format which can be easily understood by downstream code and pipelines. Let’s look at a new dataset pertaining to video game sales. This dataset is also available on Kaggle as well as in my GitHub repository. vg_df = pd.read_csv('datasets/vgsales.csv', encoding='utf-8')vg_df[['Name', 'Platform', 'Year', 'Genre', 'Publisher']].iloc[1:7] Let’s focus on the video game Genre attribute as depicted in the above data frame. It is quite evident that this is a nominal categorical attribute just like Publisher and Platform. We can easily get the list of unique video game genres as follows. genres = np.unique(vg_df['Genre'])genresOutput------array(['Action', 'Adventure', 'Fighting', 'Misc', 'Platform', 'Puzzle', 'Racing', 'Role-Playing', 'Shooter', 'Simulation', 'Sports', 'Strategy'], dtype=object) This tells us that we have 12 distinct video game genres. We can now generate a label encoding scheme for mapping each category to a numeric value by leveraging scikit-learn. from sklearn.preprocessing import LabelEncodergle = LabelEncoder()genre_labels = gle.fit_transform(vg_df['Genre'])genre_mappings = {index: label for index, label in enumerate(gle.classes_)}genre_mappingsOutput------{0: 'Action', 1: 'Adventure', 2: 'Fighting', 3: 'Misc', 4: 'Platform', 5: 'Puzzle', 6: 'Racing', 7: 'Role-Playing', 8: 'Shooter', 9: 'Simulation', 10: 'Sports', 11: 'Strategy'} Thus a mapping scheme has been generated where each genre value is mapped to a number with the help of the LabelEncoder object gle. The transformed labels are stored in the genre_labels value which we can write back to our data frame. vg_df['GenreLabel'] = genre_labelsvg_df[['Name', 'Platform', 'Year', 'Genre', 'GenreLabel']].iloc[1:7] These labels can be used directly often especially with frameworks like scikit-learn if you plan to use them as response variables for prediction, however as discussed earlier, we will need an additional step of encoding on these before we can use them as features. Ordinal attributes are categorical attributes with a sense of order amongst the values. Let’s consider our Pokémon dataset which we used in Part 1 of this series. Let’s focus more specifically on the Generation attribute. poke_df = pd.read_csv('datasets/Pokemon.csv', encoding='utf-8')poke_df = poke_df.sample(random_state=1, frac=1).reset_index(drop=True)np.unique(poke_df['Generation'])Output------array(['Gen 1', 'Gen 2', 'Gen 3', 'Gen 4', 'Gen 5', 'Gen 6'], dtype=object) Based on the above output, we can see there are a total of 6 generations and each Pokémon typically belongs to a specific generation based on the video games (when they were released) and also the television series follows a similar timeline. This attribute is typically ordinal (domain knowledge is necessary here) because most Pokémon belonging to Generation 1 were introduced earlier in the video games and the television shows than Generation 2 as so on. Fans can check out the following figure to remember some of the popular Pokémon of each generation (views may differ among fans!). Hence they have a sense of order amongst them. In general, there is no generic module or function to map and transform these features into numeric representations based on order automatically. Hence we can use a custom encoding\mapping scheme. gen_ord_map = {'Gen 1': 1, 'Gen 2': 2, 'Gen 3': 3, 'Gen 4': 4, 'Gen 5': 5, 'Gen 6': 6}poke_df['GenerationLabel'] = poke_df['Generation'].map(gen_ord_map)poke_df[['Name', 'Generation', 'GenerationLabel']].iloc[4:10] It is quite evident from the above code that the map(...) function from pandas is quite helpful in transforming this ordinal feature. If you remember what we mentioned earlier, typically feature engineering on categorical data involves a transformation process which we depicted in the previous section and a compulsory encoding process where we apply specific encoding schemes to create dummy variables or features for each category\value in a specific categorical attribute. You might be wondering, we just converted categories to numerical labels in the previous section, why on earth do we need this now? The reason is quite simple. Considering video game genres, if we directly fed the GenreLabel attribute as a feature in a machine learning model, it would consider it to be a continuous numeric feature thinking value 10 (Sports) is greater than 6 (Racing) but that is meaningless because the Sports genre is certainly not bigger or smaller than Racing, these are essentially different values or categories which cannot be compared directly. Hence we need an additional layer of encoding schemes where dummy features are created for each unique value or category out of all the distinct categories per attribute. Considering we have the numeric representation of any categorical attribute with m labels (after transformation), the one-hot encoding scheme, encodes or transforms the attribute into m binary features which can only contain a value of 1 or 0. Each observation in the categorical feature is thus converted into a vector of size m with only one of the values as 1 (indicating it as active). Let’s take a subset of our Pokémon dataset depicting two attributes of interest. poke_df[['Name', 'Generation', 'Legendary']].iloc[4:10] The attributes of interest are Pokémon Generation and their Legendary status. The first step is to transform these attributes into numeric representations based on what we learnt earlier. from sklearn.preprocessing import OneHotEncoder, LabelEncoder# transform and map pokemon generationsgen_le = LabelEncoder()gen_labels = gen_le.fit_transform(poke_df['Generation'])poke_df['Gen_Label'] = gen_labels# transform and map pokemon legendary statusleg_le = LabelEncoder()leg_labels = leg_le.fit_transform(poke_df['Legendary'])poke_df['Lgnd_Label'] = leg_labelspoke_df_sub = poke_df[['Name', 'Generation', 'Gen_Label', 'Legendary', 'Lgnd_Label']]poke_df_sub.iloc[4:10] The features Gen_Label and Lgnd_Label now depict the numeric representations of our categorical features. Let’s now apply the one-hot encoding scheme on these features. # encode generation labels using one-hot encoding schemegen_ohe = OneHotEncoder()gen_feature_arr = gen_ohe.fit_transform( poke_df[['Gen_Label']]).toarray()gen_feature_labels = list(gen_le.classes_)gen_features = pd.DataFrame(gen_feature_arr, columns=gen_feature_labels)# encode legendary status labels using one-hot encoding schemeleg_ohe = OneHotEncoder()leg_feature_arr = leg_ohe.fit_transform( poke_df[['Lgnd_Label']]).toarray()leg_feature_labels = ['Legendary_'+str(cls_label) for cls_label in leg_le.classes_]leg_features = pd.DataFrame(leg_feature_arr, columns=leg_feature_labels) In general, you can always encode both the features together using the fit_transform(...) function by passing it a two dimensional array of the two features together (Check out the documentation!). But we encode each feature separately, to make things easier to understand. Besides this, we can also create separate data frames and label them accordingly. Let’s now concatenate these feature frames and see the final result. poke_df_ohe = pd.concat([poke_df_sub, gen_features, leg_features], axis=1)columns = sum([['Name', 'Generation', 'Gen_Label'], gen_feature_labels, ['Legendary', 'Lgnd_Label'], leg_feature_labels], [])poke_df_ohe[columns].iloc[4:10] Thus you can see that 6 dummy variables or binary features have been created for Generation and 2 for Legendary since those are the total number of distinct categories in each of these attributes respectively. Active state of a category is indicated by the 1 value in one of these dummy variables which is quite evident from the above data frame. Consider you built this encoding scheme on your training data and built some model and now you have some new data which has to be engineered for features before predictions as follows. new_poke_df = pd.DataFrame([['PikaZoom', 'Gen 3', True], ['CharMyToast', 'Gen 4', False]], columns=['Name', 'Generation', 'Legendary'])new_poke_df You can leverage scikit-learn’s excellent API here by calling the transform(...) function of the previously build LabeLEncoder and OneHotEncoder objects on the new data. Remember our workflow, first we do the transformation. new_gen_labels = gen_le.transform(new_poke_df['Generation'])new_poke_df['Gen_Label'] = new_gen_labelsnew_leg_labels = leg_le.transform(new_poke_df['Legendary'])new_poke_df['Lgnd_Label'] = new_leg_labelsnew_poke_df[['Name', 'Generation', 'Gen_Label', 'Legendary', 'Lgnd_Label']] Once we have numerical labels, let’s apply the encoding scheme now! new_gen_feature_arr = gen_ohe.transform(new_poke_df[['Gen_Label']]).toarray()new_gen_features = pd.DataFrame(new_gen_feature_arr, columns=gen_feature_labels)new_leg_feature_arr = leg_ohe.transform(new_poke_df[['Lgnd_Label']]).toarray()new_leg_features = pd.DataFrame(new_leg_feature_arr, columns=leg_feature_labels)new_poke_ohe = pd.concat([new_poke_df, new_gen_features, new_leg_features], axis=1)columns = sum([['Name', 'Generation', 'Gen_Label'], gen_feature_labels, ['Legendary', 'Lgnd_Label'], leg_feature_labels], [])new_poke_ohe[columns] Thus you can see it’s quite easy to apply this scheme on new data easily by leveraging scikit-learn’s powerful API. You can also apply the one-hot encoding scheme easily by leveraging the to_dummies(...) function from pandas. gen_onehot_features = pd.get_dummies(poke_df['Generation'])pd.concat([poke_df[['Name', 'Generation']], gen_onehot_features], axis=1).iloc[4:10] The above data frame depicts the one-hot encoding scheme applied on the Generation attribute and the results are same as compared to the earlier results as expected. The dummy coding scheme is similar to the one-hot encoding scheme, except in the case of dummy coding scheme, when applied on a categorical feature with m distinct labels, we get m - 1 binary features. Thus each value of the categorical variable gets converted into a vector of size m - 1. The extra feature is completely disregarded and thus if the category values range from {0, 1, ..., m-1} the 0th or the m - 1th feature column is dropped and corresponding category values are usually represented by a vector of all zeros (0). Let’s try applying dummy coding scheme on Pokémon Generation by dropping the first level binary encoded feature (Gen 1). gen_dummy_features = pd.get_dummies(poke_df['Generation'], drop_first=True)pd.concat([poke_df[['Name', 'Generation']], gen_dummy_features], axis=1).iloc[4:10] If you want, you can also choose to drop the last level binary encoded feature (Gen 6) as follows. gen_onehot_features = pd.get_dummies(poke_df['Generation'])gen_dummy_features = gen_onehot_features.iloc[:,:-1]pd.concat([poke_df[['Name', 'Generation']], gen_dummy_features], axis=1).iloc[4:10] Based on the above depictions, it is quite clear that categories belonging to the dropped feature are represented as a vector of zeros (0) like we discussed earlier. The effect coding scheme is actually very similar to the dummy coding scheme, except during the encoding process, the encoded features or feature vector, for the category values which represent all 0 in the dummy coding scheme, is replaced by -1 in the effect coding scheme. This will become clearer with the following example. gen_onehot_features = pd.get_dummies(poke_df['Generation'])gen_effect_features = gen_onehot_features.iloc[:,:-1]gen_effect_features.loc[np.all(gen_effect_features == 0, axis=1)] = -1.pd.concat([poke_df[['Name', 'Generation']], gen_effect_features], axis=1).iloc[4:10] The above output clearly shows that the Pokémon belonging to Generation 6 are now represented by a vector of -1 values as compared to zeros in dummy coding. The encoding schemes we discussed so far, work quite well on categorical data in general, but they start causing problems when the number of distinct categories in any feature becomes very large. Essential for any categorical feature of m distinct labels, you get m separate features. This can easily increase the size of the feature set causing problems like storage issues, model training problems with regard to time, space and memory. Besides this, we also have to deal with what is popularly known as the ‘curse of dimensionality’ where basically with an enormous number of features and not enough representative samples, model performance starts getting affected often leading to overfitting. Hence we need to look towards other categorical data feature engineering schemes for features having a large number of possible categories (like IP addresses). The bin-counting scheme is a useful scheme for dealing with categorical variables having many categories. In this scheme, instead of using the actual label values for encoding, we use probability based statistical information about the value and the actual target or response value which we aim to predict in our modeling efforts. A simple example would be based on past historical data for IP addresses and the ones which were used in DDOS attacks; we can build probability values for a DDOS attack being caused by any of the IP addresses. Using this information, we can encode an input feature which depicts that if the same IP address comes in the future, what is the probability value of a DDOS attack being caused. This scheme needs historical data as a pre-requisite and is an elaborate one. Depicting this with a complete example would be currently difficult here but there are several resources online which you can refer to for the same. The feature hashing scheme is another useful feature engineering scheme for dealing with large scale categorical features. In this scheme, a hash function is typically used with the number of encoded features pre-set (as a vector of pre-defined length) such that the hashed values of the features are used as indices in this pre-defined vector and values are updated accordingly. Since a hash function maps a large number of values into a small finite set of values, multiple different values might create the same hash which is termed as collisions. Typically, a signed hash function is used so that the sign of the value obtained from the hash is used as the sign of the value which is stored in the final feature vector at the appropriate index. This should ensure lesser collisions and lesser accumulation of error due to collisions. Hashing schemes work on strings, numbers and other structures like vectors. You can think of hashed outputs as a finite set of b bins such that when hash function is applied on the same values\categories, they get assigned to the same bin (or subset of bins) out of the b bins based on the hash value. We can pre-define the value of b which becomes the final size of the encoded feature vector for each categorical attribute that we encode using the feature hashing scheme. Thus even if we have over 1000 distinct categories in a feature and we set b=10 as the final feature vector size, the output feature set will still have only 10 features as compared to 1000 binary features if we used a one-hot encoding scheme. Let’s consider the Genre attribute in our video game dataset. unique_genres = np.unique(vg_df[['Genre']])print("Total game genres:", len(unique_genres))print(unique_genres)Output------Total game genres: 12['Action' 'Adventure' 'Fighting' 'Misc' 'Platform' 'Puzzle' 'Racing' 'Role-Playing' 'Shooter' 'Simulation' 'Sports' 'Strategy'] We can see that there are a total of 12 genres of video games. If we used a one-hot encoding scheme on the Genre feature, we would end up having 12 binary features. Instead, we will now use a feature hashing scheme by leveraging scikit-learn’s FeatureHasher class, which uses a signed 32-bit version of the Murmurhash3 hash function. We will pre-define the final feature vector size to be 6 in this case. from sklearn.feature_extraction import FeatureHasherfh = FeatureHasher(n_features=6, input_type='string')hashed_features = fh.fit_transform(vg_df['Genre'])hashed_features = hashed_features.toarray()pd.concat([vg_df[['Name', 'Genre']], pd.DataFrame(hashed_features)], axis=1).iloc[1:7] Based on the above output, the Genre categorical attribute has been encoded using the hashing scheme into 6 features instead of 12. We can also see that rows 1 and 6 denote the same genre of games, Platform which have been rightly encoded into the same feature vector. These examples should give you a good idea about popular strategies for feature engineering on discrete, categorical data. If you read Part 1 of this series, you would have seen that it is slightly challenging to work with categorical data as compared to continuous, numeric data but definitely interesting! We also talked about some ways to handle large feature spaces using feature engineering but you should also remember that there are other techniques including feature selection and dimensionality reduction methods to handle large feature spaces. We will cover some of these methods in a later article. Next up will be feature engineering strategies for unstructured text data. Stay tuned! To read about feature engineering strategies for continuous numeric data, check out Part 1 of this series! All the code and datasets used in this article can be accessed from my GitHub The code is also available as a Jupyter notebook
[ { "code": null, "e": 920, "s": 171, "text": "We covered various feature engineering strategies for dealing with structured continuous numeric data in the previous article in this series. In this article, we will look at another type of structured data, which is discrete in nature and is popularly termed as categorical data. Dealing with numeric data is often easier than categorical data given that we do not have to deal with additional complexities of the semantics pertaining to each category value in any data attribute which is of a categorical type. We will use a hands-on approach to discuss several encoding schemes for dealing with categorical data and also a couple of popular techniques for dealing with large scale feature explosion, often known as the “curse of dimensionality”." }, { "code": null, "e": 1333, "s": 920, "text": "I’m sure by now you must realize the motivation and the importance of feature engineering, we do stress on the same in detail in ‘Part 1’ of this series. Do check it out for a quick refresher if necessary. In short, machine learning algorithms cannot work directly with categorical data and you do need to do some amount of engineering and transformations on this data before you can start modeling on your data." }, { "code": null, "e": 1928, "s": 1333, "text": "Let’s get an idea about categorical data representations before diving into feature engineering strategies. Typically, any data attribute which is categorical in nature represents discrete values which belong to a specific finite set of categories or classes. These are also often known as classes or labels in the context of attributes or variables which are to be predicted by a model (popularly known as response variables). These discrete values can be text or numeric in nature (or even unstructured data like images!). There are two major classes of categorical data, nominal and ordinal." }, { "code": null, "e": 2332, "s": 1928, "text": "In any nominal categorical data attribute, there is no concept of ordering amongst the values of that attribute. Consider a simple example of weather categories, as depicted in the following figure. We can see that we have six major classes or categories in this particular scenario without any concept or notion of order (windy doesn’t always occur before sunny nor is it smaller or bigger than sunny)." }, { "code": null, "e": 2470, "s": 2332, "text": "Similarly movie, music and video game genres, country names, food and cuisine types are other examples of nominal categorical attributes." }, { "code": null, "e": 2761, "s": 2470, "text": "Ordinal categorical attributes have some sense or notion of order amongst its values. For instance look at the following figure for shirt sizes. It is quite evident that order or in this case ‘size’ matters when thinking about shirts (S is smaller than M which is smaller than L and so on)." }, { "code": null, "e": 2969, "s": 2761, "text": "Shoe sizes, education level and employment roles are some other examples of ordinal categorical attributes. Having a decent idea about categorical data, let’s now look at some feature engineering strategies." }, { "code": null, "e": 3366, "s": 2969, "text": "While a lot of advancements have been made in various machine learning frameworks to accept complex categorical data types like text labels. Typically any standard workflow in feature engineering involves some form of transformation of these categorical values into numeric labels and then applying some encoding scheme on these values. We load up the necessary essentials before getting started." }, { "code": null, "e": 3404, "s": 3366, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 3802, "s": 3404, "text": "Nominal attributes consist of discrete categorical values with no notion or sense of order amongst them. The idea here is to transform these attributes into a more representative numerical format which can be easily understood by downstream code and pipelines. Let’s look at a new dataset pertaining to video game sales. This dataset is also available on Kaggle as well as in my GitHub repository." }, { "code": null, "e": 3931, "s": 3802, "text": "vg_df = pd.read_csv('datasets/vgsales.csv', encoding='utf-8')vg_df[['Name', 'Platform', 'Year', 'Genre', 'Publisher']].iloc[1:7]" }, { "code": null, "e": 4180, "s": 3931, "text": "Let’s focus on the video game Genre attribute as depicted in the above data frame. It is quite evident that this is a nominal categorical attribute just like Publisher and Platform. We can easily get the list of unique video game genres as follows." }, { "code": null, "e": 4408, "s": 4180, "text": "genres = np.unique(vg_df['Genre'])genresOutput------array(['Action', 'Adventure', 'Fighting', 'Misc', 'Platform', 'Puzzle', 'Racing', 'Role-Playing', 'Shooter', 'Simulation', 'Sports', 'Strategy'], dtype=object)" }, { "code": null, "e": 4583, "s": 4408, "text": "This tells us that we have 12 distinct video game genres. We can now generate a label encoding scheme for mapping each category to a numeric value by leveraging scikit-learn." }, { "code": null, "e": 4993, "s": 4583, "text": "from sklearn.preprocessing import LabelEncodergle = LabelEncoder()genre_labels = gle.fit_transform(vg_df['Genre'])genre_mappings = {index: label for index, label in enumerate(gle.classes_)}genre_mappingsOutput------{0: 'Action', 1: 'Adventure', 2: 'Fighting', 3: 'Misc', 4: 'Platform', 5: 'Puzzle', 6: 'Racing', 7: 'Role-Playing', 8: 'Shooter', 9: 'Simulation', 10: 'Sports', 11: 'Strategy'}" }, { "code": null, "e": 5228, "s": 4993, "text": "Thus a mapping scheme has been generated where each genre value is mapped to a number with the help of the LabelEncoder object gle. The transformed labels are stored in the genre_labels value which we can write back to our data frame." }, { "code": null, "e": 5331, "s": 5228, "text": "vg_df['GenreLabel'] = genre_labelsvg_df[['Name', 'Platform', 'Year', 'Genre', 'GenreLabel']].iloc[1:7]" }, { "code": null, "e": 5597, "s": 5331, "text": "These labels can be used directly often especially with frameworks like scikit-learn if you plan to use them as response variables for prediction, however as discussed earlier, we will need an additional step of encoding on these before we can use them as features." }, { "code": null, "e": 5820, "s": 5597, "text": "Ordinal attributes are categorical attributes with a sense of order amongst the values. Let’s consider our Pokémon dataset which we used in Part 1 of this series. Let’s focus more specifically on the Generation attribute." }, { "code": null, "e": 6108, "s": 5820, "text": "poke_df = pd.read_csv('datasets/Pokemon.csv', encoding='utf-8')poke_df = poke_df.sample(random_state=1, frac=1).reset_index(drop=True)np.unique(poke_df['Generation'])Output------array(['Gen 1', 'Gen 2', 'Gen 3', 'Gen 4', 'Gen 5', 'Gen 6'], dtype=object)" }, { "code": null, "e": 6701, "s": 6108, "text": "Based on the above output, we can see there are a total of 6 generations and each Pokémon typically belongs to a specific generation based on the video games (when they were released) and also the television series follows a similar timeline. This attribute is typically ordinal (domain knowledge is necessary here) because most Pokémon belonging to Generation 1 were introduced earlier in the video games and the television shows than Generation 2 as so on. Fans can check out the following figure to remember some of the popular Pokémon of each generation (views may differ among fans!)." }, { "code": null, "e": 6945, "s": 6701, "text": "Hence they have a sense of order amongst them. In general, there is no generic module or function to map and transform these features into numeric representations based on order automatically. Hence we can use a custom encoding\\mapping scheme." }, { "code": null, "e": 7175, "s": 6945, "text": "gen_ord_map = {'Gen 1': 1, 'Gen 2': 2, 'Gen 3': 3, 'Gen 4': 4, 'Gen 5': 5, 'Gen 6': 6}poke_df['GenerationLabel'] = poke_df['Generation'].map(gen_ord_map)poke_df[['Name', 'Generation', 'GenerationLabel']].iloc[4:10]" }, { "code": null, "e": 7309, "s": 7175, "text": "It is quite evident from the above code that the map(...) function from pandas is quite helpful in transforming this ordinal feature." }, { "code": null, "e": 7652, "s": 7309, "text": "If you remember what we mentioned earlier, typically feature engineering on categorical data involves a transformation process which we depicted in the previous section and a compulsory encoding process where we apply specific encoding schemes to create dummy variables or features for each category\\value in a specific categorical attribute." }, { "code": null, "e": 8395, "s": 7652, "text": "You might be wondering, we just converted categories to numerical labels in the previous section, why on earth do we need this now? The reason is quite simple. Considering video game genres, if we directly fed the GenreLabel attribute as a feature in a machine learning model, it would consider it to be a continuous numeric feature thinking value 10 (Sports) is greater than 6 (Racing) but that is meaningless because the Sports genre is certainly not bigger or smaller than Racing, these are essentially different values or categories which cannot be compared directly. Hence we need an additional layer of encoding schemes where dummy features are created for each unique value or category out of all the distinct categories per attribute." }, { "code": null, "e": 8867, "s": 8395, "text": "Considering we have the numeric representation of any categorical attribute with m labels (after transformation), the one-hot encoding scheme, encodes or transforms the attribute into m binary features which can only contain a value of 1 or 0. Each observation in the categorical feature is thus converted into a vector of size m with only one of the values as 1 (indicating it as active). Let’s take a subset of our Pokémon dataset depicting two attributes of interest." }, { "code": null, "e": 8923, "s": 8867, "text": "poke_df[['Name', 'Generation', 'Legendary']].iloc[4:10]" }, { "code": null, "e": 9112, "s": 8923, "text": "The attributes of interest are Pokémon Generation and their Legendary status. The first step is to transform these attributes into numeric representations based on what we learnt earlier." }, { "code": null, "e": 9612, "s": 9112, "text": "from sklearn.preprocessing import OneHotEncoder, LabelEncoder# transform and map pokemon generationsgen_le = LabelEncoder()gen_labels = gen_le.fit_transform(poke_df['Generation'])poke_df['Gen_Label'] = gen_labels# transform and map pokemon legendary statusleg_le = LabelEncoder()leg_labels = leg_le.fit_transform(poke_df['Legendary'])poke_df['Lgnd_Label'] = leg_labelspoke_df_sub = poke_df[['Name', 'Generation', 'Gen_Label', 'Legendary', 'Lgnd_Label']]poke_df_sub.iloc[4:10]" }, { "code": null, "e": 9781, "s": 9612, "text": "The features Gen_Label and Lgnd_Label now depict the numeric representations of our categorical features. Let’s now apply the one-hot encoding scheme on these features." }, { "code": null, "e": 10511, "s": 9781, "text": "# encode generation labels using one-hot encoding schemegen_ohe = OneHotEncoder()gen_feature_arr = gen_ohe.fit_transform( poke_df[['Gen_Label']]).toarray()gen_feature_labels = list(gen_le.classes_)gen_features = pd.DataFrame(gen_feature_arr, columns=gen_feature_labels)# encode legendary status labels using one-hot encoding schemeleg_ohe = OneHotEncoder()leg_feature_arr = leg_ohe.fit_transform( poke_df[['Lgnd_Label']]).toarray()leg_feature_labels = ['Legendary_'+str(cls_label) for cls_label in leg_le.classes_]leg_features = pd.DataFrame(leg_feature_arr, columns=leg_feature_labels)" }, { "code": null, "e": 10936, "s": 10511, "text": "In general, you can always encode both the features together using the fit_transform(...) function by passing it a two dimensional array of the two features together (Check out the documentation!). But we encode each feature separately, to make things easier to understand. Besides this, we can also create separate data frames and label them accordingly. Let’s now concatenate these feature frames and see the final result." }, { "code": null, "e": 11199, "s": 10936, "text": "poke_df_ohe = pd.concat([poke_df_sub, gen_features, leg_features], axis=1)columns = sum([['Name', 'Generation', 'Gen_Label'], gen_feature_labels, ['Legendary', 'Lgnd_Label'], leg_feature_labels], [])poke_df_ohe[columns].iloc[4:10]" }, { "code": null, "e": 11546, "s": 11199, "text": "Thus you can see that 6 dummy variables or binary features have been created for Generation and 2 for Legendary since those are the total number of distinct categories in each of these attributes respectively. Active state of a category is indicated by the 1 value in one of these dummy variables which is quite evident from the above data frame." }, { "code": null, "e": 11731, "s": 11546, "text": "Consider you built this encoding scheme on your training data and built some model and now you have some new data which has to be engineered for features before predictions as follows." }, { "code": null, "e": 11927, "s": 11731, "text": "new_poke_df = pd.DataFrame([['PikaZoom', 'Gen 3', True], ['CharMyToast', 'Gen 4', False]], columns=['Name', 'Generation', 'Legendary'])new_poke_df" }, { "code": null, "e": 12152, "s": 11927, "text": "You can leverage scikit-learn’s excellent API here by calling the transform(...) function of the previously build LabeLEncoder and OneHotEncoder objects on the new data. Remember our workflow, first we do the transformation." }, { "code": null, "e": 12443, "s": 12152, "text": "new_gen_labels = gen_le.transform(new_poke_df['Generation'])new_poke_df['Gen_Label'] = new_gen_labelsnew_leg_labels = leg_le.transform(new_poke_df['Legendary'])new_poke_df['Lgnd_Label'] = new_leg_labelsnew_poke_df[['Name', 'Generation', 'Gen_Label', 'Legendary', 'Lgnd_Label']]" }, { "code": null, "e": 12511, "s": 12443, "text": "Once we have numerical labels, let’s apply the encoding scheme now!" }, { "code": null, "e": 13149, "s": 12511, "text": "new_gen_feature_arr = gen_ohe.transform(new_poke_df[['Gen_Label']]).toarray()new_gen_features = pd.DataFrame(new_gen_feature_arr, columns=gen_feature_labels)new_leg_feature_arr = leg_ohe.transform(new_poke_df[['Lgnd_Label']]).toarray()new_leg_features = pd.DataFrame(new_leg_feature_arr, columns=leg_feature_labels)new_poke_ohe = pd.concat([new_poke_df, new_gen_features, new_leg_features], axis=1)columns = sum([['Name', 'Generation', 'Gen_Label'], gen_feature_labels, ['Legendary', 'Lgnd_Label'], leg_feature_labels], [])new_poke_ohe[columns]" }, { "code": null, "e": 13265, "s": 13149, "text": "Thus you can see it’s quite easy to apply this scheme on new data easily by leveraging scikit-learn’s powerful API." }, { "code": null, "e": 13375, "s": 13265, "text": "You can also apply the one-hot encoding scheme easily by leveraging the to_dummies(...) function from pandas." }, { "code": null, "e": 13530, "s": 13375, "text": "gen_onehot_features = pd.get_dummies(poke_df['Generation'])pd.concat([poke_df[['Name', 'Generation']], gen_onehot_features], axis=1).iloc[4:10]" }, { "code": null, "e": 13696, "s": 13530, "text": "The above data frame depicts the one-hot encoding scheme applied on the Generation attribute and the results are same as compared to the earlier results as expected." }, { "code": null, "e": 14349, "s": 13696, "text": "The dummy coding scheme is similar to the one-hot encoding scheme, except in the case of dummy coding scheme, when applied on a categorical feature with m distinct labels, we get m - 1 binary features. Thus each value of the categorical variable gets converted into a vector of size m - 1. The extra feature is completely disregarded and thus if the category values range from {0, 1, ..., m-1} the 0th or the m - 1th feature column is dropped and corresponding category values are usually represented by a vector of all zeros (0). Let’s try applying dummy coding scheme on Pokémon Generation by dropping the first level binary encoded feature (Gen 1)." }, { "code": null, "e": 14554, "s": 14349, "text": "gen_dummy_features = pd.get_dummies(poke_df['Generation'], drop_first=True)pd.concat([poke_df[['Name', 'Generation']], gen_dummy_features], axis=1).iloc[4:10]" }, { "code": null, "e": 14653, "s": 14554, "text": "If you want, you can also choose to drop the last level binary encoded feature (Gen 6) as follows." }, { "code": null, "e": 14859, "s": 14653, "text": "gen_onehot_features = pd.get_dummies(poke_df['Generation'])gen_dummy_features = gen_onehot_features.iloc[:,:-1]pd.concat([poke_df[['Name', 'Generation']], gen_dummy_features], axis=1).iloc[4:10]" }, { "code": null, "e": 15025, "s": 14859, "text": "Based on the above depictions, it is quite clear that categories belonging to the dropped feature are represented as a vector of zeros (0) like we discussed earlier." }, { "code": null, "e": 15353, "s": 15025, "text": "The effect coding scheme is actually very similar to the dummy coding scheme, except during the encoding process, the encoded features or feature vector, for the category values which represent all 0 in the dummy coding scheme, is replaced by -1 in the effect coding scheme. This will become clearer with the following example." }, { "code": null, "e": 15662, "s": 15353, "text": "gen_onehot_features = pd.get_dummies(poke_df['Generation'])gen_effect_features = gen_onehot_features.iloc[:,:-1]gen_effect_features.loc[np.all(gen_effect_features == 0, axis=1)] = -1.pd.concat([poke_df[['Name', 'Generation']], gen_effect_features], axis=1).iloc[4:10]" }, { "code": null, "e": 15820, "s": 15662, "text": "The above output clearly shows that the Pokémon belonging to Generation 6 are now represented by a vector of -1 values as compared to zeros in dummy coding." }, { "code": null, "e": 16519, "s": 15820, "text": "The encoding schemes we discussed so far, work quite well on categorical data in general, but they start causing problems when the number of distinct categories in any feature becomes very large. Essential for any categorical feature of m distinct labels, you get m separate features. This can easily increase the size of the feature set causing problems like storage issues, model training problems with regard to time, space and memory. Besides this, we also have to deal with what is popularly known as the ‘curse of dimensionality’ where basically with an enormous number of features and not enough representative samples, model performance starts getting affected often leading to overfitting." }, { "code": null, "e": 17626, "s": 16519, "text": "Hence we need to look towards other categorical data feature engineering schemes for features having a large number of possible categories (like IP addresses). The bin-counting scheme is a useful scheme for dealing with categorical variables having many categories. In this scheme, instead of using the actual label values for encoding, we use probability based statistical information about the value and the actual target or response value which we aim to predict in our modeling efforts. A simple example would be based on past historical data for IP addresses and the ones which were used in DDOS attacks; we can build probability values for a DDOS attack being caused by any of the IP addresses. Using this information, we can encode an input feature which depicts that if the same IP address comes in the future, what is the probability value of a DDOS attack being caused. This scheme needs historical data as a pre-requisite and is an elaborate one. Depicting this with a complete example would be currently difficult here but there are several resources online which you can refer to for the same." }, { "code": null, "e": 18464, "s": 17626, "text": "The feature hashing scheme is another useful feature engineering scheme for dealing with large scale categorical features. In this scheme, a hash function is typically used with the number of encoded features pre-set (as a vector of pre-defined length) such that the hashed values of the features are used as indices in this pre-defined vector and values are updated accordingly. Since a hash function maps a large number of values into a small finite set of values, multiple different values might create the same hash which is termed as collisions. Typically, a signed hash function is used so that the sign of the value obtained from the hash is used as the sign of the value which is stored in the final feature vector at the appropriate index. This should ensure lesser collisions and lesser accumulation of error due to collisions." }, { "code": null, "e": 18938, "s": 18464, "text": "Hashing schemes work on strings, numbers and other structures like vectors. You can think of hashed outputs as a finite set of b bins such that when hash function is applied on the same values\\categories, they get assigned to the same bin (or subset of bins) out of the b bins based on the hash value. We can pre-define the value of b which becomes the final size of the encoded feature vector for each categorical attribute that we encode using the feature hashing scheme." }, { "code": null, "e": 19244, "s": 18938, "text": "Thus even if we have over 1000 distinct categories in a feature and we set b=10 as the final feature vector size, the output feature set will still have only 10 features as compared to 1000 binary features if we used a one-hot encoding scheme. Let’s consider the Genre attribute in our video game dataset." }, { "code": null, "e": 19515, "s": 19244, "text": "unique_genres = np.unique(vg_df[['Genre']])print(\"Total game genres:\", len(unique_genres))print(unique_genres)Output------Total game genres: 12['Action' 'Adventure' 'Fighting' 'Misc' 'Platform' 'Puzzle' 'Racing' 'Role-Playing' 'Shooter' 'Simulation' 'Sports' 'Strategy']" }, { "code": null, "e": 19920, "s": 19515, "text": "We can see that there are a total of 12 genres of video games. If we used a one-hot encoding scheme on the Genre feature, we would end up having 12 binary features. Instead, we will now use a feature hashing scheme by leveraging scikit-learn’s FeatureHasher class, which uses a signed 32-bit version of the Murmurhash3 hash function. We will pre-define the final feature vector size to be 6 in this case." }, { "code": null, "e": 20215, "s": 19920, "text": "from sklearn.feature_extraction import FeatureHasherfh = FeatureHasher(n_features=6, input_type='string')hashed_features = fh.fit_transform(vg_df['Genre'])hashed_features = hashed_features.toarray()pd.concat([vg_df[['Name', 'Genre']], pd.DataFrame(hashed_features)], axis=1).iloc[1:7]" }, { "code": null, "e": 20484, "s": 20215, "text": "Based on the above output, the Genre categorical attribute has been encoded using the hashing scheme into 6 features instead of 12. We can also see that rows 1 and 6 denote the same genre of games, Platform which have been rightly encoded into the same feature vector." }, { "code": null, "e": 21094, "s": 20484, "text": "These examples should give you a good idea about popular strategies for feature engineering on discrete, categorical data. If you read Part 1 of this series, you would have seen that it is slightly challenging to work with categorical data as compared to continuous, numeric data but definitely interesting! We also talked about some ways to handle large feature spaces using feature engineering but you should also remember that there are other techniques including feature selection and dimensionality reduction methods to handle large feature spaces. We will cover some of these methods in a later article." }, { "code": null, "e": 21181, "s": 21094, "text": "Next up will be feature engineering strategies for unstructured text data. Stay tuned!" }, { "code": null, "e": 21288, "s": 21181, "text": "To read about feature engineering strategies for continuous numeric data, check out Part 1 of this series!" }, { "code": null, "e": 21366, "s": 21288, "text": "All the code and datasets used in this article can be accessed from my GitHub" } ]
Guava - Multimap Interface
Multimap interface extends Map so that its keys can be mapped to multiple values at a time. Following is the declaration for com.google.common.collect.Multimap<K,V> interface − @GwtCompatible public interface Multimap<K,V> Map<K,Collection<V>> asMap() Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values. void clear() Removes all key-value pairs from the multimap, leaving it empty. boolean containsEntry(Object key, Object value) Returns true if this multimap contains at least one key-value pair with the key and the value. boolean containsKey(Object key) Returns true if this multimap contains at least one key-value pair with the key. boolean containsValue(Object value) Returns true if this multimap contains at least one key-value pair with the value. Collection<Map.Entry<K,V>> entries() Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances. boolean equals(Object obj) Compares the specified object with this multimap for equality. Collection<V> get(K key) Returns a view collection of the values associated with key in this multimap, if any. int hashCode() Returns the hash code for this multimap. boolean isEmpty() Returns true if this multimap contains no key-value pairs. Multiset<K> keys() Returns a view collection containing the key from each key-value pair in this multimap, without collapsing duplicates. Set<K> keySet() Returns a view collection of all distinct keys contained in this multimap. boolean put(K key, V value) Stores a key-value pair in this multimap. boolean putAll(K key, Iterable<? extends V> values) Stores a key-value pair in this multimap for each of values, all using the same key, key. boolean putAll(Multimap<? extends K,? extends V> multimap) Stores all key-value pairs of multimap in this multimap, in the order returned by multimap.entries(). boolean remove(Object key, Object value) Removes a single key-value pair with the key and the value from this multimap, if such exists. Collection<V> removeAll(Object key) Removes all values associated with the key. Collection<V> replaceValues(K key, Iterable<? extends V> values) Stores a collection of values with the same key, replacing any existing values for that key. int size() Returns the number of key-value pairs in this multimap. Collection<V> values() Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size()). Create the following java program using any editor of your choice in say C:/> Guava. import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); Multimap<String,String> multimap = tester.getMultimap(); List<String> lowerList = (List<String>)multimap.get("lower"); System.out.println("Initial lower case list"); System.out.println(lowerList.toString()); lowerList.add("f"); System.out.println("Modified lower case list"); System.out.println(lowerList.toString()); List<String> upperList = (List<String>)multimap.get("upper"); System.out.println("Initial upper case list"); System.out.println(upperList.toString()); upperList.remove("D"); System.out.println("Modified upper case list"); System.out.println(upperList.toString()); Map<String, Collection<String>> map = multimap.asMap(); System.out.println("Multimap as a map"); for (Map.Entry<String, Collection<String>> entry : map.entrySet()) { String key = entry.getKey(); Collection<String> value = multimap.get("lower"); System.out.println(key + ":" + value); } System.out.println("Keys of Multimap"); Set<String> keys = multimap.keySet(); for(String key:keys) { System.out.println(key); } System.out.println("Values of Multimap"); Collection<String> values = multimap.values(); System.out.println(values); } private Multimap<String,String> getMultimap() { //Map<String, List<String>> // lower -> a, b, c, d, e // upper -> A, B, C, D Multimap<String,String> multimap = ArrayListMultimap.create(); multimap.put("lower", "a"); multimap.put("lower", "b"); multimap.put("lower", "c"); multimap.put("lower", "d"); multimap.put("lower", "e"); multimap.put("upper", "A"); multimap.put("upper", "B"); multimap.put("upper", "C"); multimap.put("upper", "D"); return multimap; } } Compile the class using javac compiler as follows − C:\Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:\Guava>java GuavaTester See the result. Initial lower case list [a, b, c, d, e] Modified lower case list [a, b, c, d, e, f] Initial upper case list [A, B, C, D] Modified upper case list [A, B, C] Multimap as a map upper:[a, b, c, d, e, f] lower:[a, b, c, d, e, f] Keys of Multimap upper lower Values of Multimap [a, b, c, d, e, f, A, B, C] Print Add Notes Bookmark this page
[ { "code": null, "e": 1977, "s": 1885, "text": "Multimap interface extends Map so that its keys can be mapped to multiple values at a time." }, { "code": null, "e": 2062, "s": 1977, "text": "Following is the declaration for com.google.common.collect.Multimap<K,V> interface −" }, { "code": null, "e": 2108, "s": 2062, "text": "@GwtCompatible\npublic interface Multimap<K,V>" }, { "code": null, "e": 2137, "s": 2108, "text": "Map<K,Collection<V>> asMap()" }, { "code": null, "e": 2261, "s": 2137, "text": "Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values." }, { "code": null, "e": 2274, "s": 2261, "text": "void clear()" }, { "code": null, "e": 2339, "s": 2274, "text": "Removes all key-value pairs from the multimap, leaving it empty." }, { "code": null, "e": 2387, "s": 2339, "text": "boolean containsEntry(Object key, Object value)" }, { "code": null, "e": 2482, "s": 2387, "text": "Returns true if this multimap contains at least one key-value pair with the key and the value." }, { "code": null, "e": 2514, "s": 2482, "text": "boolean containsKey(Object key)" }, { "code": null, "e": 2595, "s": 2514, "text": "Returns true if this multimap contains at least one key-value pair with the key." }, { "code": null, "e": 2631, "s": 2595, "text": "boolean containsValue(Object value)" }, { "code": null, "e": 2714, "s": 2631, "text": "Returns true if this multimap contains at least one key-value pair with the value." }, { "code": null, "e": 2751, "s": 2714, "text": "Collection<Map.Entry<K,V>>\tentries()" }, { "code": null, "e": 2852, "s": 2751, "text": "Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances." }, { "code": null, "e": 2879, "s": 2852, "text": "boolean equals(Object obj)" }, { "code": null, "e": 2942, "s": 2879, "text": "Compares the specified object with this multimap for equality." }, { "code": null, "e": 2967, "s": 2942, "text": "Collection<V> get(K key)" }, { "code": null, "e": 3053, "s": 2967, "text": "Returns a view collection of the values associated with key in this multimap, if any." }, { "code": null, "e": 3068, "s": 3053, "text": "int hashCode()" }, { "code": null, "e": 3109, "s": 3068, "text": "Returns the hash code for this multimap." }, { "code": null, "e": 3127, "s": 3109, "text": "boolean isEmpty()" }, { "code": null, "e": 3186, "s": 3127, "text": "Returns true if this multimap contains no key-value pairs." }, { "code": null, "e": 3205, "s": 3186, "text": "Multiset<K> keys()" }, { "code": null, "e": 3324, "s": 3205, "text": "Returns a view collection containing the key from each key-value pair in this multimap, without collapsing duplicates." }, { "code": null, "e": 3340, "s": 3324, "text": "Set<K> keySet()" }, { "code": null, "e": 3415, "s": 3340, "text": "Returns a view collection of all distinct keys contained in this multimap." }, { "code": null, "e": 3443, "s": 3415, "text": "boolean put(K key, V value)" }, { "code": null, "e": 3485, "s": 3443, "text": "Stores a key-value pair in this multimap." }, { "code": null, "e": 3537, "s": 3485, "text": "boolean putAll(K key, Iterable<? extends V> values)" }, { "code": null, "e": 3627, "s": 3537, "text": "Stores a key-value pair in this multimap for each of values, all using the same key, key." }, { "code": null, "e": 3686, "s": 3627, "text": "boolean putAll(Multimap<? extends K,? extends V> multimap)" }, { "code": null, "e": 3788, "s": 3686, "text": "Stores all key-value pairs of multimap in this multimap, in the order returned by multimap.entries()." }, { "code": null, "e": 3829, "s": 3788, "text": "boolean remove(Object key, Object value)" }, { "code": null, "e": 3924, "s": 3829, "text": "Removes a single key-value pair with the key and the value from this multimap, if such exists." }, { "code": null, "e": 3960, "s": 3924, "text": "Collection<V> removeAll(Object key)" }, { "code": null, "e": 4004, "s": 3960, "text": "Removes all values associated with the key." }, { "code": null, "e": 4069, "s": 4004, "text": "Collection<V> replaceValues(K key, Iterable<? extends V> values)" }, { "code": null, "e": 4162, "s": 4069, "text": "Stores a collection of values with the same key, replacing any existing values for that key." }, { "code": null, "e": 4173, "s": 4162, "text": "int size()" }, { "code": null, "e": 4229, "s": 4173, "text": "Returns the number of key-value pairs in this multimap." }, { "code": null, "e": 4252, "s": 4229, "text": "Collection<V> values()" }, { "code": null, "e": 4414, "s": 4252, "text": "Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size())." }, { "code": null, "e": 4499, "s": 4414, "text": "Create the following java program using any editor of your choice in say C:/> Guava." }, { "code": null, "e": 6682, "s": 4499, "text": "import java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.collect.ArrayListMultimap;\nimport com.google.common.collect.Multimap;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n \n GuavaTester tester = new GuavaTester();\n Multimap<String,String> multimap = tester.getMultimap();\n\n List<String> lowerList = (List<String>)multimap.get(\"lower\");\n System.out.println(\"Initial lower case list\");\n System.out.println(lowerList.toString());\n\n lowerList.add(\"f\");\n System.out.println(\"Modified lower case list\");\n System.out.println(lowerList.toString());\n\n List<String> upperList = (List<String>)multimap.get(\"upper\");\n System.out.println(\"Initial upper case list\");\n System.out.println(upperList.toString());\n\n upperList.remove(\"D\");\n System.out.println(\"Modified upper case list\");\n System.out.println(upperList.toString());\n\n Map<String, Collection<String>> map = multimap.asMap();\n System.out.println(\"Multimap as a map\");\n\n for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {\n String key = entry.getKey();\n Collection<String> value = multimap.get(\"lower\");\n System.out.println(key + \":\" + value);\n }\n\n System.out.println(\"Keys of Multimap\");\n Set<String> keys = multimap.keySet();\n\n for(String key:keys) {\n System.out.println(key);\n }\n\n System.out.println(\"Values of Multimap\");\n Collection<String> values = multimap.values();\n System.out.println(values);\n }\n\n private Multimap<String,String> getMultimap() {\n\n //Map<String, List<String>>\n // lower -> a, b, c, d, e\n // upper -> A, B, C, D\n\n Multimap<String,String> multimap = ArrayListMultimap.create();\n\n multimap.put(\"lower\", \"a\");\n multimap.put(\"lower\", \"b\");\n multimap.put(\"lower\", \"c\");\n multimap.put(\"lower\", \"d\");\n multimap.put(\"lower\", \"e\");\n\n multimap.put(\"upper\", \"A\");\n multimap.put(\"upper\", \"B\");\n multimap.put(\"upper\", \"C\");\n multimap.put(\"upper\", \"D\");\t\t\n\n return multimap;\n }\n}" }, { "code": null, "e": 6734, "s": 6682, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 6767, "s": 6734, "text": "C:\\Guava>javac GuavaTester.java\n" }, { "code": null, "e": 6810, "s": 6767, "text": "Now run the GuavaTester to see the result." }, { "code": null, "e": 6837, "s": 6810, "text": "C:\\Guava>java GuavaTester\n" }, { "code": null, "e": 6853, "s": 6837, "text": "See the result." }, { "code": null, "e": 7154, "s": 6853, "text": "Initial lower case list\n[a, b, c, d, e]\nModified lower case list\n[a, b, c, d, e, f]\nInitial upper case list\n[A, B, C, D]\nModified upper case list\n[A, B, C]\nMultimap as a map\nupper:[a, b, c, d, e, f]\nlower:[a, b, c, d, e, f]\nKeys of Multimap\nupper\nlower\nValues of Multimap\n[a, b, c, d, e, f, A, B, C]\n" }, { "code": null, "e": 7161, "s": 7154, "text": " Print" }, { "code": null, "e": 7172, "s": 7161, "text": " Add Notes" } ]
Angular CLI - ng add Command
This chapter explains the syntax, argument and options of ng add command along with an example. The syntax for ng add command is as follows − ng add <collection> [options] ng add a npm package to workspace. The argument for ng add command is as follows − Options are optional parameters. Shows a help message for this command in the console. Default: false Display additional details about internal operations during execution. Default: false First move to an angular project updated using ng build command,which is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm. Now run the add command. An example for ng add command is given below − \>Node\>TutorialsPoint> ng add @angular/pwa Installing packages for tooling via npm. Installed packages for tooling via npm. CREATE ngsw-config.json (620 bytes) CREATE src/manifest.webmanifest (1352 bytes) CREATE src/assets/icons/icon-128x128.png (1253 bytes) CREATE src/assets/icons/icon-144x144.png (1394 bytes) CREATE src/assets/icons/icon-152x152.png (1427 bytes) CREATE src/assets/icons/icon-192x192.png (1790 bytes) CREATE src/assets/icons/icon-384x384.png (3557 bytes) CREATE src/assets/icons/icon-512x512.png (5008 bytes) CREATE src/assets/icons/icon-72x72.png (792 bytes) CREATE src/assets/icons/icon-96x96.png (958 bytes) UPDATE angular.json (3803 bytes) UPDATE package.json (1332 bytes) UPDATE src/app/app.module.ts (682 bytes) UPDATE src/index.html (482 bytes) √ Packages installed successfully. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2171, "s": 2075, "text": "This chapter explains the syntax, argument and options of ng add command along with an example." }, { "code": null, "e": 2217, "s": 2171, "text": "The syntax for ng add command is as follows −" }, { "code": null, "e": 2248, "s": 2217, "text": "ng add <collection> [options]\n" }, { "code": null, "e": 2283, "s": 2248, "text": "ng add a npm package to workspace." }, { "code": null, "e": 2331, "s": 2283, "text": "The argument for ng add command is as follows −" }, { "code": null, "e": 2364, "s": 2331, "text": "Options are optional parameters." }, { "code": null, "e": 2418, "s": 2364, "text": "Shows a help message for this command in the console." }, { "code": null, "e": 2433, "s": 2418, "text": "Default: false" }, { "code": null, "e": 2504, "s": 2433, "text": "Display additional details about internal operations during execution." }, { "code": null, "e": 2519, "s": 2504, "text": "Default: false" }, { "code": null, "e": 2674, "s": 2519, "text": "First move to an angular project updated using ng build command,which is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm." }, { "code": null, "e": 2699, "s": 2674, "text": "Now run the add command." }, { "code": null, "e": 2746, "s": 2699, "text": "An example for ng add command is given below −" }, { "code": null, "e": 3555, "s": 2746, "text": "\\>Node\\>TutorialsPoint> ng add @angular/pwa\nInstalling packages for tooling via npm.\nInstalled packages for tooling via npm.\nCREATE ngsw-config.json (620 bytes)\nCREATE src/manifest.webmanifest (1352 bytes)\nCREATE src/assets/icons/icon-128x128.png (1253 bytes)\nCREATE src/assets/icons/icon-144x144.png (1394 bytes)\nCREATE src/assets/icons/icon-152x152.png (1427 bytes)\nCREATE src/assets/icons/icon-192x192.png (1790 bytes)\nCREATE src/assets/icons/icon-384x384.png (3557 bytes)\nCREATE src/assets/icons/icon-512x512.png (5008 bytes)\nCREATE src/assets/icons/icon-72x72.png (792 bytes)\nCREATE src/assets/icons/icon-96x96.png (958 bytes)\nUPDATE angular.json (3803 bytes)\nUPDATE package.json (1332 bytes)\nUPDATE src/app/app.module.ts (682 bytes)\nUPDATE src/index.html (482 bytes)\n√ Packages installed successfully.\n" }, { "code": null, "e": 3590, "s": 3555, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3604, "s": 3590, "text": " Anadi Sharma" }, { "code": null, "e": 3639, "s": 3604, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3653, "s": 3639, "text": " Anadi Sharma" }, { "code": null, "e": 3688, "s": 3653, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3708, "s": 3688, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 3743, "s": 3708, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3760, "s": 3743, "text": " Frahaan Hussain" }, { "code": null, "e": 3793, "s": 3760, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 3805, "s": 3793, "text": " Senol Atac" }, { "code": null, "e": 3840, "s": 3805, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3852, "s": 3840, "text": " Senol Atac" }, { "code": null, "e": 3859, "s": 3852, "text": " Print" }, { "code": null, "e": 3870, "s": 3859, "text": " Add Notes" } ]
Three Sum Closest | Practice | GeeksforGeeks
Given an array Arr of N numbers and another number target, find three integers in the array such that the sum is closest to target. Return the sum of the three integers. Example 1: Input: N = 6, target = 2 A[] = {-7,9,8,3,1,1} Output: 2 Explanation: There is one triplet with sum 2 in the array. Triplet elements are -7,8, 1 whose sum is 2. Example 2: Input: N = 4, target = 13 A[] = {5,2,7,5} Output: 14 Explanation: There is one triplet with sum 12 and other with sum 14 in the array. Triplet elements are 5, 2, 5 and 2, 7, 5 respectively. Since abs(13-12) == abs(13-14) maximum triplet sum will be preferred i.e 14. Your Task: Complete threeSumClosest() function and return the expected answer. NOTE: If their exists more than one answer then return the maximum sum. Expected Time Complexity: O(N*N). Expected Auxiliary Space: O(1). Constraints: 3 ≤ N ≤ 103 -105 ≤ A[i] ≤ 105 1 ≤ target ≤ 105 0 trivedipranjal02 This comment was deleted. 0 gauravrastogi4 weeks ago this is easy ? 0 patelneer4031 month ago int i,diff1=10000,diff2=100000,end,start,sum; sort(arr.begin(),arr.end()); int n=arr.size(); for(i=0;i<n;i++) { start=i+1; end=n-1; while(start<end) { sum=arr[i]+arr[start]+arr[end]; if(sum==target) return sum; else if(sum>target){ end--; diff1=min(diff1,sum-target); } else if(sum<target){ start++; diff2=min(diff2,target-sum); } } } if(diff1 < diff2) return target+diff1; if(diff1==diff2) return target+diff1; return target-diff2; } +1 akkeshri140420012 months ago int threeSumClosest(vector<int> arr, int target) { // Your code goes here int mini=INT_MAX; sort(arr.begin(),arr.end()); int m=0; for(int i=0;i<arr.size();i++){ int j=i+1; int k=arr.size()-1; while(j<k){ if(arr[i]+arr[j]+arr[k]==target){ return target; } else if(arr[i]+arr[j]+arr[k]<target){ int len=abs((arr[i]+arr[j]+arr[k])-target); if(mini>len){ mini=len; m=arr[i]+arr[j]+arr[k]; } j++; } else{ int len=abs((arr[i]+arr[j]+arr[k])-target); if(mini>=len){ mini=len; m=arr[i]+arr[j]+arr[k]; } k--; } } } return m; } 0 jswxingyu12 months ago Python solution class Solution: def threeSumClosest (self, arr, target): # Your Code Here arr.sort() N = len(arr) Sum = 1e10 for i in range(N-2): a = arr[i] L = i + 1 R = N - 1 while L < R: temp = a+arr[L]+arr[R] if temp == target: return target elif temp > target: R -= 1 else: L += 1 if abs(temp - target) < abs(Sum - target): Sum = temp elif abs(temp - target) == abs(Sum - target) and temp > Sum: Sum = temp # record the bigger one return Sum 0 soumik8672 months ago int threeSumClosest(vector<int> arr, int target) { sort(arr.begin(),arr.end()); int ans=INT_MAX; for(int i=0;i<arr.size();i++){ int x=0,y=arr.size()-1; int z=arr[i]; while(y>x){ if(x==i){ x++; continue; } if(y==i){ y--; continue; } if(z+arr[x]+arr[y]==target){ return target; } if(abs(target-ans)>abs(target-(z+arr[x]+arr[y]))){ ans=z+arr[x]+arr[y]; }else if(abs(target-ans)==abs(target-(z+arr[x]+arr[y]))){ ans=max(z+arr[x]+arr[y],ans); } if(z+arr[x]+arr[y]>target){ y--; }else{ x++; } } } return ans; } 0 mohammedhashimb190253cs2 months ago How does the space complexity is O(1)? we are clearly using most efficient sorting algorithms like merge sort or quick sort which take O(N) space complexity. Correct me if I'm wrong... -1 parul7003 months ago class Solution{ public: int threeSumClosest(vector<int> arr, int target) { int i,j,k,sum; int n=arr.size(),closestsum=INT_MAX; sort(arr.begin(),arr.end()); for(i=0;i<n-2;i++) { j=i+1; k=n-1; while(j<k) { sum=arr[i]+arr[j]+arr[k]; if(sum==target) return sum; if(abs(target-sum)<abs(target-closestsum)) closestsum=sum; if(abs(target-sum)==abs(target-closestsum)) closestsum=max(sum,closestsum); if(sum<target) j++; else k--; } } return closestsum; } }; 0 harshshukla30983 months ago int n=array.length; int i=0; long sum=0; Arrays.sort(array); long closesum=Integer.MAX_VALUE; for( i=0;i<n-2;i++){ int start=1+i,end=n-1; while(start<end){ sum=array[i]+array[start]+array[end]; if(Math.abs(target-sum)<Math.abs(target-closesum)){ closesum=sum; } // System.out.print(closesum); //closesum=; if(Math.abs(target-sum)==Math.abs(target-closesum)){ closesum=Math.max(closesum,sum); } if(target>sum){ start++; // System.out.print(start); } else{ end --; } } } return (int)closesum; sumbtied by kouslendra and piyush +1 ankitsinha1112004 months ago class Solution{ public: int threeSumClosest(vector<int> arr, int target) { sort(arr.begin(),arr.end()); int i,j,k,d=INT_MAX,s=target,n=arr.size(); for(i=0;i<n-1;i++) { j=i+1; k=n-1; while(j<k) { if(arr[i]+arr[j]+arr[k]==target) return target; else if(arr[i]+arr[j]+arr[k]<target) { if(d>abs(target-arr[i]-arr[j]-arr[k])) { d=abs(target-arr[i]-arr[j]-arr[k]); s=arr[i]+arr[j]+arr[k]; } j++; } else { if(d>=abs(target-arr[i]-arr[j]-arr[k])) { d=abs(target-arr[i]-arr[j]-arr[k]); s=arr[i]+arr[j]+arr[k]; } k--; } } } return s; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 408, "s": 238, "text": "Given an array Arr of N numbers and another number target, find three integers in the array such that the sum is closest to target. Return the sum of the three integers." }, { "code": null, "e": 419, "s": 408, "text": "Example 1:" }, { "code": null, "e": 580, "s": 419, "text": "Input:\nN = 6, target = 2\nA[] = {-7,9,8,3,1,1}\nOutput: 2\nExplanation: There is one triplet with sum\n2 in the array. Triplet elements are -7,8,\n1 whose sum is 2.\n" }, { "code": null, "e": 591, "s": 580, "text": "Example 2:" }, { "code": null, "e": 858, "s": 591, "text": "Input:\nN = 4, target = 13\nA[] = {5,2,7,5}\nOutput: 14\nExplanation: There is one triplet with sum\n12 and other with sum 14 in the array.\nTriplet elements are 5, 2, 5 and 2, 7, 5\nrespectively. Since abs(13-12) ==\nabs(13-14) maximum triplet sum will be\npreferred i.e 14." }, { "code": null, "e": 937, "s": 858, "text": "Your Task:\nComplete threeSumClosest() function and return the expected answer." }, { "code": null, "e": 1009, "s": 937, "text": "NOTE: If their exists more than one answer then return the maximum sum." }, { "code": null, "e": 1075, "s": 1009, "text": "Expected Time Complexity: O(N*N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1135, "s": 1075, "text": "Constraints:\n3 ≤ N ≤ 103\n-105 ≤ A[i] ≤ 105\n1 ≤ target ≤ 105" }, { "code": null, "e": 1137, "s": 1135, "text": "0" }, { "code": null, "e": 1154, "s": 1137, "text": "trivedipranjal02" }, { "code": null, "e": 1180, "s": 1154, "text": "This comment was deleted." }, { "code": null, "e": 1182, "s": 1180, "text": "0" }, { "code": null, "e": 1207, "s": 1182, "text": "gauravrastogi4 weeks ago" }, { "code": null, "e": 1222, "s": 1207, "text": "this is easy ?" }, { "code": null, "e": 1224, "s": 1222, "text": "0" }, { "code": null, "e": 1248, "s": 1224, "text": "patelneer4031 month ago" }, { "code": null, "e": 2080, "s": 1248, "text": " int i,diff1=10000,diff2=100000,end,start,sum; sort(arr.begin(),arr.end()); int n=arr.size(); for(i=0;i<n;i++) { start=i+1; end=n-1; while(start<end) { sum=arr[i]+arr[start]+arr[end]; if(sum==target) return sum; else if(sum>target){ end--; diff1=min(diff1,sum-target); } else if(sum<target){ start++; diff2=min(diff2,target-sum); } } } if(diff1 < diff2) return target+diff1; if(diff1==diff2) return target+diff1;" }, { "code": null, "e": 2119, "s": 2080, "text": " return target-diff2; }" }, { "code": null, "e": 2122, "s": 2119, "text": "+1" }, { "code": null, "e": 2151, "s": 2122, "text": "akkeshri140420012 months ago" }, { "code": null, "e": 3126, "s": 2151, "text": "int threeSumClosest(vector<int> arr, int target) {\n // Your code goes here\n int mini=INT_MAX;\n sort(arr.begin(),arr.end());\n int m=0;\n for(int i=0;i<arr.size();i++){\n int j=i+1;\n int k=arr.size()-1;\n while(j<k){\n if(arr[i]+arr[j]+arr[k]==target){\n return target;\n }\n else if(arr[i]+arr[j]+arr[k]<target){\n int len=abs((arr[i]+arr[j]+arr[k])-target);\n if(mini>len){\n mini=len;\n m=arr[i]+arr[j]+arr[k];\n }\n j++;\n }\n else{\n int len=abs((arr[i]+arr[j]+arr[k])-target);\n if(mini>=len){\n mini=len;\n m=arr[i]+arr[j]+arr[k];\n }\n k--;\n }\n }\n }\n return m;\n \n }" }, { "code": null, "e": 3128, "s": 3126, "text": "0" }, { "code": null, "e": 3151, "s": 3128, "text": "jswxingyu12 months ago" }, { "code": null, "e": 3167, "s": 3151, "text": "Python solution" }, { "code": null, "e": 3933, "s": 3167, "text": "class Solution:\n def threeSumClosest (self, arr, target):\n # Your Code Here\n arr.sort()\n N = len(arr)\n Sum = 1e10\n for i in range(N-2):\n a = arr[i]\n L = i + 1\n R = N - 1\n while L < R:\n temp = a+arr[L]+arr[R]\n if temp == target:\n return target\n elif temp > target:\n R -= 1\n else:\n L += 1\n \n if abs(temp - target) < abs(Sum - target):\n Sum = temp\n elif abs(temp - target) == abs(Sum - target) and temp > Sum:\n Sum = temp # record the bigger one\n \n return Sum" }, { "code": null, "e": 3935, "s": 3933, "text": "0" }, { "code": null, "e": 3957, "s": 3935, "text": "soumik8672 months ago" }, { "code": null, "e": 4843, "s": 3957, "text": "int threeSumClosest(vector<int> arr, int target) { sort(arr.begin(),arr.end()); int ans=INT_MAX; for(int i=0;i<arr.size();i++){ int x=0,y=arr.size()-1; int z=arr[i]; while(y>x){ if(x==i){ x++; continue; } if(y==i){ y--; continue; } if(z+arr[x]+arr[y]==target){ return target; } if(abs(target-ans)>abs(target-(z+arr[x]+arr[y]))){ ans=z+arr[x]+arr[y]; }else if(abs(target-ans)==abs(target-(z+arr[x]+arr[y]))){ ans=max(z+arr[x]+arr[y],ans); } if(z+arr[x]+arr[y]>target){ y--; }else{ x++; } } } return ans; }" }, { "code": null, "e": 4845, "s": 4843, "text": "0" }, { "code": null, "e": 4881, "s": 4845, "text": "mohammedhashimb190253cs2 months ago" }, { "code": null, "e": 4920, "s": 4881, "text": "How does the space complexity is O(1)?" }, { "code": null, "e": 5039, "s": 4920, "text": "we are clearly using most efficient sorting algorithms like merge sort or quick sort which take O(N) space complexity." }, { "code": null, "e": 5066, "s": 5039, "text": "Correct me if I'm wrong..." }, { "code": null, "e": 5069, "s": 5066, "text": "-1" }, { "code": null, "e": 5090, "s": 5069, "text": "parul7003 months ago" }, { "code": null, "e": 5716, "s": 5090, "text": "class Solution{ public: int threeSumClosest(vector<int> arr, int target) { int i,j,k,sum; int n=arr.size(),closestsum=INT_MAX; sort(arr.begin(),arr.end()); for(i=0;i<n-2;i++) { j=i+1; k=n-1; while(j<k) { sum=arr[i]+arr[j]+arr[k]; if(sum==target) return sum; if(abs(target-sum)<abs(target-closestsum)) closestsum=sum; if(abs(target-sum)==abs(target-closestsum)) closestsum=max(sum,closestsum); if(sum<target) j++; else k--; } } return closestsum; } };" }, { "code": null, "e": 5718, "s": 5716, "text": "0" }, { "code": null, "e": 5746, "s": 5718, "text": "harshshukla30983 months ago" }, { "code": null, "e": 6563, "s": 5746, "text": " int n=array.length; int i=0; long sum=0; Arrays.sort(array); long closesum=Integer.MAX_VALUE; for( i=0;i<n-2;i++){ int start=1+i,end=n-1; while(start<end){ sum=array[i]+array[start]+array[end]; if(Math.abs(target-sum)<Math.abs(target-closesum)){ closesum=sum; } // System.out.print(closesum); //closesum=; if(Math.abs(target-sum)==Math.abs(target-closesum)){ closesum=Math.max(closesum,sum); } if(target>sum){ start++; // System.out.print(start); } else{ end --; } } } return (int)closesum;" }, { "code": null, "e": 6598, "s": 6563, "text": "sumbtied by kouslendra and piyush " }, { "code": null, "e": 6601, "s": 6598, "text": "+1" }, { "code": null, "e": 6630, "s": 6601, "text": "ankitsinha1112004 months ago" }, { "code": null, "e": 7591, "s": 6630, "text": "class Solution{\n public:\n int threeSumClosest(vector<int> arr, int target) {\n sort(arr.begin(),arr.end());\n int i,j,k,d=INT_MAX,s=target,n=arr.size();\n for(i=0;i<n-1;i++)\n {\n j=i+1; k=n-1;\n while(j<k)\n {\n if(arr[i]+arr[j]+arr[k]==target)\n return target;\n else if(arr[i]+arr[j]+arr[k]<target)\n {\n if(d>abs(target-arr[i]-arr[j]-arr[k]))\n {\n d=abs(target-arr[i]-arr[j]-arr[k]);\n s=arr[i]+arr[j]+arr[k];\n }\n j++;\n }\n else\n {\n if(d>=abs(target-arr[i]-arr[j]-arr[k]))\n {\n d=abs(target-arr[i]-arr[j]-arr[k]);\n s=arr[i]+arr[j]+arr[k];\n }\n k--;\n }\n }\n }\n return s; \n }\n};" }, { "code": null, "e": 7737, "s": 7591, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7773, "s": 7737, "text": " Login to access your submissions. " }, { "code": null, "e": 7783, "s": 7773, "text": "\nProblem\n" }, { "code": null, "e": 7793, "s": 7783, "text": "\nContest\n" }, { "code": null, "e": 7856, "s": 7793, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8004, "s": 7856, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8212, "s": 8004, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8318, "s": 8212, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to create animation using XML file in an Android App?
This example demonstrates how do I create an animation using XML in an android app. 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"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:padding="4dp" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:textSize="24sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Have a Wonderful day!" android:layout_centerInParent="true" android:id="@+id/textView" /> <Button android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start Animation"/> </RelativeLayout> Step 3 − Create a new android resource directory (anim) and create these below mentioned anim resource files Myanim.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true"> <alpha android:duration="1000" android:fromAlpha="0.0" android:interpolator="@android:anim/accelerate_interpolator" android:toAlpha="1.0" /> </set> zoom.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true"> <scale android:duration="1000" android:fromXScale="1" android:fromYScale="1" android:pivotX="50%" android:pivotY="50%" android:toXScale="3" android:toYScale="3"></scale> </set> blink.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:duration="600" android:repeatMode="reverse" android:repeatCount="infinite"/> </set> Step 4 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements Animation.AnimationListener { TextView textView; Button button; Animation animation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); button = findViewById(R.id.button); animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink); animation.setAnimationListener(this); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setVisibility(View.VISIBLE); textView.startAnimation(animation); } }); } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation1) { } @Override public void onAnimationRepeat(Animation animation) { } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 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 the 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 − Click here to download the project code.
[ { "code": null, "e": 1146, "s": 1062, "text": "This example demonstrates how do I create an animation using XML in an android app." }, { "code": null, "e": 1275, "s": 1146, "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": 1340, "s": 1275, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2153, "s": 1340, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout 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:padding=\"4dp\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Have a Wonderful day!\"\n android:layout_centerInParent=\"true\"\n android:id=\"@+id/textView\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_alignParentBottom=\"true\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Start Animation\"/>\n</RelativeLayout>" }, { "code": null, "e": 2262, "s": 2153, "text": "Step 3 − Create a new android resource directory (anim) and create these below mentioned anim resource files" }, { "code": null, "e": 2273, "s": 2262, "text": "Myanim.xml" }, { "code": null, "e": 2577, "s": 2273, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter=\"true\">\n <alpha\n android:duration=\"1000\"\n android:fromAlpha=\"0.0\"\n android:interpolator=\"@android:anim/accelerate_interpolator\"\n android:toAlpha=\"1.0\" />\n</set>" }, { "code": null, "e": 2586, "s": 2577, "text": "zoom.xml" }, { "code": null, "e": 2937, "s": 2586, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter=\"true\">\n <scale\n android:duration=\"1000\"\n android:fromXScale=\"1\"\n android:fromYScale=\"1\"\n android:pivotX=\"50%\"\n android:pivotY=\"50%\"\n android:toXScale=\"3\"\n android:toYScale=\"3\"></scale>\n</set>" }, { "code": null, "e": 2947, "s": 2937, "text": "blink.xml" }, { "code": null, "e": 3290, "s": 2947, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<set xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <alpha android:fromAlpha=\"0.0\"\n android:toAlpha=\"1.0\"\n android:interpolator=\"@android:anim/accelerate_interpolator\"\n android:duration=\"600\"\n android:repeatMode=\"reverse\"\n android:repeatCount=\"infinite\"/>\n</set>" }, { "code": null, "e": 3347, "s": 3290, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4594, "s": 3347, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.view.animation.Animation;\nimport android.view.animation.AnimationUtils;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity implements\nAnimation.AnimationListener {\n TextView textView;\n Button button;\n Animation animation;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n button = findViewById(R.id.button);\n animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink);\n animation.setAnimationListener(this);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n textView.setVisibility(View.VISIBLE);\n textView.startAnimation(animation);\n }\n });\n }\n @Override\n public void onAnimationStart(Animation animation) {\n }\n @Override\n public void onAnimationEnd(Animation animation1) {\n }\n @Override\n public void onAnimationRepeat(Animation animation) {\n }\n}" }, { "code": null, "e": 4649, "s": 4594, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5334, "s": 4649, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5685, "s": 5334, "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 the 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": 5726, "s": 5685, "text": "Click here to download the project code." } ]
Find a specific column in all the tables in a database?
For this, use COLUMN_NAME and set LIKE with that specific column name. Let us find a specific column in an unknown table in a database − mysql> SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT -> FROM INFORMATION_SCHEMA.COLUMNS -> WHERE column_name LIKE '%StudentName%' -> AND table_schema = 'web'; This will produce the following output − +-------------------+-------------+-----------+-------------+----------------+ | TABLE_NAME | COLUMN_NAME | DATA_TYPE | IS_NULLABLE |COLUMN_DEFAULT | +-------------------+-------------+-----------+-------------+----------------+ | demotable215 | StudentName | varchar | YES | NULL | | demotable221 | StudentName | varchar | YES | NULL | | demotable224 | StudentName | varchar | YES | NULL | | demotable234 | StudentName | varchar | YES | NULL | | demotable269 | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | NO | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | json | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | NO | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | DemoTable | StudentName | varchar | YES | NULL | | view_DemoTable | StudentName | varchar | YES | NULL | +-------------------+-------------+-----------+-------------+----------------+ 19 rows in set (0.07 sec) Above displays all the tables with a specific column “StudentName”.
[ { "code": null, "e": 1199, "s": 1062, "text": "For this, use COLUMN_NAME and set LIKE with that specific column name. Let us find a specific column in an unknown table in a database −" }, { "code": null, "e": 1392, "s": 1199, "text": "mysql> SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT\n -> FROM INFORMATION_SCHEMA.COLUMNS\n -> WHERE column_name LIKE '%StudentName%'\n -> AND table_schema = 'web';" }, { "code": null, "e": 1433, "s": 1392, "text": "This will produce the following output −" }, { "code": null, "e": 3276, "s": 1433, "text": "+-------------------+-------------+-----------+-------------+----------------+\n| TABLE_NAME | COLUMN_NAME | DATA_TYPE | IS_NULLABLE |COLUMN_DEFAULT |\n+-------------------+-------------+-----------+-------------+----------------+\n| demotable215 | StudentName | varchar | YES | NULL |\n| demotable221 | StudentName | varchar | YES | NULL |\n| demotable224 | StudentName | varchar | YES | NULL |\n| demotable234 | StudentName | varchar | YES | NULL |\n| demotable269 | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | NO | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | json | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | NO | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| DemoTable | StudentName | varchar | YES | NULL |\n| view_DemoTable | StudentName | varchar | YES | NULL |\n+-------------------+-------------+-----------+-------------+----------------+\n19 rows in set (0.07 sec)" }, { "code": null, "e": 3344, "s": 3276, "text": "Above displays all the tables with a specific column “StudentName”." } ]
How to get and store Device ID in Android?
This example demonstrates how do I get and store Device ID in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); String ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); textView.setText("Device ID: "+ ID); } } Step 3 − Add the following code to src/MainActivity.java <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="24sp" android:textStyle="bold"/> </RelativeLayout> Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 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": 1133, "s": 1062, "text": "This example demonstrates how do I get and store Device ID in android." }, { "code": null, "e": 1262, "s": 1133, "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": 1327, "s": 1262, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1898, "s": 1327, "text": "import android.provider.Settings;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n String ID = Settings.Secure.getString(getContentResolver(),\n Settings.Secure.ANDROID_ID);\n textView.setText(\"Device ID: \"+ ID);\n }\n}" }, { "code": null, "e": 1955, "s": 1898, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2490, "s": 1955, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n 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 tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"/>\n</RelativeLayout>" }, { "code": null, "e": 2545, "s": 2490, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3251, "s": 2545, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3597, "s": 3251, "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 −" } ]
JavaScript - Math floor Method
This method returns the largest integer less than or equal to a number. Its syntax is as follows − Math.floor( x ) ; x − A numbers. Returns the largest integer less than or equal to a number x. Try the following example program. <html> <head> <title>JavaScript Math floor() Method</title> </head> <body> <script type = "text/javascript"> var value = Math.floor(10.3); document.write("First Test Value : " + value ); var value = Math.floor(30.9); document.write("<br />Second Test Value : " + value ); var value = Math.floor(-2.9); document.write("<br />Third Test Value : " + value ); var value = Math.floor(-2.2); document.write("<br />Fourth Test Value : " + value ); </script> </body> </html> First Test Value : 10 Second Test Value : 30 Third Test Value : -3 Fourth Test Value : -3 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2538, "s": 2466, "text": "This method returns the largest integer less than or equal to a number." }, { "code": null, "e": 2565, "s": 2538, "text": "Its syntax is as follows −" }, { "code": null, "e": 2584, "s": 2565, "text": "Math.floor( x ) ;\n" }, { "code": null, "e": 2600, "s": 2584, "text": "x − A numbers." }, { "code": null, "e": 2662, "s": 2600, "text": "Returns the largest integer less than or equal to a number x." }, { "code": null, "e": 2697, "s": 2662, "text": "Try the following example program." }, { "code": null, "e": 3318, "s": 2697, "text": "<html> \n <head>\n <title>JavaScript Math floor() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var value = Math.floor(10.3);\n document.write(\"First Test Value : \" + value );\n \n var value = Math.floor(30.9);\n document.write(\"<br />Second Test Value : \" + value ); \n \n var value = Math.floor(-2.9);\n document.write(\"<br />Third Test Value : \" + value ); \n \n var value = Math.floor(-2.2);\n document.write(\"<br />Fourth Test Value : \" + value ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3410, "s": 3318, "text": "First Test Value : 10\nSecond Test Value : 30\nThird Test Value : -3\nFourth Test Value : -3 \n" }, { "code": null, "e": 3445, "s": 3410, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3459, "s": 3445, "text": " Anadi Sharma" }, { "code": null, "e": 3493, "s": 3459, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3507, "s": 3493, "text": " Lets Kode It" }, { "code": null, "e": 3542, "s": 3507, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3559, "s": 3542, "text": " Frahaan Hussain" }, { "code": null, "e": 3594, "s": 3559, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3611, "s": 3594, "text": " Frahaan Hussain" }, { "code": null, "e": 3644, "s": 3611, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3672, "s": 3644, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3706, "s": 3672, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3734, "s": 3706, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3741, "s": 3734, "text": " Print" }, { "code": null, "e": 3752, "s": 3741, "text": " Add Notes" } ]
JavaScript Date constructor Property
Javascript date constructor property returns a reference to the array function that created the instance's prototype. Its syntax is as follows − date.constructor Returns the function that created this object's instance. Try the following example. <html> <head> <title>JavaScript Date constructor Property</title> </head> <body> <script type = "text/javascript"> var dt = new Date(); document.write("dt.constructor is : " + dt.constructor); </script> </body> </html> dt.constructor is: function Date() { [native code] } 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2584, "s": 2466, "text": "Javascript date constructor property returns a reference to the array function that created the instance's prototype." }, { "code": null, "e": 2611, "s": 2584, "text": "Its syntax is as follows −" }, { "code": null, "e": 2629, "s": 2611, "text": "date.constructor\n" }, { "code": null, "e": 2687, "s": 2629, "text": "Returns the function that created this object's instance." }, { "code": null, "e": 2714, "s": 2687, "text": "Try the following example." }, { "code": null, "e": 2995, "s": 2714, "text": "<html>\n <head>\n <title>JavaScript Date constructor Property</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date();\n document.write(\"dt.constructor is : \" + dt.constructor); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3050, "s": 2995, "text": "dt.constructor is: function Date() { [native code] } \n" }, { "code": null, "e": 3085, "s": 3050, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3099, "s": 3085, "text": " Anadi Sharma" }, { "code": null, "e": 3133, "s": 3099, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3147, "s": 3133, "text": " Lets Kode It" }, { "code": null, "e": 3182, "s": 3147, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3199, "s": 3182, "text": " Frahaan Hussain" }, { "code": null, "e": 3234, "s": 3199, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3251, "s": 3234, "text": " Frahaan Hussain" }, { "code": null, "e": 3284, "s": 3251, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3312, "s": 3284, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3346, "s": 3312, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3374, "s": 3346, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3381, "s": 3374, "text": " Print" }, { "code": null, "e": 3392, "s": 3381, "text": " Add Notes" } ]
Collections.binarySearch() in Java with Examples - GeeksforGeeks
28 Jun, 2021 java.util.Collections.binarySearch() method is a java.util.Collections class method that returns position of an object in a sorted list. // Returns index of key in sorted list sorted in // ascending order public static int binarySearch(List slist, T key) // Returns index of key in sorted list sorted in // order defined by Comparator c. public static int binarySearch(List slist, T key, Comparator c) If key is not present, the it returns "(-(insertion point) - 1)". The insertion point is defined as the point at which the key would be inserted into the list. The method throws ClassCastException if elements of list are not comparable using the specified comparator, or the search key is not comparable with the elements.Searching an int key in a list sorted in ascending order: Java // Java program to demonstrate working of Collections.// binarySearch()import java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<Integer>(); al.add(1); al.add(2); al.add(3); al.add(10); al.add(20); // 10 is present at index 3. int index = Collections.binarySearch(al, 10); System.out.println(index); // 13 is not present. 13 would have been inserted // at position 4. So the function returns (-4-1) // which is -5. index = Collections.binarySearch(al, 13); System.out.println(index); }} Output : 3 -5 Searching an int key in a list sorted in descending order. Java // Java program to demonstrate working of Collections.// binarySearch() in an array sorted in descending order.import java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<Integer>(); al.add(100); al.add(50); al.add(30); al.add(10); al.add(2); // The last parameter specifies the comparator // method used for sorting. int index = Collections.binarySearch( al, 50, Collections.reverseOrder()); System.out.println("Found at index " + index); }} Output : Found at index 1 Searching in a list of user-defined class objects: Java // Java program to demonstrate working of Collections.// binarySearch() in a list of user defined objectsimport java.util.*; class Binarysearch { public static void main(String[] args) { // Create a list List<Domain> l = new ArrayList<Domain>(); l.add(new Domain(10, "quiz.geeksforgeeks.org")); l.add(new Domain(20, "practice.geeksforgeeks.org")); l.add(new Domain(30, "code.geeksforgeeks.org")); l.add(new Domain(40, "www.geeksforgeeks.org")); Comparator<Domain> c = new Comparator<Domain>() { public int compare(Domain u1, Domain u2) { return u1.getId().compareTo(u2.getId()); } }; // Searching a domain with key value 10. To search // we create an object of domain with key 10. int index = Collections.binarySearch( l, new Domain(10, null), c); System.out.println("Found at index " + index); // Searching an item with key 5 index = Collections.binarySearch( l, new Domain(5, null), c); System.out.println(index); }} // A user-defined class to store domains with id and urlclass Domain { private int id; private String url; // Constructor public Domain(int id, String url) { this.id = id; this.url = url; } public Integer getId() { return Integer.valueOf(id); }} Output : 0 -1 Arrays.binarysearch() vs Collections.binarySearch() Arrays.binarysearch() works for arrays which can be of primitive data type also. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList. Important Points: If input list is not sorted, the results are undefined. If there are duplicates, there is no guarantee which one will be found. This method runs in log(n) time for a “random access” list like ArrayList. If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons. Reference : https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T)This article is contributed by Mohit Gupta. 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 jigneshk5 Prashant__Singh Binary Search Java - util package Java-Collections Java-Collections-Class Java-Functions Java Java Binary Search Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java Collections in Java Set in Java Overriding in Java
[ { "code": null, "e": 23847, "s": 23819, "text": "\n28 Jun, 2021" }, { "code": null, "e": 23985, "s": 23847, "text": "java.util.Collections.binarySearch() method is a java.util.Collections class method that returns position of an object in a sorted list. " }, { "code": null, "e": 24414, "s": 23985, "text": "// Returns index of key in sorted list sorted in\n// ascending order\npublic static int binarySearch(List slist, T key)\n\n// Returns index of key in sorted list sorted in\n// order defined by Comparator c.\npublic static int binarySearch(List slist, T key, Comparator c)\n\nIf key is not present, the it returns \"(-(insertion point) - 1)\". \nThe insertion point is defined as the point at which the key \nwould be inserted into the list." }, { "code": null, "e": 24636, "s": 24414, "text": "The method throws ClassCastException if elements of list are not comparable using the specified comparator, or the search key is not comparable with the elements.Searching an int key in a list sorted in ascending order: " }, { "code": null, "e": 24641, "s": 24636, "text": "Java" }, { "code": "// Java program to demonstrate working of Collections.// binarySearch()import java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<Integer>(); al.add(1); al.add(2); al.add(3); al.add(10); al.add(20); // 10 is present at index 3. int index = Collections.binarySearch(al, 10); System.out.println(index); // 13 is not present. 13 would have been inserted // at position 4. So the function returns (-4-1) // which is -5. index = Collections.binarySearch(al, 13); System.out.println(index); }}", "e": 25351, "s": 24641, "text": null }, { "code": null, "e": 25361, "s": 25351, "text": "Output : " }, { "code": null, "e": 25366, "s": 25361, "text": "3\n-5" }, { "code": null, "e": 25427, "s": 25366, "text": "Searching an int key in a list sorted in descending order. " }, { "code": null, "e": 25432, "s": 25427, "text": "Java" }, { "code": "// Java program to demonstrate working of Collections.// binarySearch() in an array sorted in descending order.import java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<Integer>(); al.add(100); al.add(50); al.add(30); al.add(10); al.add(2); // The last parameter specifies the comparator // method used for sorting. int index = Collections.binarySearch( al, 50, Collections.reverseOrder()); System.out.println(\"Found at index \" + index); }}", "e": 26079, "s": 25432, "text": null }, { "code": null, "e": 26089, "s": 26079, "text": "Output : " }, { "code": null, "e": 26106, "s": 26089, "text": "Found at index 1" }, { "code": null, "e": 26159, "s": 26106, "text": "Searching in a list of user-defined class objects: " }, { "code": null, "e": 26164, "s": 26159, "text": "Java" }, { "code": "// Java program to demonstrate working of Collections.// binarySearch() in a list of user defined objectsimport java.util.*; class Binarysearch { public static void main(String[] args) { // Create a list List<Domain> l = new ArrayList<Domain>(); l.add(new Domain(10, \"quiz.geeksforgeeks.org\")); l.add(new Domain(20, \"practice.geeksforgeeks.org\")); l.add(new Domain(30, \"code.geeksforgeeks.org\")); l.add(new Domain(40, \"www.geeksforgeeks.org\")); Comparator<Domain> c = new Comparator<Domain>() { public int compare(Domain u1, Domain u2) { return u1.getId().compareTo(u2.getId()); } }; // Searching a domain with key value 10. To search // we create an object of domain with key 10. int index = Collections.binarySearch( l, new Domain(10, null), c); System.out.println(\"Found at index \" + index); // Searching an item with key 5 index = Collections.binarySearch( l, new Domain(5, null), c); System.out.println(index); }} // A user-defined class to store domains with id and urlclass Domain { private int id; private String url; // Constructor public Domain(int id, String url) { this.id = id; this.url = url; } public Integer getId() { return Integer.valueOf(id); }}", "e": 27554, "s": 26164, "text": null }, { "code": null, "e": 27564, "s": 27554, "text": "Output : " }, { "code": null, "e": 27569, "s": 27564, "text": "0\n-1" }, { "code": null, "e": 27810, "s": 27569, "text": "Arrays.binarysearch() vs Collections.binarySearch() Arrays.binarysearch() works for arrays which can be of primitive data type also. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList. Important Points: " }, { "code": null, "e": 27866, "s": 27810, "text": "If input list is not sorted, the results are undefined." }, { "code": null, "e": 27938, "s": 27866, "text": "If there are duplicates, there is no guarantee which one will be found." }, { "code": null, "e": 28216, "s": 27938, "text": "This method runs in log(n) time for a “random access” list like ArrayList. If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons." }, { "code": null, "e": 28720, "s": 28216, "text": "Reference : https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T)This article is contributed by Mohit Gupta. 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": 28730, "s": 28720, "text": "jigneshk5" }, { "code": null, "e": 28746, "s": 28730, "text": "Prashant__Singh" }, { "code": null, "e": 28760, "s": 28746, "text": "Binary Search" }, { "code": null, "e": 28780, "s": 28760, "text": "Java - util package" }, { "code": null, "e": 28797, "s": 28780, "text": "Java-Collections" }, { "code": null, "e": 28820, "s": 28797, "text": "Java-Collections-Class" }, { "code": null, "e": 28835, "s": 28820, "text": "Java-Functions" }, { "code": null, "e": 28840, "s": 28835, "text": "Java" }, { "code": null, "e": 28845, "s": 28840, "text": "Java" }, { "code": null, "e": 28859, "s": 28845, "text": "Binary Search" }, { "code": null, "e": 28876, "s": 28859, "text": "Java-Collections" }, { "code": null, "e": 28974, "s": 28876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28983, "s": 28974, "text": "Comments" }, { "code": null, "e": 28996, "s": 28983, "text": "Old Comments" }, { "code": null, "e": 29015, "s": 28996, "text": "Interfaces in Java" }, { "code": null, "e": 29047, "s": 29015, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29065, "s": 29047, "text": "ArrayList in Java" }, { "code": null, "e": 29085, "s": 29065, "text": "Stack Class in Java" }, { "code": null, "e": 29117, "s": 29085, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29141, "s": 29117, "text": "Singleton Class in Java" }, { "code": null, "e": 29160, "s": 29141, "text": "LinkedList in Java" }, { "code": null, "e": 29180, "s": 29160, "text": "Collections in Java" }, { "code": null, "e": 29192, "s": 29180, "text": "Set in Java" } ]
Android Hello World Example
The first step is to create a simple Android Application using Android Studio. Follow the option File -> New project ->Configure your new project -> selct factor your application is run on -> add activity ->Customise your activity -> and finally select finish wizard from the wizard list. Now name your application as HelloWorld using the wizard window as follows − Next, follow the instructions provided and keep all other entries as default till the final step. Once your project is created successfully, you will have following project screen − Before you run your app, you should be aware of a few directories and files in the Android project − build This contains the auto generated file which are as Aidl,Build configuration, and R(R.JAVA) Libs This is a directory to add the libraries to develop the android applications src This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon. res This is a directory,which is having drawable,layout,values,and android manifest file res/drawable-hdpi This is a directory for drawable objects that are designed for high-density screens. res/layout This is a directory for files that define your app's user interface. res/menu This is a directory for menu objects that are designed to make menu in android applications res/values This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions. AndroidManifest.xml This is the manifest file which describes the fundamental characteristics of the app and defines each of its components. Following section will give a brief overview few of the important application files. The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application − package com.example.helloworld; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of many methods that are fi red when an activity is loaded. Whatever component you develop as a part of your application, you must declare all its components in a manifest.xml which resides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file − <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloworld" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest> Here <application>...</application> tags enclosed the components related to the application. Attribute android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags. The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon. The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in the strings.xml fi le, which is "HelloWorld". Similar way, other strings get populated in the application. Following is the list of tags which you will use in your manifest file to specify different Android application components − <activity>elements for activities <service> elements for services <receiver> elements for broadcast receivers <provider> elements for content providers The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file − <resources> <string name="app_name">HelloWorld</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">MainActivity</string> </resources> The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your "Hello World!" application, this file will have following content related to default layout − <RelativeLayout 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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:padding="@dimen/padding_medium" android:text="@string/hello_world" tools:context=".MainActivity" /> </RelativeLayout> This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is an Android control used to build the GUI and it have various attribuites like android:layout_width, android:layout_height etc which are being used to set its width and height etc. The @string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in the strings.xml fi le, which is "Hello World!". Let's try to run our Hello World! application we just created. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Congratulations!!! you have developed your first Android Application and now just keep following rest of the tutorial step by step to become a great Android Developer. All the very best. 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3974, "s": 3607, "text": "The first step is to create a simple Android Application using Android Studio. Follow the option File -> New project ->Configure your new project -> selct factor your application is run on -> add activity ->Customise your activity -> and finally select finish wizard from the wizard list. Now name your application as HelloWorld using the wizard window as follows −" }, { "code": null, "e": 4156, "s": 3974, "text": "Next, follow the instructions provided and keep all other entries as default till the final step. Once your project is created successfully, you will have following project screen −" }, { "code": null, "e": 4257, "s": 4156, "text": "Before you run your app, you should be aware of a few directories and files in the Android project −" }, { "code": null, "e": 4263, "s": 4257, "text": "build" }, { "code": null, "e": 4354, "s": 4263, "text": "This contains the auto generated file which are as Aidl,Build configuration, and R(R.JAVA)" }, { "code": null, "e": 4359, "s": 4354, "text": "Libs" }, { "code": null, "e": 4436, "s": 4359, "text": "This is a directory to add the libraries to develop the android applications" }, { "code": null, "e": 4440, "s": 4436, "text": "src" }, { "code": null, "e": 4633, "s": 4440, "text": "This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon." }, { "code": null, "e": 4637, "s": 4633, "text": "res" }, { "code": null, "e": 4722, "s": 4637, "text": "This is a directory,which is having drawable,layout,values,and android manifest file" }, { "code": null, "e": 4740, "s": 4722, "text": "res/drawable-hdpi" }, { "code": null, "e": 4825, "s": 4740, "text": "This is a directory for drawable objects that are designed for high-density screens." }, { "code": null, "e": 4836, "s": 4825, "text": "res/layout" }, { "code": null, "e": 4905, "s": 4836, "text": "This is a directory for files that define your app's user interface." }, { "code": null, "e": 4914, "s": 4905, "text": "res/menu" }, { "code": null, "e": 5006, "s": 4914, "text": "This is a directory for menu objects that are designed to make menu in android applications" }, { "code": null, "e": 5017, "s": 5006, "text": "res/values" }, { "code": null, "e": 5145, "s": 5017, "text": "This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions." }, { "code": null, "e": 5165, "s": 5145, "text": "AndroidManifest.xml" }, { "code": null, "e": 5286, "s": 5165, "text": "This is the manifest file which describes the fundamental characteristics of the app and defines each of its components." }, { "code": null, "e": 5371, "s": 5286, "text": "Following section will give a brief overview few of the important application files." }, { "code": null, "e": 5643, "s": 5371, "text": "The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application −" }, { "code": null, "e": 5971, "s": 5643, "text": "package com.example.helloworld;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 6160, "s": 5971, "text": "Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of many methods that are fi red when an activity is loaded." }, { "code": null, "e": 6581, "s": 6160, "text": "Whatever component you develop as a part of your application, you must declare all its components in a manifest.xml which resides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file −" }, { "code": null, "e": 7340, "s": 6581, "text": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.helloworld\"\n android:versionCode=\"1\"\n android:versionName=\"1.0\" >\n \n <uses-sdk\n android:minSdkVersion=\"8\"\n android:targetSdkVersion=\"22\" />\n \n <application\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/title_activity_main\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\"/>\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 7611, "s": 7340, "text": "Here <application>...</application> tags enclosed the components related to the application. Attribute android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders" }, { "code": null, "e": 7903, "s": 7611, "text": "The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags." }, { "code": null, "e": 8209, "s": 7903, "text": "The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon." }, { "code": null, "e": 8441, "s": 8209, "text": "The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in the strings.xml fi le, which is \"HelloWorld\". Similar way, other strings get populated in the application." }, { "code": null, "e": 8566, "s": 8441, "text": "Following is the list of tags which you will use in your manifest file to specify different Android application components −" }, { "code": null, "e": 8600, "s": 8566, "text": "<activity>elements for activities" }, { "code": null, "e": 8632, "s": 8600, "text": "<service> elements for services" }, { "code": null, "e": 8676, "s": 8632, "text": "<receiver> elements for broadcast receivers" }, { "code": null, "e": 8718, "s": 8676, "text": "<provider> elements for content providers" }, { "code": null, "e": 9060, "s": 8718, "text": "The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file −" }, { "code": null, "e": 9294, "s": 9060, "text": "<resources>\n <string name=\"app_name\">HelloWorld</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"menu_settings\">Settings</string>\n <string name=\"title_activity_main\">MainActivity</string>\n</resources>" }, { "code": null, "e": 9623, "s": 9294, "text": "The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your \"Hello World!\" application, this file will have following content related to default layout −" }, { "code": null, "e": 10161, "s": 9623, "text": "<RelativeLayout 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\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\"\n android:padding=\"@dimen/padding_medium\"\n android:text=\"@string/hello_world\"\n tools:context=\".MainActivity\" />\n\n</RelativeLayout>" }, { "code": null, "e": 10634, "s": 10161, "text": "This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is an Android control used to build the GUI and it have various attribuites like android:layout_width, android:layout_height etc which are being used to set its width and height etc. The @string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in the strings.xml fi le, which is \"Hello World!\"." }, { "code": null, "e": 11039, "s": 10634, "text": "Let's try to run our Hello World! application we just created. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −" }, { "code": null, "e": 11226, "s": 11039, "text": "Congratulations!!! you have developed your first Android Application and now just keep following rest of the tutorial step by step to become a great Android Developer. All the very best." }, { "code": null, "e": 11261, "s": 11226, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11273, "s": 11261, "text": " Aditya Dua" }, { "code": null, "e": 11308, "s": 11273, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11322, "s": 11308, "text": " Sharad Kumar" }, { "code": null, "e": 11354, "s": 11322, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 11371, "s": 11354, "text": " Abhilash Nelson" }, { "code": null, "e": 11406, "s": 11371, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11423, "s": 11406, "text": " Abhilash Nelson" }, { "code": null, "e": 11458, "s": 11423, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11475, "s": 11458, "text": " Abhilash Nelson" }, { "code": null, "e": 11508, "s": 11475, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 11525, "s": 11508, "text": " Abhilash Nelson" }, { "code": null, "e": 11532, "s": 11525, "text": " Print" }, { "code": null, "e": 11543, "s": 11532, "text": " Add Notes" } ]
How to check whether an array is empty using PHP? - GeeksforGeeks
31 Jul, 2021 An empty array can sometimes cause software crash or unexpected outputs. To avoid this, it is better to check whether an array is empty or not beforehand. There are various methods and functions available in PHP to check whether the defined or given array is an empty or not. Some of them are given below: Using empty() Function: This function determines whether a given variable is empty. This function does not return a warning if a variable does not exist.Syntax:bool empty( $var )Example:<?php // Declare an array and initialize it$non_empty_array = array('URL' => 'https://www.geeksforgeeks.org/'); // Declare an empty array$empty_array = array(); // Condition to check array is empty or notif(!empty($non_empty_array)) echo "Given Array is not empty <br>"; if(empty($empty_array)) echo "Given Array is empty";?>Output:Given Array is not empty Given Array is empty Using count Function: This function counts all the elements in an array. If number of elements in array is zero, then it will display empty array.Syntax:int count( $array_or_countable )Example:<?php // Declare an empty array $empty_array = array(); // Function to count array // element and use conditionif(count($empty_array) == 0) echo "Array is empty";else echo "Array is non- empty";?>Output:Array is empty Using sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty.Example:<?php // Declare an empty array$empty_array = array(); // Use array index to check// array is empty or notif( sizeof($empty_array) == 0 ) echo "Empty Array";else echo "Non-Empty Array";?>Output:Empty Array Using empty() Function: This function determines whether a given variable is empty. This function does not return a warning if a variable does not exist.Syntax:bool empty( $var )Example:<?php // Declare an array and initialize it$non_empty_array = array('URL' => 'https://www.geeksforgeeks.org/'); // Declare an empty array$empty_array = array(); // Condition to check array is empty or notif(!empty($non_empty_array)) echo "Given Array is not empty <br>"; if(empty($empty_array)) echo "Given Array is empty";?>Output:Given Array is not empty Given Array is empty Syntax: bool empty( $var ) Example: <?php // Declare an array and initialize it$non_empty_array = array('URL' => 'https://www.geeksforgeeks.org/'); // Declare an empty array$empty_array = array(); // Condition to check array is empty or notif(!empty($non_empty_array)) echo "Given Array is not empty <br>"; if(empty($empty_array)) echo "Given Array is empty";?> Given Array is not empty Given Array is empty Using count Function: This function counts all the elements in an array. If number of elements in array is zero, then it will display empty array.Syntax:int count( $array_or_countable )Example:<?php // Declare an empty array $empty_array = array(); // Function to count array // element and use conditionif(count($empty_array) == 0) echo "Array is empty";else echo "Array is non- empty";?>Output:Array is empty Syntax: int count( $array_or_countable ) Example: <?php // Declare an empty array $empty_array = array(); // Function to count array // element and use conditionif(count($empty_array) == 0) echo "Array is empty";else echo "Array is non- empty";?> Array is empty Using sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty.Example:<?php // Declare an empty array$empty_array = array(); // Use array index to check// array is empty or notif( sizeof($empty_array) == 0 ) echo "Empty Array";else echo "Non-Empty Array";?>Output:Empty Array Example: <?php // Declare an empty array$empty_array = array(); // Use array index to check// array is empty or notif( sizeof($empty_array) == 0 ) echo "Empty Array";else echo "Non-Empty Array";?> Empty Array PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Picked PHP PHP Programs PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to run JavaScript from PHP? How to pass JavaScript variables to PHP ? Download file from URL using PHP How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to run JavaScript from PHP? How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP
[ { "code": null, "e": 24450, "s": 24422, "text": "\n31 Jul, 2021" }, { "code": null, "e": 24756, "s": 24450, "text": "An empty array can sometimes cause software crash or unexpected outputs. To avoid this, it is better to check whether an array is empty or not beforehand. There are various methods and functions available in PHP to check whether the defined or given array is an empty or not. Some of them are given below:" }, { "code": null, "e": 26119, "s": 24756, "text": "Using empty() Function: This function determines whether a given variable is empty. This function does not return a warning if a variable does not exist.Syntax:bool empty( $var )Example:<?php // Declare an array and initialize it$non_empty_array = array('URL' => 'https://www.geeksforgeeks.org/'); // Declare an empty array$empty_array = array(); // Condition to check array is empty or notif(!empty($non_empty_array)) echo \"Given Array is not empty <br>\"; if(empty($empty_array)) echo \"Given Array is empty\";?>Output:Given Array is not empty Given Array is empty\nUsing count Function: This function counts all the elements in an array. If number of elements in array is zero, then it will display empty array.Syntax:int count( $array_or_countable )Example:<?php // Declare an empty array $empty_array = array(); // Function to count array // element and use conditionif(count($empty_array) == 0) echo \"Array is empty\";else echo \"Array is non- empty\";?>Output:Array is empty\nUsing sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty.Example:<?php // Declare an empty array$empty_array = array(); // Use array index to check// array is empty or notif( sizeof($empty_array) == 0 ) echo \"Empty Array\";else echo \"Non-Empty Array\";?>Output:Empty Array\n" }, { "code": null, "e": 26695, "s": 26119, "text": "Using empty() Function: This function determines whether a given variable is empty. This function does not return a warning if a variable does not exist.Syntax:bool empty( $var )Example:<?php // Declare an array and initialize it$non_empty_array = array('URL' => 'https://www.geeksforgeeks.org/'); // Declare an empty array$empty_array = array(); // Condition to check array is empty or notif(!empty($non_empty_array)) echo \"Given Array is not empty <br>\"; if(empty($empty_array)) echo \"Given Array is empty\";?>Output:Given Array is not empty Given Array is empty\n" }, { "code": null, "e": 26703, "s": 26695, "text": "Syntax:" }, { "code": null, "e": 26722, "s": 26703, "text": "bool empty( $var )" }, { "code": null, "e": 26731, "s": 26722, "text": "Example:" }, { "code": "<?php // Declare an array and initialize it$non_empty_array = array('URL' => 'https://www.geeksforgeeks.org/'); // Declare an empty array$empty_array = array(); // Condition to check array is empty or notif(!empty($non_empty_array)) echo \"Given Array is not empty <br>\"; if(empty($empty_array)) echo \"Given Array is empty\";?>", "e": 27068, "s": 26731, "text": null }, { "code": null, "e": 27115, "s": 27068, "text": "Given Array is not empty Given Array is empty\n" }, { "code": null, "e": 27538, "s": 27115, "text": "Using count Function: This function counts all the elements in an array. If number of elements in array is zero, then it will display empty array.Syntax:int count( $array_or_countable )Example:<?php // Declare an empty array $empty_array = array(); // Function to count array // element and use conditionif(count($empty_array) == 0) echo \"Array is empty\";else echo \"Array is non- empty\";?>Output:Array is empty\n" }, { "code": null, "e": 27546, "s": 27538, "text": "Syntax:" }, { "code": null, "e": 27579, "s": 27546, "text": "int count( $array_or_countable )" }, { "code": null, "e": 27588, "s": 27579, "text": "Example:" }, { "code": "<?php // Declare an empty array $empty_array = array(); // Function to count array // element and use conditionif(count($empty_array) == 0) echo \"Array is empty\";else echo \"Array is non- empty\";?>", "e": 27796, "s": 27588, "text": null }, { "code": null, "e": 27812, "s": 27796, "text": "Array is empty\n" }, { "code": null, "e": 28178, "s": 27812, "text": "Using sizeof() function: This method check the size of array. If the size of array is zero then array is empty otherwise array is not empty.Example:<?php // Declare an empty array$empty_array = array(); // Use array index to check// array is empty or notif( sizeof($empty_array) == 0 ) echo \"Empty Array\";else echo \"Non-Empty Array\";?>Output:Empty Array\n" }, { "code": null, "e": 28187, "s": 28178, "text": "Example:" }, { "code": "<?php // Declare an empty array$empty_array = array(); // Use array index to check// array is empty or notif( sizeof($empty_array) == 0 ) echo \"Empty Array\";else echo \"Non-Empty Array\";?>", "e": 28386, "s": 28187, "text": null }, { "code": null, "e": 28399, "s": 28386, "text": "Empty Array\n" }, { "code": null, "e": 28568, "s": 28399, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 28575, "s": 28568, "text": "Picked" }, { "code": null, "e": 28579, "s": 28575, "text": "PHP" }, { "code": null, "e": 28592, "s": 28579, "text": "PHP Programs" }, { "code": null, "e": 28596, "s": 28592, "text": "PHP" }, { "code": null, "e": 28694, "s": 28596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28734, "s": 28694, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28779, "s": 28734, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28811, "s": 28779, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 28853, "s": 28811, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 28886, "s": 28853, "text": "Download file from URL using PHP" }, { "code": null, "e": 28926, "s": 28886, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28978, "s": 28926, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 29010, "s": 28978, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 29052, "s": 29010, "text": "How to pass JavaScript variables to PHP ?" } ]
Maximize the count of adjacent element pairs with even sum by rearranging the Array - GeeksforGeeks
12 Jul, 2021 Given an array, arr[] of N integers, the task is to find the maximum possible count of adjacent pairs with an even sum, rearranging the array arr[]. Examples: Input: arr[] = {5, 5, 1}Output: 2Explanation:The given array is already arranged to give the maximum count of adjacent pairs with an even sum. {arr[0](= 5), arr[1](= 5}, the sum of the elements is 10, which is even.{arr[1](= 5), arr[2](= 1}, the sum of the elements is 6, which is even. {arr[0](= 5), arr[1](= 5}, the sum of the elements is 10, which is even. {arr[1](= 5), arr[2](= 1}, the sum of the elements is 6, which is even. Therefore, there are totals of 2 adjacent pairs with an even sum. And it is also the maximum possible count. Input: arr[] = {9, 13, 15, 3, 16, 9, 13, 18}Output: 6Explanation:One way to obtain the maximum count is to rearrange the array as {9, 9, 3, 13, 13, 15, 16, 18}. {arr[0](= 9), arr[1](= 9}, the sum of the elements is 18, which is even.{arr[1](= 9), arr[2](= 3}, the sum of the elements is 12, which is even.{arr[2](= 3), arr[3](= 13}, the sum of the elements is 16, which is even.{arr[3](= 13), arr[4](= 13}, the sum of the elements is 26, which is even.{arr[4](= 13), arr[5](= 15}, the sum of the elements is 28, which is even.{arr[5](= 15), arr[6](= 16}, the sum of the elements is 31, which is not even.{arr[6](= 16), arr[7](= 18}, the sum of the elements is 34, which is even. {arr[0](= 9), arr[1](= 9}, the sum of the elements is 18, which is even. {arr[1](= 9), arr[2](= 3}, the sum of the elements is 12, which is even. {arr[2](= 3), arr[3](= 13}, the sum of the elements is 16, which is even. {arr[3](= 13), arr[4](= 13}, the sum of the elements is 26, which is even. {arr[4](= 13), arr[5](= 15}, the sum of the elements is 28, which is even. {arr[5](= 15), arr[6](= 16}, the sum of the elements is 31, which is not even. {arr[6](= 16), arr[7](= 18}, the sum of the elements is 34, which is even. Therefore, there are a total of 6 adjacent pairs with an even sum. And it is also the maximum possible count. Naive Approach: The simplest approach is to try every possible arrangement of the elements and then count the number of the adjacent pairs with an even sum. Time Complexity: O(N*N!)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized based on the following observations: It is known that:Odd + Odd = EvenEven + Even = EvenEven + Odd = OddOdd + Even = OddThe total count of adjacent pairs is N-1.Therefore, the maximum count can be obtained by putting all even numbers together and then all odd numbers or vice versa.Rearranging in the above-mentioned way, there will be only one pair of adjacent elements with an odd sum which will be at the junction of even numbers and odd numbers. It is known that:Odd + Odd = EvenEven + Even = EvenEven + Odd = OddOdd + Even = Odd Odd + Odd = Even Even + Even = Even Even + Odd = Odd Odd + Even = Odd The total count of adjacent pairs is N-1. Therefore, the maximum count can be obtained by putting all even numbers together and then all odd numbers or vice versa. Rearranging in the above-mentioned way, there will be only one pair of adjacent elements with an odd sum which will be at the junction of even numbers and odd numbers. Follow the steps below to solve the problem: Find the count of odd numbers and even numbers in an array and then store them in variables say odd and even. If odd and even both are greater than 0, then print the total count N-2 as the answer. Otherwise, print N-1 as the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum count// pair of adjacent elements with// even sumint maximumCount(int arr[], int N){ // Stores count of odd numbers int odd = 0; // Stores count of even numbers int even = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd and even) return N - 2; // Otherwise else return N - 1;} // Driver Codeint main() { int arr[] = { 9, 13, 15, 3, 16, 9, 13, 18 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maximumCount(arr, N); return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { // Function to find maximum count // pair of adjacent elements with // even sum static int maximumCount(int arr[], int N) { // Stores count of odd numbers int odd = 0; // Stores count of even numbers int even = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2 == 1) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd > 0 && even > 0) return N - 2; // Otherwise else return N - 1; } // Driver Code public static void main(String[] args) { int arr[] = { 9, 13, 15, 3, 16, 9, 13, 18 }; int N = arr.length; System.out.println(maximumCount(arr, N)); }} // This code is contributed by Potta Lokesh # Python 3 program for the above approach # Function to find maximum count# pair of adjacent elements with# even sumdef maximumCount(arr, N): # Stores count of odd numbers odd = 0 # Stores count of even numbers even = 0 # Traverse the array arr[] for i in range(N): # If arr[i]%2 is 1 if (arr[i] % 2): odd += 1 # Else else: even += 1 # If odd and even both # are greater than 0 if (odd and even): return N - 2 # Otherwise else: return N - 1 # Driver Codeif __name__ == '__main__': arr = [9, 13, 15, 3, 16, 9, 13, 18] N = len(arr) print(maximumCount(arr, N)) # This code is contributed by bgangwar59. // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find maximum count// pair of adjacent elements with// even sumstatic int maximumCount(int []arr, int N){ // Stores count of odd numbers int odd = 0; // Stores count of even numbers int even = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2 !=0) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd!=0 && even!=0) return N - 2; // Otherwise else return N - 1;} // Driver Codepublic static void Main() { int []arr = { 9, 13, 15, 3, 16, 9, 13, 18 }; int N = arr.Length; Console.Write(maximumCount(arr, N)); }} // This code is contributed by ipg2016107. <script> // JavaScript program for the above approach // Function to find maximum count // pair of adjacent elements with // even sum function maximumCount(arr, N) { // Stores count of odd numbers let odd = 0; // Stores count of even numbers let even = 0; // Traverse the array arr[] for (let i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd && even) return N - 2; // Otherwise else return N - 1; } // Driver Code let arr = [9, 13, 15, 3, 16, 9, 13, 18]; let N = arr.length; document.write(maximumCount(arr, N)); // This code is contributed by Potta Lokesh </script> 6 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 bgangwar59 ipg2016107 array-rearrange Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24405, "s": 24377, "text": "\n12 Jul, 2021" }, { "code": null, "e": 24554, "s": 24405, "text": "Given an array, arr[] of N integers, the task is to find the maximum possible count of adjacent pairs with an even sum, rearranging the array arr[]." }, { "code": null, "e": 24564, "s": 24554, "text": "Examples:" }, { "code": null, "e": 24707, "s": 24564, "text": "Input: arr[] = {5, 5, 1}Output: 2Explanation:The given array is already arranged to give the maximum count of adjacent pairs with an even sum." }, { "code": null, "e": 24851, "s": 24707, "text": "{arr[0](= 5), arr[1](= 5}, the sum of the elements is 10, which is even.{arr[1](= 5), arr[2](= 1}, the sum of the elements is 6, which is even." }, { "code": null, "e": 24924, "s": 24851, "text": "{arr[0](= 5), arr[1](= 5}, the sum of the elements is 10, which is even." }, { "code": null, "e": 24996, "s": 24924, "text": "{arr[1](= 5), arr[2](= 1}, the sum of the elements is 6, which is even." }, { "code": null, "e": 25105, "s": 24996, "text": "Therefore, there are totals of 2 adjacent pairs with an even sum. And it is also the maximum possible count." }, { "code": null, "e": 25266, "s": 25105, "text": "Input: arr[] = {9, 13, 15, 3, 16, 9, 13, 18}Output: 6Explanation:One way to obtain the maximum count is to rearrange the array as {9, 9, 3, 13, 13, 15, 16, 18}." }, { "code": null, "e": 25784, "s": 25266, "text": "{arr[0](= 9), arr[1](= 9}, the sum of the elements is 18, which is even.{arr[1](= 9), arr[2](= 3}, the sum of the elements is 12, which is even.{arr[2](= 3), arr[3](= 13}, the sum of the elements is 16, which is even.{arr[3](= 13), arr[4](= 13}, the sum of the elements is 26, which is even.{arr[4](= 13), arr[5](= 15}, the sum of the elements is 28, which is even.{arr[5](= 15), arr[6](= 16}, the sum of the elements is 31, which is not even.{arr[6](= 16), arr[7](= 18}, the sum of the elements is 34, which is even." }, { "code": null, "e": 25857, "s": 25784, "text": "{arr[0](= 9), arr[1](= 9}, the sum of the elements is 18, which is even." }, { "code": null, "e": 25930, "s": 25857, "text": "{arr[1](= 9), arr[2](= 3}, the sum of the elements is 12, which is even." }, { "code": null, "e": 26004, "s": 25930, "text": "{arr[2](= 3), arr[3](= 13}, the sum of the elements is 16, which is even." }, { "code": null, "e": 26079, "s": 26004, "text": "{arr[3](= 13), arr[4](= 13}, the sum of the elements is 26, which is even." }, { "code": null, "e": 26154, "s": 26079, "text": "{arr[4](= 13), arr[5](= 15}, the sum of the elements is 28, which is even." }, { "code": null, "e": 26233, "s": 26154, "text": "{arr[5](= 15), arr[6](= 16}, the sum of the elements is 31, which is not even." }, { "code": null, "e": 26308, "s": 26233, "text": "{arr[6](= 16), arr[7](= 18}, the sum of the elements is 34, which is even." }, { "code": null, "e": 26418, "s": 26308, "text": "Therefore, there are a total of 6 adjacent pairs with an even sum. And it is also the maximum possible count." }, { "code": null, "e": 26575, "s": 26418, "text": "Naive Approach: The simplest approach is to try every possible arrangement of the elements and then count the number of the adjacent pairs with an even sum." }, { "code": null, "e": 26621, "s": 26575, "text": "Time Complexity: O(N*N!)Auxiliary Space: O(1)" }, { "code": null, "e": 26714, "s": 26621, "text": "Efficient Approach: The above approach can be optimized based on the following observations:" }, { "code": null, "e": 27127, "s": 26714, "text": "It is known that:Odd + Odd = EvenEven + Even = EvenEven + Odd = OddOdd + Even = OddThe total count of adjacent pairs is N-1.Therefore, the maximum count can be obtained by putting all even numbers together and then all odd numbers or vice versa.Rearranging in the above-mentioned way, there will be only one pair of adjacent elements with an odd sum which will be at the junction of even numbers and odd numbers." }, { "code": null, "e": 27211, "s": 27127, "text": "It is known that:Odd + Odd = EvenEven + Even = EvenEven + Odd = OddOdd + Even = Odd" }, { "code": null, "e": 27228, "s": 27211, "text": "Odd + Odd = Even" }, { "code": null, "e": 27247, "s": 27228, "text": "Even + Even = Even" }, { "code": null, "e": 27264, "s": 27247, "text": "Even + Odd = Odd" }, { "code": null, "e": 27281, "s": 27264, "text": "Odd + Even = Odd" }, { "code": null, "e": 27323, "s": 27281, "text": "The total count of adjacent pairs is N-1." }, { "code": null, "e": 27445, "s": 27323, "text": "Therefore, the maximum count can be obtained by putting all even numbers together and then all odd numbers or vice versa." }, { "code": null, "e": 27613, "s": 27445, "text": "Rearranging in the above-mentioned way, there will be only one pair of adjacent elements with an odd sum which will be at the junction of even numbers and odd numbers." }, { "code": null, "e": 27658, "s": 27613, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27768, "s": 27658, "text": "Find the count of odd numbers and even numbers in an array and then store them in variables say odd and even." }, { "code": null, "e": 27855, "s": 27768, "text": "If odd and even both are greater than 0, then print the total count N-2 as the answer." }, { "code": null, "e": 27891, "s": 27855, "text": "Otherwise, print N-1 as the answer." }, { "code": null, "e": 27942, "s": 27891, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27946, "s": 27942, "text": "C++" }, { "code": null, "e": 27951, "s": 27946, "text": "Java" }, { "code": null, "e": 27959, "s": 27951, "text": "Python3" }, { "code": null, "e": 27962, "s": 27959, "text": "C#" }, { "code": null, "e": 27973, "s": 27962, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum count// pair of adjacent elements with// even sumint maximumCount(int arr[], int N){ // Stores count of odd numbers int odd = 0; // Stores count of even numbers int even = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd and even) return N - 2; // Otherwise else return N - 1;} // Driver Codeint main() { int arr[] = { 9, 13, 15, 3, 16, 9, 13, 18 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maximumCount(arr, N); return 0;}", "e": 28762, "s": 27973, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { // Function to find maximum count // pair of adjacent elements with // even sum static int maximumCount(int arr[], int N) { // Stores count of odd numbers int odd = 0; // Stores count of even numbers int even = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2 == 1) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd > 0 && even > 0) return N - 2; // Otherwise else return N - 1; } // Driver Code public static void main(String[] args) { int arr[] = { 9, 13, 15, 3, 16, 9, 13, 18 }; int N = arr.length; System.out.println(maximumCount(arr, N)); }} // This code is contributed by Potta Lokesh", "e": 29760, "s": 28762, "text": null }, { "code": "# Python 3 program for the above approach # Function to find maximum count# pair of adjacent elements with# even sumdef maximumCount(arr, N): # Stores count of odd numbers odd = 0 # Stores count of even numbers even = 0 # Traverse the array arr[] for i in range(N): # If arr[i]%2 is 1 if (arr[i] % 2): odd += 1 # Else else: even += 1 # If odd and even both # are greater than 0 if (odd and even): return N - 2 # Otherwise else: return N - 1 # Driver Codeif __name__ == '__main__': arr = [9, 13, 15, 3, 16, 9, 13, 18] N = len(arr) print(maximumCount(arr, N)) # This code is contributed by bgangwar59.", "e": 30488, "s": 29760, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find maximum count// pair of adjacent elements with// even sumstatic int maximumCount(int []arr, int N){ // Stores count of odd numbers int odd = 0; // Stores count of even numbers int even = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2 !=0) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd!=0 && even!=0) return N - 2; // Otherwise else return N - 1;} // Driver Codepublic static void Main() { int []arr = { 9, 13, 15, 3, 16, 9, 13, 18 }; int N = arr.Length; Console.Write(maximumCount(arr, N)); }} // This code is contributed by ipg2016107.", "e": 31340, "s": 30488, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find maximum count // pair of adjacent elements with // even sum function maximumCount(arr, N) { // Stores count of odd numbers let odd = 0; // Stores count of even numbers let even = 0; // Traverse the array arr[] for (let i = 0; i < N; i++) { // If arr[i]%2 is 1 if (arr[i] % 2) odd++; // Else else even++; } // If odd and even both // are greater than 0 if (odd && even) return N - 2; // Otherwise else return N - 1; } // Driver Code let arr = [9, 13, 15, 3, 16, 9, 13, 18]; let N = arr.length; document.write(maximumCount(arr, N)); // This code is contributed by Potta Lokesh </script>", "e": 32361, "s": 31340, "text": null }, { "code": null, "e": 32366, "s": 32364, "text": "6" }, { "code": null, "e": 32413, "s": 32370, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 32429, "s": 32415, "text": "lokeshpotta20" }, { "code": null, "e": 32440, "s": 32429, "text": "bgangwar59" }, { "code": null, "e": 32451, "s": 32440, "text": "ipg2016107" }, { "code": null, "e": 32467, "s": 32451, "text": "array-rearrange" }, { "code": null, "e": 32474, "s": 32467, "text": "Arrays" }, { "code": null, "e": 32481, "s": 32474, "text": "Greedy" }, { "code": null, "e": 32494, "s": 32481, "text": "Mathematical" }, { "code": null, "e": 32501, "s": 32494, "text": "Arrays" }, { "code": null, "e": 32508, "s": 32501, "text": "Greedy" }, { "code": null, "e": 32521, "s": 32508, "text": "Mathematical" }, { "code": null, "e": 32619, "s": 32521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32628, "s": 32619, "text": "Comments" }, { "code": null, "e": 32641, "s": 32628, "text": "Old Comments" }, { "code": null, "e": 32662, "s": 32641, "text": "Next Greater Element" }, { "code": null, "e": 32687, "s": 32662, "text": "Window Sliding Technique" }, { "code": null, "e": 32714, "s": 32687, "text": "Count pairs with given sum" }, { "code": null, "e": 32763, "s": 32714, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32801, "s": 32763, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32852, "s": 32801, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 32903, "s": 32852, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 32961, "s": 32903, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 32992, "s": 32961, "text": "Huffman Coding | Greedy Algo-3" } ]
Minimum operations required to make two numbers equal - GeeksforGeeks
24 Nov, 2021 Given two integers A and B. the task is to find the minimum number of operations required to make A and B equal. In each operation, either of the below steps can be performed: Increment either A or B with its initial value. Increment both A and B with their initial value Examples: Input: A = 4, B = 10 Output: 4 Explanation: Initially A = 4, B = 10 Operation 1: Increment A only: A = A + 4 = 8 Operation 2: Increment A only: A = A + 4 = 12 Operation 3: Increment A only: A = A + 4 = 16 Operation 4: Increment A and B: A = A + 4 = 20 and B = B + 10 = 20 They are equal now.Input: A = 7, B = 23 Output: 22 Explanation: Initially A = 7, B = 23 Operation 1 – 7: Increment A and B: A = 56 and B = 161 Operation 8 – 22: Increment A: A = 161 and B = 161 They are equal now. Approach: This problem can be solved using GCD. If A is greater than B, then swap A and B.Now reduce B, such that gcd of A and B becomes 1.Hence the minimum operations required to reach equal value is (B – 1). If A is greater than B, then swap A and B. Now reduce B, such that gcd of A and B becomes 1. Hence the minimum operations required to reach equal value is (B – 1). For example: If A = 4, B = 10: Step 1: Compare 4 and 10, as we always need B as the greater value. Here already B is greater than A. So, now no swap is required. Step 2: GCD(4, 10) = 2. So, we reduce B to B/2. Now A = 4 and B = 5. GCD(4, 5) = 1, which was the target. Step 3: (Current value of B – 1) will be the required count. Here, Current B = 5. So (5 – 1 = 4), i.e. total 4 operations are required. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to find minimum// operations required to// make two numbers equal #include <bits/stdc++.h>using namespace std; // Function to return the// minimum operations requiredlong long int minOperations( long long int A, long long int B){ // Keeping B always greater if (A > B) swap(A, B); // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1;} // Driver codeint main(){ long long int A = 7, B = 15; cout << minOperations(A, B) << endl; return 0;} // Java program to find minimum// operations required to// make two numbers equalclass GFG{ // Function to return the// minimum operations requiredstatic int minOperations( int A, int B){ // Keeping B always greater if (A > B) { A = A+B; B = A-B; A = A-B; } // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1;}static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void main(String[] args){ int A = 7, B = 15; System.out.print(minOperations(A, B) +"\n"); }} // This code contributed by sapnasingh4991 # Python program to find minimum# operations required to# make two numbers equalimport math # Function to return the# minimum operations requireddef minOperations(A, B): # Keeping B always greater if (A > B): swap(A, B) # Reduce B such that # gcd(A, B) becomes 1. B = B // math.gcd(A, B); return B - 1 # Driver codeA = 7B = 15 print(minOperations(A, B)) # This code is contributed by Sanjit_Prasad // C# program to find minimum// operations required to// make two numbers equalusing System; class GFG{ // Function to return the// minimum operations requiredstatic int minOperations( int A, int B){ // Keeping B always greater if (A > B) { A = A+B; B = A-B; A = A-B; } // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1;}static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void Main(String[] args){ int A = 7, B = 15; Console.Write(minOperations(A, B) +"\n");}} // This code is contributed by sapnasingh4991 <script>// javascript program to find minimum// operations required to// make two numbers equal // Function to return the // minimum operations required function minOperations(A, B){ // Keeping B always greater if (A > B) { A = A + B; B = A - B; A = A - B; } // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code var A = 7, B = 15; document.write(minOperations(A, B) + "\n"); // This code is contributed by Rajput-Ji</script> 14 Time Complexity: O(log(max(A, B)) Auxiliary Space: O(log(max(A, B)) Sanjit_Prasad sapnasingh4991 Rajput-Ji subham348 GCD-LCM Numbers Mathematical Mathematical Numbers 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 Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 26057, "s": 26029, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26235, "s": 26057, "text": "Given two integers A and B. the task is to find the minimum number of operations required to make A and B equal. In each operation, either of the below steps can be performed: " }, { "code": null, "e": 26283, "s": 26235, "text": "Increment either A or B with its initial value." }, { "code": null, "e": 26331, "s": 26283, "text": "Increment both A and B with their initial value" }, { "code": null, "e": 26343, "s": 26331, "text": "Examples: " }, { "code": null, "e": 26831, "s": 26343, "text": "Input: A = 4, B = 10 Output: 4 Explanation: Initially A = 4, B = 10 Operation 1: Increment A only: A = A + 4 = 8 Operation 2: Increment A only: A = A + 4 = 12 Operation 3: Increment A only: A = A + 4 = 16 Operation 4: Increment A and B: A = A + 4 = 20 and B = B + 10 = 20 They are equal now.Input: A = 7, B = 23 Output: 22 Explanation: Initially A = 7, B = 23 Operation 1 – 7: Increment A and B: A = 56 and B = 161 Operation 8 – 22: Increment A: A = 161 and B = 161 They are equal now. " }, { "code": null, "e": 26883, "s": 26833, "text": "Approach: This problem can be solved using GCD. " }, { "code": null, "e": 27045, "s": 26883, "text": "If A is greater than B, then swap A and B.Now reduce B, such that gcd of A and B becomes 1.Hence the minimum operations required to reach equal value is (B – 1)." }, { "code": null, "e": 27088, "s": 27045, "text": "If A is greater than B, then swap A and B." }, { "code": null, "e": 27138, "s": 27088, "text": "Now reduce B, such that gcd of A and B becomes 1." }, { "code": null, "e": 27209, "s": 27138, "text": "Hence the minimum operations required to reach equal value is (B – 1)." }, { "code": null, "e": 27242, "s": 27209, "text": "For example: If A = 4, B = 10: " }, { "code": null, "e": 27373, "s": 27242, "text": "Step 1: Compare 4 and 10, as we always need B as the greater value. Here already B is greater than A. So, now no swap is required." }, { "code": null, "e": 27479, "s": 27373, "text": "Step 2: GCD(4, 10) = 2. So, we reduce B to B/2. Now A = 4 and B = 5. GCD(4, 5) = 1, which was the target." }, { "code": null, "e": 27615, "s": 27479, "text": "Step 3: (Current value of B – 1) will be the required count. Here, Current B = 5. So (5 – 1 = 4), i.e. total 4 operations are required." }, { "code": null, "e": 27668, "s": 27615, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 27672, "s": 27668, "text": "C++" }, { "code": null, "e": 27677, "s": 27672, "text": "Java" }, { "code": null, "e": 27685, "s": 27677, "text": "Python3" }, { "code": null, "e": 27688, "s": 27685, "text": "C#" }, { "code": null, "e": 27699, "s": 27688, "text": "Javascript" }, { "code": "// C++ program to find minimum// operations required to// make two numbers equal #include <bits/stdc++.h>using namespace std; // Function to return the// minimum operations requiredlong long int minOperations( long long int A, long long int B){ // Keeping B always greater if (A > B) swap(A, B); // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1;} // Driver codeint main(){ long long int A = 7, B = 15; cout << minOperations(A, B) << endl; return 0;}", "e": 28233, "s": 27699, "text": null }, { "code": "// Java program to find minimum// operations required to// make two numbers equalclass GFG{ // Function to return the// minimum operations requiredstatic int minOperations( int A, int B){ // Keeping B always greater if (A > B) { A = A+B; B = A-B; A = A-B; } // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1;}static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void main(String[] args){ int A = 7, B = 15; System.out.print(minOperations(A, B) +\"\\n\"); }} // This code contributed by sapnasingh4991", "e": 28888, "s": 28233, "text": null }, { "code": "# Python program to find minimum# operations required to# make two numbers equalimport math # Function to return the# minimum operations requireddef minOperations(A, B): # Keeping B always greater if (A > B): swap(A, B) # Reduce B such that # gcd(A, B) becomes 1. B = B // math.gcd(A, B); return B - 1 # Driver codeA = 7B = 15 print(minOperations(A, B)) # This code is contributed by Sanjit_Prasad", "e": 29314, "s": 28888, "text": null }, { "code": "// C# program to find minimum// operations required to// make two numbers equalusing System; class GFG{ // Function to return the// minimum operations requiredstatic int minOperations( int A, int B){ // Keeping B always greater if (A > B) { A = A+B; B = A-B; A = A-B; } // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1;}static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); } // Driver codepublic static void Main(String[] args){ int A = 7, B = 15; Console.Write(minOperations(A, B) +\"\\n\");}} // This code is contributed by sapnasingh4991", "e": 29985, "s": 29314, "text": null }, { "code": "<script>// javascript program to find minimum// operations required to// make two numbers equal // Function to return the // minimum operations required function minOperations(A, B){ // Keeping B always greater if (A > B) { A = A + B; B = A - B; A = A - B; } // Reduce B such that // gcd(A, B) becomes 1. B = B / __gcd(A, B); return B - 1; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code var A = 7, B = 15; document.write(minOperations(A, B) + \"\\n\"); // This code is contributed by Rajput-Ji</script>", "e": 30646, "s": 29985, "text": null }, { "code": null, "e": 30649, "s": 30646, "text": "14" }, { "code": null, "e": 30685, "s": 30651, "text": "Time Complexity: O(log(max(A, B))" }, { "code": null, "e": 30720, "s": 30685, "text": "Auxiliary Space: O(log(max(A, B)) " }, { "code": null, "e": 30734, "s": 30720, "text": "Sanjit_Prasad" }, { "code": null, "e": 30749, "s": 30734, "text": "sapnasingh4991" }, { "code": null, "e": 30759, "s": 30749, "text": "Rajput-Ji" }, { "code": null, "e": 30769, "s": 30759, "text": "subham348" }, { "code": null, "e": 30777, "s": 30769, "text": "GCD-LCM" }, { "code": null, "e": 30785, "s": 30777, "text": "Numbers" }, { "code": null, "e": 30798, "s": 30785, "text": "Mathematical" }, { "code": null, "e": 30811, "s": 30798, "text": "Mathematical" }, { "code": null, "e": 30819, "s": 30811, "text": "Numbers" }, { "code": null, "e": 30917, "s": 30819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30941, "s": 30917, "text": "Merge two sorted arrays" }, { "code": null, "e": 30984, "s": 30941, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30998, "s": 30984, "text": "Prime Numbers" }, { "code": null, "e": 31071, "s": 30998, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31112, "s": 31071, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 31155, "s": 31112, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31176, "s": 31155, "text": "Operators in C / C++" }, { "code": null, "e": 31210, "s": 31176, "text": "Program for factorial of a number" }, { "code": null, "e": 31263, "s": 31210, "text": "Find minimum number of coins that make a given value" } ]
How to Iterate HashMap in Java? - GeeksforGeeks
16 Oct, 2021 HashMap is a part of Java’s collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. In order to use this class and its methods, it is necessary to import java.util.HashMap package or its superclass. There is a numerous number of ways to iterate over HashMap of which 5 are listed as below: Iterate through a HashMap EntrySet using Iterators.Iterate through HashMap KeySet using Iterator.Iterate HashMap using for-each loop.Iterating through a HashMap using Lambda Expressions.Loop through a HashMap using Stream API. Iterate through a HashMap EntrySet using Iterators. Iterate through HashMap KeySet using Iterator. Iterate HashMap using for-each loop. Iterating through a HashMap using Lambda Expressions. Loop through a HashMap using Stream API. Method 1: Using a for loop to iterate through a HashMap. Iterating a HashMap through a for loop to use getValue() and getKey() functions. Implementation: In the code given below, entrySet() is used to return a set view of mapped elements. From the code given below: set.getValue() to get value from the set. set.getKey() to get key from the set. Java // Java Program to Iterate over HashMap // Importing Map and HashMap classes// from package names java.utilimport java.util.HashMap;import java.util.Map; // Class for iterating HashMap using for looppublic class GFG { // Main driver method public static void main(String[] args) { // Creating a HashMap Map<String, String> foodTable = new HashMap<String, String>(); // Inserting elements to the adobe HashMap // Elements- Key value pairs using put() method foodTable.put("A", "Angular"); foodTable.put("J", "Java"); foodTable.put("P", "Python"); foodTable.put("H", "Hibernate"); // Iterating HashMap through for loop for (Map.Entry<String, String> set : foodTable.entrySet()) { // Printing all elements of a Map System.out.println(set.getKey() + " = " + set.getValue()); } }} P = Python A = Angular H = Hibernate J = Java Method 2: Using a forEach to iterate through a HashMap. In the second method, the forEach function to iterate the key-value pairs. Java // Java Program to Iterate over HashMap// Iterating HashMap using forEach // Importing Map and HashMap classes// from package names java.utilimport java.util.HashMap;import java.util.Map; public class GFG { // Main driver method public static void main(String[] args) { // Creating hash map Map<Character, String> charType = new HashMap<Character, String>(); // Inserting data in the hash map. charType.put('J', "Java"); charType.put('H', "Hibernate"); charType.put('P', "Python"); charType.put('A', "Angular"); // Iterating HashMap through forEach and // Printing all. elements in a Map charType.forEach( (key, value) -> System.out.println(key + " = " + value)); }} P = Python A = Angular H = Hibernate J = Java Method 3: Using an iterator to iterate through a HashMap. In this method, iterator is being used to iterate each mapped pair in HashMap as shown in below java program. Example: Java // Java Program to Iterate over HashMap// Using Iterator // Importing classes from java.util packageimport java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry; public class GFG { // Main driver method public static void main(String[] arguments) { // Creating Hash map Map<Integer, String> intType = new HashMap<Integer, String>(); // Inserting data(Key-value pairs) in hashmap intType.put(1, "First"); intType.put(2, "Second"); intType.put(3, "Third"); intType.put(4, "Fourth"); // Iterator Iterator<Entry<Integer, String> > new_Iterator = intType.entrySet().iterator(); // Iterating every set of entry in the HashMap while (new_Iterator.hasNext()) { Map.Entry<Integer, String> new_Map = (Map.Entry<Integer, String>) new_Iterator.next(); // Displaying HashMap System.out.println(new_Map.getKey() + " = " + new_Map.getValue()); } }} 1 = First 2 = Second 3 = Third 4 = Fourth Method 4: Iterating through a HashMap using Lambda Expressions A lambda expression is a short block of code that takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name, and they can be implemented right in the body of a method. The simplest lambda expression contains a single parameter and an expression: parameter -> expression Example: Java // Iterating HashMap using Lambda Expressions- forEach()// Importing Map and HashMap classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating hash map Map<Character, String> charType = new HashMap<Character, String>(); // Inserting elements(key-value pairs) // in the hash map ( Custom inputs) charType.put('A', "Apple"); charType.put('B', "Basketball"); charType.put('C', "Cat"); charType.put('D', "Dog"); // Iterating through forEach and // printing the elements charType.forEach( (key, value) -> System.out.println(key + " = " + value)); }} A = Apple B = Basketball C = Cat D = Dog Method 5: Loop through a HashMap using Stream API The below example iterates over a HashMap with the help of the stream API. Stream API is used to process collections of objects. Streams don’t change the original data structure, they only provide the result as per the pipelined methods Steps : First invoke entrySet().stream() method which inturn returns Stream object. Next forEach method, which iterates the input objects that are in the entrySet(). See the below code. Example: Java // Java Program to Iterate over HashMap// Loop through a HashMap using Stream API // Importing classes from// package named 'java.util'import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry; // HashMap classpublic class GFG { // Main driver method public static void main(String[] arguments) { // Creating hash map Map<Integer, String> intType = new HashMap<Integer, String>(); // Inserting data(key-value pairs) in HashMap // Custom inputs intType.put(1, "First"); intType.put(2, "Second"); intType.put(3, "Third"); intType.put(4, "Fourth"); // Iterating every set of entry in the HashMap, and // printing all elements of it intType.entrySet().stream().forEach( input -> System.out.println(input.getKey() + " : " + input.getValue())); }} 1 : First 2 : Second 3 : Third 4 : Fourth adnanirshad158 varshagumber28 abhishek0719kadiyan ruhelaa48 Java-HashMap Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Program to print ASCII Value of a character Iterate through List in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n16 Oct, 2021" }, { "code": null, "e": 25712, "s": 25249, "text": "HashMap is a part of Java’s collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. In order to use this class and its methods, it is necessary to import java.util.HashMap package or its superclass." }, { "code": null, "e": 25804, "s": 25712, "text": "There is a numerous number of ways to iterate over HashMap of which 5 are listed as below: " }, { "code": null, "e": 26031, "s": 25804, "text": "Iterate through a HashMap EntrySet using Iterators.Iterate through HashMap KeySet using Iterator.Iterate HashMap using for-each loop.Iterating through a HashMap using Lambda Expressions.Loop through a HashMap using Stream API." }, { "code": null, "e": 26083, "s": 26031, "text": "Iterate through a HashMap EntrySet using Iterators." }, { "code": null, "e": 26130, "s": 26083, "text": "Iterate through HashMap KeySet using Iterator." }, { "code": null, "e": 26167, "s": 26130, "text": "Iterate HashMap using for-each loop." }, { "code": null, "e": 26221, "s": 26167, "text": "Iterating through a HashMap using Lambda Expressions." }, { "code": null, "e": 26262, "s": 26221, "text": "Loop through a HashMap using Stream API." }, { "code": null, "e": 26400, "s": 26262, "text": "Method 1: Using a for loop to iterate through a HashMap. Iterating a HashMap through a for loop to use getValue() and getKey() functions." }, { "code": null, "e": 26528, "s": 26400, "text": "Implementation: In the code given below, entrySet() is used to return a set view of mapped elements. From the code given below:" }, { "code": null, "e": 26570, "s": 26528, "text": "set.getValue() to get value from the set." }, { "code": null, "e": 26608, "s": 26570, "text": "set.getKey() to get key from the set." }, { "code": null, "e": 26613, "s": 26608, "text": "Java" }, { "code": "// Java Program to Iterate over HashMap // Importing Map and HashMap classes// from package names java.utilimport java.util.HashMap;import java.util.Map; // Class for iterating HashMap using for looppublic class GFG { // Main driver method public static void main(String[] args) { // Creating a HashMap Map<String, String> foodTable = new HashMap<String, String>(); // Inserting elements to the adobe HashMap // Elements- Key value pairs using put() method foodTable.put(\"A\", \"Angular\"); foodTable.put(\"J\", \"Java\"); foodTable.put(\"P\", \"Python\"); foodTable.put(\"H\", \"Hibernate\"); // Iterating HashMap through for loop for (Map.Entry<String, String> set : foodTable.entrySet()) { // Printing all elements of a Map System.out.println(set.getKey() + \" = \" + set.getValue()); } }}", "e": 27557, "s": 26613, "text": null }, { "code": null, "e": 27603, "s": 27557, "text": "P = Python\nA = Angular\nH = Hibernate\nJ = Java" }, { "code": null, "e": 27734, "s": 27603, "text": "Method 2: Using a forEach to iterate through a HashMap. In the second method, the forEach function to iterate the key-value pairs." }, { "code": null, "e": 27739, "s": 27734, "text": "Java" }, { "code": "// Java Program to Iterate over HashMap// Iterating HashMap using forEach // Importing Map and HashMap classes// from package names java.utilimport java.util.HashMap;import java.util.Map; public class GFG { // Main driver method public static void main(String[] args) { // Creating hash map Map<Character, String> charType = new HashMap<Character, String>(); // Inserting data in the hash map. charType.put('J', \"Java\"); charType.put('H', \"Hibernate\"); charType.put('P', \"Python\"); charType.put('A', \"Angular\"); // Iterating HashMap through forEach and // Printing all. elements in a Map charType.forEach( (key, value) -> System.out.println(key + \" = \" + value)); }}", "e": 28528, "s": 27739, "text": null }, { "code": null, "e": 28574, "s": 28528, "text": "P = Python\nA = Angular\nH = Hibernate\nJ = Java" }, { "code": null, "e": 28742, "s": 28574, "text": "Method 3: Using an iterator to iterate through a HashMap. In this method, iterator is being used to iterate each mapped pair in HashMap as shown in below java program." }, { "code": null, "e": 28751, "s": 28742, "text": "Example:" }, { "code": null, "e": 28756, "s": 28751, "text": "Java" }, { "code": "// Java Program to Iterate over HashMap// Using Iterator // Importing classes from java.util packageimport java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry; public class GFG { // Main driver method public static void main(String[] arguments) { // Creating Hash map Map<Integer, String> intType = new HashMap<Integer, String>(); // Inserting data(Key-value pairs) in hashmap intType.put(1, \"First\"); intType.put(2, \"Second\"); intType.put(3, \"Third\"); intType.put(4, \"Fourth\"); // Iterator Iterator<Entry<Integer, String> > new_Iterator = intType.entrySet().iterator(); // Iterating every set of entry in the HashMap while (new_Iterator.hasNext()) { Map.Entry<Integer, String> new_Map = (Map.Entry<Integer, String>) new_Iterator.next(); // Displaying HashMap System.out.println(new_Map.getKey() + \" = \" + new_Map.getValue()); } }}", "e": 29850, "s": 28756, "text": null }, { "code": null, "e": 29895, "s": 29853, "text": "1 = First\n2 = Second\n3 = Third\n4 = Fourth" }, { "code": null, "e": 29959, "s": 29895, "text": " Method 4: Iterating through a HashMap using Lambda Expressions" }, { "code": null, "e": 30260, "s": 29959, "text": "A lambda expression is a short block of code that takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name, and they can be implemented right in the body of a method. The simplest lambda expression contains a single parameter and an expression:" }, { "code": null, "e": 30284, "s": 30260, "text": "parameter -> expression" }, { "code": null, "e": 30294, "s": 30284, "text": "Example: " }, { "code": null, "e": 30299, "s": 30294, "text": "Java" }, { "code": "// Iterating HashMap using Lambda Expressions- forEach()// Importing Map and HashMap classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating hash map Map<Character, String> charType = new HashMap<Character, String>(); // Inserting elements(key-value pairs) // in the hash map ( Custom inputs) charType.put('A', \"Apple\"); charType.put('B', \"Basketball\"); charType.put('C', \"Cat\"); charType.put('D', \"Dog\"); // Iterating through forEach and // printing the elements charType.forEach( (key, value) -> System.out.println(key + \" = \" + value)); }}", "e": 31096, "s": 30299, "text": null }, { "code": null, "e": 31137, "s": 31096, "text": "A = Apple\nB = Basketball\nC = Cat\nD = Dog" }, { "code": null, "e": 31187, "s": 31137, "text": "Method 5: Loop through a HashMap using Stream API" }, { "code": null, "e": 31263, "s": 31187, "text": "The below example iterates over a HashMap with the help of the stream API. " }, { "code": null, "e": 31317, "s": 31263, "text": "Stream API is used to process collections of objects." }, { "code": null, "e": 31425, "s": 31317, "text": "Streams don’t change the original data structure, they only provide the result as per the pipelined methods" }, { "code": null, "e": 31434, "s": 31425, "text": " Steps :" }, { "code": null, "e": 31510, "s": 31434, "text": "First invoke entrySet().stream() method which inturn returns Stream object." }, { "code": null, "e": 31612, "s": 31510, "text": "Next forEach method, which iterates the input objects that are in the entrySet(). See the below code." }, { "code": null, "e": 31621, "s": 31612, "text": "Example:" }, { "code": null, "e": 31626, "s": 31621, "text": "Java" }, { "code": "// Java Program to Iterate over HashMap// Loop through a HashMap using Stream API // Importing classes from// package named 'java.util'import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry; // HashMap classpublic class GFG { // Main driver method public static void main(String[] arguments) { // Creating hash map Map<Integer, String> intType = new HashMap<Integer, String>(); // Inserting data(key-value pairs) in HashMap // Custom inputs intType.put(1, \"First\"); intType.put(2, \"Second\"); intType.put(3, \"Third\"); intType.put(4, \"Fourth\"); // Iterating every set of entry in the HashMap, and // printing all elements of it intType.entrySet().stream().forEach( input -> System.out.println(input.getKey() + \" : \" + input.getValue())); }}", "e": 32567, "s": 31626, "text": null }, { "code": null, "e": 32609, "s": 32567, "text": "1 : First\n2 : Second\n3 : Third\n4 : Fourth" }, { "code": null, "e": 32626, "s": 32611, "text": "adnanirshad158" }, { "code": null, "e": 32641, "s": 32626, "text": "varshagumber28" }, { "code": null, "e": 32661, "s": 32641, "text": "abhishek0719kadiyan" }, { "code": null, "e": 32671, "s": 32661, "text": "ruhelaa48" }, { "code": null, "e": 32684, "s": 32671, "text": "Java-HashMap" }, { "code": null, "e": 32691, "s": 32684, "text": "Picked" }, { "code": null, "e": 32696, "s": 32691, "text": "Java" }, { "code": null, "e": 32710, "s": 32696, "text": "Java Programs" }, { "code": null, "e": 32715, "s": 32710, "text": "Java" }, { "code": null, "e": 32813, "s": 32715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32828, "s": 32813, "text": "Stream In Java" }, { "code": null, "e": 32849, "s": 32828, "text": "Constructors in Java" }, { "code": null, "e": 32868, "s": 32849, "text": "Exceptions in Java" }, { "code": null, "e": 32898, "s": 32868, "text": "Functional Interfaces in Java" }, { "code": null, "e": 32944, "s": 32898, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 32970, "s": 32944, "text": "Java Programming Examples" }, { "code": null, "e": 33004, "s": 32970, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 33051, "s": 33004, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 33095, "s": 33051, "text": "Program to print ASCII Value of a character" } ]
Check if a large number is divisible by 25 or not - GeeksforGeeks
15 Apr, 2021 Given a number, the task is to check if number is divisible by 25. The input number may be large and it may not be possible to store even if we use long long int. Examples: Input : n = 56945250 Output : Yes Input : n = 1234567589333100 Output : Yes Input : n = 3635883959606670431112222 Output : No Since input number may be very large, we cannot use n % 25 to check if a number is divisible by 25 or not, especially in languages like C/C++. The idea is based on following fact. A number is divisible by 25 if its digits last two digits will be 0 or divisible by 25 . Illustration: For example, let us consider 769575 Number formed by last two digits is = 75 Since 75 is divisible by 25 , answer is YES. Let us consider 5325, we can write it as 5325 = 5*1000 + 3*100 + 2*10 + 5 The proof is based on below observation: Remainder of 10i divided by 25 is 0 if i greater than or equal to two. Note than 100, 1000, ... etc lead to remainder 0 when divided by 25. So remainder of " 5*1000 + 3*100 + 2*10 + 5" divided by 25 is equivalent to remainder of following : 0 + 0 + 20 + 5 = 25 Since 25 is divisible by 25, answer is yes. C++ Java Python3 C# PHP Javascript // C++ program to find if a number is// divisible by 25 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible// by 25 or not.bool isDivisibleBy25(string str){ // If length of string is single digit then // it's not divisible by 25 int n = str.length(); if (n == 1) return false; return ( (str[n-1]-'0' == 0 && str[n-2]-'0' == 0) || ((str[n-2]-'0')*10 + (str[n-1]-'0'))%25 == 0 );} // Driver codeint main(){ string str = "76955"; isDivisibleBy25(str)? cout << "Yes" : cout << "No "; return 0;} // Java program to find if a number is// divisible by 25 or notclass IsDivisible{ // Function to find that number divisible // by 25 or not. static boolean isDivisibleBy25(String str) { // If length of string is single digit then // it's not divisible by 25 int n = str.length(); if (n == 1) return false; return ( (str.charAt(n-1)-'0' == 0 && str.charAt(n-2)-'0' == 0) || ((str.charAt(n-2)-'0')*10 + (str.charAt(n-1)-'0'))%25 == 0 ); } // main function public static void main (String[] args) { String str = "76955"; if(isDivisibleBy25(str)) System.out.println("Yes"); else System.out.println("No"); }} # Python 3 program to find if# a number is divisible by 25# or not # Function to find that# number divisible by 25 or not.def isDivisibleBy25(st) : # If length of string is # single digit then it's # not divisible by 25 n = len(st) if (n == 1) : return False return ((int)(st[n-1]) == 0 and ((int)(st[n-2])== 0) or ((int)(st[n-2])*10 + (int)(st[n-1])%25 == 0)) # Driver codest = "76955"if(isDivisibleBy25(st)) : print("Yes")else : print("No") # This code is contributed by Nikita Tiwari. // C# program to find if a number// is divisible by 25 or notusing System; class IsDivisible{ // Function to find that number // divisible by 25 or not. static bool isDivisibleBy25(String str) { // If length of string is single digit then // then it's not divisible by 25 int n = str.Length; if (n == 1) return false; return ((str[n - 1] - '0' == 0 && str[n - 2] - '0' == 0) || ((str[n - 2] - '0') * 10 + (str[n - 1] - '0')) % 25 == 0); } // Driver Code public static void Main () { String str = "76955"; if(isDivisibleBy25(str)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by Nitin Mittal <?php// PHP program to find if a number// is divisible by 25 or not // Function to find that number// divisible by 25 or not.function isDivisibleBy25($str){ // If length of string // is single digit then // it's not divisible by 25 $n = strlen($str); if ($n == 1) return false; return ( ($str[$n - 1] -'0' == 0 && $str[$n - 2] -'0' == 0) || (($str[$n - 2] -'0') * 10 + ($str[$n - 1] - '0')) % 25 == 0 );} // Driver code$str = "76955";$x = isDivisibleBy25($str) ? "Yes" : "No ";echo($x); // This code is contributed by Ajit.?> <script> // Javascript program to find if a number// is divisible by 25 or not // Function to find that number// divisible by 25 or notfunction isDivisibleBy25(str){ // If length of string // is single digit then // it's not divisible by 25 n = str.length; if (n == 1) return false; return ((str[n - 1] -'0' == 0 && str[n - 2] -'0' == 0) || ((str[n - 2] -'0') * 10 + (str[n - 1] - '0')) % 25 == 0);} // Driver Codevar str = "76955";var x = isDivisibleBy25(str) ? "Yes" : "No"; document.write (x); // This code is contributed by bunnyram19 </script> Output: No This article is contributed by DANISH_RAZA . 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. nitin mittal jit_t Akanksha_Rai bunnyram19 divisibility large-numbers Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25962, "s": 25934, "text": "\n15 Apr, 2021" }, { "code": null, "e": 26125, "s": 25962, "text": "Given a number, the task is to check if number is divisible by 25. The input number may be large and it may not be possible to store even if we use long long int." }, { "code": null, "e": 26136, "s": 26125, "text": "Examples: " }, { "code": null, "e": 26267, "s": 26136, "text": "Input : n = 56945250\nOutput : Yes\n\nInput : n = 1234567589333100\nOutput : Yes\n\nInput : n = 3635883959606670431112222\nOutput : No" }, { "code": null, "e": 26447, "s": 26267, "text": "Since input number may be very large, we cannot use n % 25 to check if a number is divisible by 25 or not, especially in languages like C/C++. The idea is based on following fact." }, { "code": null, "e": 26538, "s": 26447, "text": "A number is divisible by 25 if its digits \nlast two digits will be 0 or divisible by 25 ." }, { "code": null, "e": 26553, "s": 26538, "text": "Illustration: " }, { "code": null, "e": 26676, "s": 26553, "text": "For example, let us consider 769575 \nNumber formed by last two digits is = 75\nSince 75 is divisible by 25 , answer is YES." }, { "code": null, "e": 27103, "s": 26676, "text": "Let us consider 5325, we can write it as\n5325 = 5*1000 + 3*100 + 2*10 + 5\n\nThe proof is based on below observation:\nRemainder of 10i divided by 25 is 0 if i greater \nthan or equal to two. Note than 100, 1000,\n... etc lead to remainder 0 when divided by 25.\n\nSo remainder of \" 5*1000 + 3*100 + 2*10 + 5\" \ndivided by 25 is equivalent to remainder \nof following : \n0 + 0 + 20 + 5 = 25\n\nSince 25 is divisible by 25, answer is yes." }, { "code": null, "e": 27107, "s": 27103, "text": "C++" }, { "code": null, "e": 27112, "s": 27107, "text": "Java" }, { "code": null, "e": 27120, "s": 27112, "text": "Python3" }, { "code": null, "e": 27123, "s": 27120, "text": "C#" }, { "code": null, "e": 27127, "s": 27123, "text": "PHP" }, { "code": null, "e": 27138, "s": 27127, "text": "Javascript" }, { "code": "// C++ program to find if a number is// divisible by 25 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible// by 25 or not.bool isDivisibleBy25(string str){ // If length of string is single digit then // it's not divisible by 25 int n = str.length(); if (n == 1) return false; return ( (str[n-1]-'0' == 0 && str[n-2]-'0' == 0) || ((str[n-2]-'0')*10 + (str[n-1]-'0'))%25 == 0 );} // Driver codeint main(){ string str = \"76955\"; isDivisibleBy25(str)? cout << \"Yes\" : cout << \"No \"; return 0;}", "e": 27744, "s": 27138, "text": null }, { "code": "// Java program to find if a number is// divisible by 25 or notclass IsDivisible{ // Function to find that number divisible // by 25 or not. static boolean isDivisibleBy25(String str) { // If length of string is single digit then // it's not divisible by 25 int n = str.length(); if (n == 1) return false; return ( (str.charAt(n-1)-'0' == 0 && str.charAt(n-2)-'0' == 0) || ((str.charAt(n-2)-'0')*10 + (str.charAt(n-1)-'0'))%25 == 0 ); } // main function public static void main (String[] args) { String str = \"76955\"; if(isDivisibleBy25(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 28500, "s": 27744, "text": null }, { "code": "# Python 3 program to find if# a number is divisible by 25# or not # Function to find that# number divisible by 25 or not.def isDivisibleBy25(st) : # If length of string is # single digit then it's # not divisible by 25 n = len(st) if (n == 1) : return False return ((int)(st[n-1]) == 0 and ((int)(st[n-2])== 0) or ((int)(st[n-2])*10 + (int)(st[n-1])%25 == 0)) # Driver codest = \"76955\"if(isDivisibleBy25(st)) : print(\"Yes\")else : print(\"No\") # This code is contributed by Nikita Tiwari.", "e": 29036, "s": 28500, "text": null }, { "code": "// C# program to find if a number// is divisible by 25 or notusing System; class IsDivisible{ // Function to find that number // divisible by 25 or not. static bool isDivisibleBy25(String str) { // If length of string is single digit then // then it's not divisible by 25 int n = str.Length; if (n == 1) return false; return ((str[n - 1] - '0' == 0 && str[n - 2] - '0' == 0) || ((str[n - 2] - '0') * 10 + (str[n - 1] - '0')) % 25 == 0); } // Driver Code public static void Main () { String str = \"76955\"; if(isDivisibleBy25(str)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by Nitin Mittal", "e": 29834, "s": 29036, "text": null }, { "code": "<?php// PHP program to find if a number// is divisible by 25 or not // Function to find that number// divisible by 25 or not.function isDivisibleBy25($str){ // If length of string // is single digit then // it's not divisible by 25 $n = strlen($str); if ($n == 1) return false; return ( ($str[$n - 1] -'0' == 0 && $str[$n - 2] -'0' == 0) || (($str[$n - 2] -'0') * 10 + ($str[$n - 1] - '0')) % 25 == 0 );} // Driver code$str = \"76955\";$x = isDivisibleBy25($str) ? \"Yes\" : \"No \";echo($x); // This code is contributed by Ajit.?>", "e": 30428, "s": 29834, "text": null }, { "code": "<script> // Javascript program to find if a number// is divisible by 25 or not // Function to find that number// divisible by 25 or notfunction isDivisibleBy25(str){ // If length of string // is single digit then // it's not divisible by 25 n = str.length; if (n == 1) return false; return ((str[n - 1] -'0' == 0 && str[n - 2] -'0' == 0) || ((str[n - 2] -'0') * 10 + (str[n - 1] - '0')) % 25 == 0);} // Driver Codevar str = \"76955\";var x = isDivisibleBy25(str) ? \"Yes\" : \"No\"; document.write (x); // This code is contributed by bunnyram19 </script>", "e": 31052, "s": 30428, "text": null }, { "code": null, "e": 31061, "s": 31052, "text": "Output: " }, { "code": null, "e": 31064, "s": 31061, "text": "No" }, { "code": null, "e": 31489, "s": 31064, "text": "This article is contributed by DANISH_RAZA . 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. " }, { "code": null, "e": 31502, "s": 31489, "text": "nitin mittal" }, { "code": null, "e": 31508, "s": 31502, "text": "jit_t" }, { "code": null, "e": 31521, "s": 31508, "text": "Akanksha_Rai" }, { "code": null, "e": 31532, "s": 31521, "text": "bunnyram19" }, { "code": null, "e": 31545, "s": 31532, "text": "divisibility" }, { "code": null, "e": 31559, "s": 31545, "text": "large-numbers" }, { "code": null, "e": 31572, "s": 31559, "text": "Mathematical" }, { "code": null, "e": 31585, "s": 31572, "text": "Mathematical" }, { "code": null, "e": 31683, "s": 31585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31727, "s": 31683, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 31769, "s": 31727, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 31800, "s": 31769, "text": "Modular multiplicative inverse" }, { "code": null, "e": 31871, "s": 31800, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 31896, "s": 31871, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 31928, "s": 31896, "text": "Check if a number is Palindrome" }, { "code": null, "e": 31961, "s": 31928, "text": "Program to multiply two matrices" }, { "code": null, "e": 32007, "s": 31961, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 32051, "s": 32007, "text": "Generate all permutation of a set in Python" } ]
Matplotlib.axes.Axes.boxplot() in Python - GeeksforGeeks
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.boxplot() function in axes module of matplotlib library is used to make a box and whisker plot for each column of x or each vector in sequence x. Syntax: Axes.boxplot(self, x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, *, data=None) Parameters: This method accept the following parameters that are described below: x: This parameter is a sequence of data. notch: This parameter will produce a notched box plot if true. Otherwise, a rectangular boxplot is produced. sym : This parameter is an optional parameter and contain string value. It is a default symbol for flier points. vert: This parameter is an optional parameter and contain boolean value. It makes the boxes vertical if true.Otherwise horizontal. whis : This parameter determines the reach of the whiskers to the beyond the first and third quartiles. bootstrap : This parameter is also an optional parameter which contain boolean value and specifies whether to bootstrap the confidence intervals around the median for notched boxplots. usermedians : This parameter is an array or sequence whose first dimension is compatible with x. conf_intervals : This parameter is also an array or sequence whose first dimension is compatible with x and whose second dimension is 2 positions : This parameter is used to sets the positions of the boxes. widths: This parameter is used to sets the width of each box either with a scalar or a sequence. patch_artist : This parameter is used to produce boxes with the Line2D artist if it is false. Otherwise, boxes with Patch artists. labels : This parameter is the labels for each dataset. manage_ticks : This parameter is used to adjust the tick locations and labels. zorder : This parameter is used to sets the zorder of the boxplot. Returns: This returns the following: result :This returns the dictionary which maps each component of the boxplot to a list of the matplotlib.lines.Line2D. Below examples illustrate the matplotlib.axes.Axes.boxplot() function in matplotlib.axes: Example-1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7) val1 = np.random.rand(50) * 80val2 = np.ones(80) * 50val3 = np.random.rand(50) * 80 + 100val4 = np.random.rand(50) * -80data = np.concatenate((val1, val2, val3, val4)) fig1, ax1 = plt.subplots()ax1.boxplot(data) ax1.set_title('matplotlib.axes.Axes.boxplot() Example')plt.show() Output: Example-2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7) val1 = np.random.rand(50) * 80val2 = np.ones(25) * 80val3 = np.random.rand(25) * 80 + 100val4 = np.random.rand(25) * -80data = np.concatenate((val1, val2, val3, val4))data1 = np.concatenate((val2, val4, val1, val3))data = [data, data1] fig1, ax1 = plt.subplots()ax1.boxplot(data, notch = True, vert = False, whis = 0.75) ax1.set_title('matplotlib.axes.Axes.boxplot() Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n13 Apr, 2020" }, { "code": null, "e": 25833, "s": 25537, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 25988, "s": 25833, "text": "The Axes.boxplot() function in axes module of matplotlib library is used to make a box and whisker plot for each column of x or each vector in sequence x." }, { "code": null, "e": 26418, "s": 25988, "text": "Syntax: Axes.boxplot(self, x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, *, data=None)" }, { "code": null, "e": 26500, "s": 26418, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26541, "s": 26500, "text": "x: This parameter is a sequence of data." }, { "code": null, "e": 26650, "s": 26541, "text": "notch: This parameter will produce a notched box plot if true. Otherwise, a rectangular boxplot is produced." }, { "code": null, "e": 26763, "s": 26650, "text": "sym : This parameter is an optional parameter and contain string value. It is a default symbol for flier points." }, { "code": null, "e": 26894, "s": 26763, "text": "vert: This parameter is an optional parameter and contain boolean value. It makes the boxes vertical if true.Otherwise horizontal." }, { "code": null, "e": 26998, "s": 26894, "text": "whis : This parameter determines the reach of the whiskers to the beyond the first and third quartiles." }, { "code": null, "e": 27183, "s": 26998, "text": "bootstrap : This parameter is also an optional parameter which contain boolean value and specifies whether to bootstrap the confidence intervals around the median for notched boxplots." }, { "code": null, "e": 27280, "s": 27183, "text": "usermedians : This parameter is an array or sequence whose first dimension is compatible with x." }, { "code": null, "e": 27416, "s": 27280, "text": "conf_intervals : This parameter is also an array or sequence whose first dimension is compatible with x and whose second dimension is 2" }, { "code": null, "e": 27487, "s": 27416, "text": "positions : This parameter is used to sets the positions of the boxes." }, { "code": null, "e": 27584, "s": 27487, "text": "widths: This parameter is used to sets the width of each box either with a scalar or a sequence." }, { "code": null, "e": 27715, "s": 27584, "text": "patch_artist : This parameter is used to produce boxes with the Line2D artist if it is false. Otherwise, boxes with Patch artists." }, { "code": null, "e": 27771, "s": 27715, "text": "labels : This parameter is the labels for each dataset." }, { "code": null, "e": 27850, "s": 27771, "text": "manage_ticks : This parameter is used to adjust the tick locations and labels." }, { "code": null, "e": 27917, "s": 27850, "text": "zorder : This parameter is used to sets the zorder of the boxplot." }, { "code": null, "e": 27954, "s": 27917, "text": "Returns: This returns the following:" }, { "code": null, "e": 28073, "s": 27954, "text": "result :This returns the dictionary which maps each component of the boxplot to a list of the matplotlib.lines.Line2D." }, { "code": null, "e": 28163, "s": 28073, "text": "Below examples illustrate the matplotlib.axes.Axes.boxplot() function in matplotlib.axes:" }, { "code": null, "e": 28174, "s": 28163, "text": "Example-1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7) val1 = np.random.rand(50) * 80val2 = np.ones(80) * 50val3 = np.random.rand(50) * 80 + 100val4 = np.random.rand(50) * -80data = np.concatenate((val1, val2, val3, val4)) fig1, ax1 = plt.subplots()ax1.boxplot(data) ax1.set_title('matplotlib.axes.Axes.boxplot() Example')plt.show()", "e": 28569, "s": 28174, "text": null }, { "code": null, "e": 28577, "s": 28569, "text": "Output:" }, { "code": null, "e": 28588, "s": 28577, "text": "Example-2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7) val1 = np.random.rand(50) * 80val2 = np.ones(25) * 80val3 = np.random.rand(25) * 80 + 100val4 = np.random.rand(25) * -80data = np.concatenate((val1, val2, val3, val4))data1 = np.concatenate((val2, val4, val1, val3))data = [data, data1] fig1, ax1 = plt.subplots()ax1.boxplot(data, notch = True, vert = False, whis = 0.75) ax1.set_title('matplotlib.axes.Axes.boxplot() Example')plt.show()", "e": 29092, "s": 28588, "text": null }, { "code": null, "e": 29100, "s": 29092, "text": "Output:" }, { "code": null, "e": 29118, "s": 29100, "text": "Python-matplotlib" }, { "code": null, "e": 29125, "s": 29118, "text": "Python" }, { "code": null, "e": 29223, "s": 29125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29255, "s": 29223, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29297, "s": 29255, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29339, "s": 29297, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29395, "s": 29339, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29422, "s": 29395, "text": "Python Classes and Objects" }, { "code": null, "e": 29453, "s": 29422, "text": "Python | os.path.join() method" }, { "code": null, "e": 29492, "s": 29453, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29521, "s": 29492, "text": "Create a directory in Python" }, { "code": null, "e": 29543, "s": 29521, "text": "Defaultdict in Python" } ]
How to convert JSON data to a html table using JavaScript/jQuery ? - GeeksforGeeks
30 Sep, 2021 Given an HTML document containing JSON data and the task is to convert JSON data into a HTML table. Approach 1: Take the JSON Object in a variable. Call a function which first adds the column names to the < table > element.(It is looking for the all columns, which is UNION of the column names). Traverse the JSON data and match key with the column name. Put the value of that key in the respective column. Leave the column empty if there is no value of that key. Example 1: This example implements the above approach. HTML <!DOCTYPE HTML> <html> <head> <title> How to convert JSON data to a html table using JavaScript ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "constructTable('#table')"> click here </button> <br><br> <table align = "center" id="table" border="1"> </table> <script> var el_up = document.getElementById("GFG_UP"); var list = [ { "col_1": "val_11", "col_3": "val_13" }, { "col_2": "val_22", "col_3": "val_23" }, { "col_1": "val_31", "col_3": "val_33" } ]; el_up.innerHTML = "Click on the button to create " + "the table from the JSON data.<br><br>" + JSON.stringify(list[0]) + "<br>" + JSON.stringify(list[1]) + "<br>" + JSON.stringify(list[2]); function constructTable(selector) { // Getting the all column names var cols = Headers(list, selector); // Traversing the JSON data for (var i = 0; i < list.length; i++) { var row = $('<tr/>'); for (var colIndex = 0; colIndex < cols.length; colIndex++) { var val = list[i][cols[colIndex]]; // If there is any key, which is matching // with the column name if (val == null) val = ""; row.append($('<td/>').html(val)); } // Adding each row to the table $(selector).append(row); } } function Headers(list, selector) { var columns = []; var header = $('<tr/>'); for (var i = 0; i < list.length; i++) { var row = list[i]; for (var k in row) { if ($.inArray(k, columns) == -1) { columns.push(k); // Creating the header header.append($('<th/>').html(k)); } } } // Appending the header to the table $(selector).append(header); return columns; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Store the JSON object into the variable. First put all keys in a list. Create an element <table>. Create a <tr> element for the header of the table. Visit the keys list and create a <th> for each value and insert it into the <tr> element created for the header. Then, for every entry in the object, create a cell and insert it to the particular row. Leave the column empty if there is no value of that key. Example 2: This example implements the above approach. HTML <!DOCTYPE HTML> <html> <head> <title> How to convert JSON data to a html table using JavaScript/jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_FUN()"> click here </button> <br><br> <table id="table" align = "center" border="1px"></table> <script> var el_up = document.getElementById("GFG_UP"); var list = [ {"col_1":"val_11", "col_2":"val_12", "col_3":"val_13"}, {"col_1":"val_21", "col_2":"val_22", "col_3":"val_23"}, {"col_1":"val_31", "col_2":"val_32", "col_3":"val_33"} ]; el_up.innerHTML = "Click on the button to create the " + "table from the JSON data.<br><br>" + JSON.stringify(list[0]) + "<br>" + JSON.stringify(list[1]) + "<br>" + JSON.stringify(list[2]); function GFG_FUN() { var cols = []; for (var i = 0; i < list.length; i++) { for (var k in list[i]) { if (cols.indexOf(k) === -1) { // Push all keys to the array cols.push(k); } } } // Create a table element var table = document.createElement("table"); // Create table row tr element of a table var tr = table.insertRow(-1); for (var i = 0; i < cols.length; i++) { // Create the table header th element var theader = document.createElement("th"); theader.innerHTML = cols[i]; // Append columnName to the table row tr.appendChild(theader); } // Adding the data to the table for (var i = 0; i < list.length; i++) { // Create a new row trow = table.insertRow(-1); for (var j = 0; j < cols.length; j++) { var cell = trow.insertCell(-1); // Inserting the cell at particular place cell.innerHTML = list[i][cols[j]]; } } // Add the newly created table containing json data var el = document.getElementById("table"); el.innerHTML = ""; el.appendChild(table); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. simranarora5sos JSON JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 39241, "s": 39213, "text": "\n30 Sep, 2021" }, { "code": null, "e": 39342, "s": 39241, "text": "Given an HTML document containing JSON data and the task is to convert JSON data into a HTML table. " }, { "code": null, "e": 39355, "s": 39342, "text": "Approach 1: " }, { "code": null, "e": 39391, "s": 39355, "text": "Take the JSON Object in a variable." }, { "code": null, "e": 39539, "s": 39391, "text": "Call a function which first adds the column names to the < table > element.(It is looking for the all columns, which is UNION of the column names)." }, { "code": null, "e": 39650, "s": 39539, "text": "Traverse the JSON data and match key with the column name. Put the value of that key in the respective column." }, { "code": null, "e": 39707, "s": 39650, "text": "Leave the column empty if there is no value of that key." }, { "code": null, "e": 39764, "s": 39707, "text": "Example 1: This example implements the above approach. " }, { "code": null, "e": 39769, "s": 39764, "text": "HTML" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JSON data to a html table using JavaScript ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"constructTable('#table')\"> click here </button> <br><br> <table align = \"center\" id=\"table\" border=\"1\"> </table> <script> var el_up = document.getElementById(\"GFG_UP\"); var list = [ { \"col_1\": \"val_11\", \"col_3\": \"val_13\" }, { \"col_2\": \"val_22\", \"col_3\": \"val_23\" }, { \"col_1\": \"val_31\", \"col_3\": \"val_33\" } ]; el_up.innerHTML = \"Click on the button to create \" + \"the table from the JSON data.<br><br>\" + JSON.stringify(list[0]) + \"<br>\" + JSON.stringify(list[1]) + \"<br>\" + JSON.stringify(list[2]); function constructTable(selector) { // Getting the all column names var cols = Headers(list, selector); // Traversing the JSON data for (var i = 0; i < list.length; i++) { var row = $('<tr/>'); for (var colIndex = 0; colIndex < cols.length; colIndex++) { var val = list[i][cols[colIndex]]; // If there is any key, which is matching // with the column name if (val == null) val = \"\"; row.append($('<td/>').html(val)); } // Adding each row to the table $(selector).append(row); } } function Headers(list, selector) { var columns = []; var header = $('<tr/>'); for (var i = 0; i < list.length; i++) { var row = list[i]; for (var k in row) { if ($.inArray(k, columns) == -1) { columns.push(k); // Creating the header header.append($('<th/>').html(k)); } } } // Appending the header to the table $(selector).append(header); return columns; } </script></body> </html>", "e": 42453, "s": 39769, "text": null }, { "code": null, "e": 42462, "s": 42453, "text": "Output: " }, { "code": null, "e": 42494, "s": 42462, "text": "Before clicking on the button: " }, { "code": null, "e": 42525, "s": 42494, "text": "After clicking on the button: " }, { "code": null, "e": 42539, "s": 42525, "text": "Approach 2: " }, { "code": null, "e": 42580, "s": 42539, "text": "Store the JSON object into the variable." }, { "code": null, "e": 42610, "s": 42580, "text": "First put all keys in a list." }, { "code": null, "e": 42637, "s": 42610, "text": "Create an element <table>." }, { "code": null, "e": 42688, "s": 42637, "text": "Create a <tr> element for the header of the table." }, { "code": null, "e": 42801, "s": 42688, "text": "Visit the keys list and create a <th> for each value and insert it into the <tr> element created for the header." }, { "code": null, "e": 42889, "s": 42801, "text": "Then, for every entry in the object, create a cell and insert it to the particular row." }, { "code": null, "e": 42946, "s": 42889, "text": "Leave the column empty if there is no value of that key." }, { "code": null, "e": 43002, "s": 42946, "text": "Example 2: This example implements the above approach. " }, { "code": null, "e": 43007, "s": 43002, "text": "HTML" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JSON data to a html table using JavaScript/jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_FUN()\"> click here </button> <br><br> <table id=\"table\" align = \"center\" border=\"1px\"></table> <script> var el_up = document.getElementById(\"GFG_UP\"); var list = [ {\"col_1\":\"val_11\", \"col_2\":\"val_12\", \"col_3\":\"val_13\"}, {\"col_1\":\"val_21\", \"col_2\":\"val_22\", \"col_3\":\"val_23\"}, {\"col_1\":\"val_31\", \"col_2\":\"val_32\", \"col_3\":\"val_33\"} ]; el_up.innerHTML = \"Click on the button to create the \" + \"table from the JSON data.<br><br>\" + JSON.stringify(list[0]) + \"<br>\" + JSON.stringify(list[1]) + \"<br>\" + JSON.stringify(list[2]); function GFG_FUN() { var cols = []; for (var i = 0; i < list.length; i++) { for (var k in list[i]) { if (cols.indexOf(k) === -1) { // Push all keys to the array cols.push(k); } } } // Create a table element var table = document.createElement(\"table\"); // Create table row tr element of a table var tr = table.insertRow(-1); for (var i = 0; i < cols.length; i++) { // Create the table header th element var theader = document.createElement(\"th\"); theader.innerHTML = cols[i]; // Append columnName to the table row tr.appendChild(theader); } // Adding the data to the table for (var i = 0; i < list.length; i++) { // Create a new row trow = table.insertRow(-1); for (var j = 0; j < cols.length; j++) { var cell = trow.insertCell(-1); // Inserting the cell at particular place cell.innerHTML = list[i][cols[j]]; } } // Add the newly created table containing json data var el = document.getElementById(\"table\"); el.innerHTML = \"\"; el.appendChild(table); } </script></body> </html>", "e": 45841, "s": 43007, "text": null }, { "code": null, "e": 45850, "s": 45841, "text": "Output: " }, { "code": null, "e": 45882, "s": 45850, "text": "Before clicking on the button: " }, { "code": null, "e": 45913, "s": 45882, "text": "After clicking on the button: " }, { "code": null, "e": 46132, "s": 45913, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 46148, "s": 46132, "text": "simranarora5sos" }, { "code": null, "e": 46153, "s": 46148, "text": "JSON" }, { "code": null, "e": 46164, "s": 46153, "text": "JavaScript" }, { "code": null, "e": 46181, "s": 46164, "text": "Web Technologies" }, { "code": null, "e": 46208, "s": 46181, "text": "Web technologies Questions" }, { "code": null, "e": 46306, "s": 46208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46346, "s": 46306, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46391, "s": 46346, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 46452, "s": 46391, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 46524, "s": 46452, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 46593, "s": 46524, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 46633, "s": 46593, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46666, "s": 46633, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 46711, "s": 46666, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 46754, "s": 46711, "text": "How to fetch data from an API in ReactJS ?" } ]
jQuery | table2excel Plugin - GeeksforGeeks
28 May, 2020 In the process of web design and development, taking regular backups is an important practice followed. jQuery provides table2excel plugin which helps to export HTML tables to excel (.xls) files. Please download the required library files from the jQuery table2excel plugin and include it in your working folder as shown in the following examples. Download link: https://github.com/rainabba/jquery-table2excel Example 1: The following example demonstrates the very basic functionality of the table2excel plugin. The table contents along with the headers are exported to the “GFGFile.xls” file. <!DOCTYPE html><html> <head> <title>jQuery table2excel plugin</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"> </script> <script src="jquery.table2excel.js"></script> </head> <body> <h1 style="color:green">GeeksForGeeks</h1> <b>jQuery table2excel plugin </b> <p></p> <table id="myTable" class="table2excel"> <tr> <th>Company</th> <th>Name</th> <th>Country</th> </tr> <tr> <td>IBM</td> <td>Maria</td> <td>Germany</td> </tr> <tr> <td>TCS</td> <td>Yen Chang</td> <td>Mexico</td> </tr> <tr> <td>Microsoft</td> <td>Roland</td> <td>Austria</td> </tr> <tr> <td>Wipro</td> <td>Helen</td> <td>UK</td> </tr> <tr> <td>Samsung</td> <td>Yoshwini</td> <td>Canada</td> </tr> <tr> <td>Virtusa</td> <td>Rovelli</td> <td>Italy</td> </tr> </table> <script> $(function() { $("#myTable").table2excel({ name: "Backup file for HTML content", // include extension also filename: "GFGFile.xls", // 'True' is set if background and font colors preserved preserveColors: false }); }); </script> </body></html> Output: Before export: Before export: After export in ‘GFGFile.xls’: After export in ‘GFGFile.xls’: Example 2: In the following example, table2excel plugin is explained along with showing more options setting. In the HTML structure, two tables are taken for showing different results in export files. The table’s row 1 headers are not exported in the output excel files as they have been assigned class “noExl” as shown in the below program. Table 2 is assigned with class “colorClass” so that the colors assigned to any HTML controls are preserved as shown in the code. Programmers can set options depending on the application’s requirements. <!DOCTYPE html><html> <head> <title>jQuery table2excel plugin</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"> </script> <script src="jquery.table2excel.js"></script> </head> <body> <h1 style="color:green">GeeksForGeeks</h1> <b>jQuery table2excel plugin </b> <p></p> <table class="table2excel"> <thead> <tr class="noExl"> <td> Table 1 Header, column 1 (not exported)</td> <td>Table 1 Header, column 2(not exported) </td> </tr> <tr><td>Table 1 Header, column 1 (exported)</td> <td>Table 1 Header, column 2 (exported)</td></tr> </thead> <tbody> <tr><td>Row 1, column 1 data of table1</td> <td>Row 1 column 2 data of table 1</td></tr> <tr><td>Row 2, column 1 data of table1</td> <td>Row 2, column 2 dataof table1</td></tr> </tbody> <tfoot> <tr><td colspan="2">This is the footer of table 1.</td></tr> </tfoot> </table> <button class="exportBtnClass">Export to XLS file</button><p></p> <table class="table2excel colorClass"> <thead> <tr class="noExl"> <td>Table 2 Header, column 1 (not exported)</td> <td>Table 2 Header, column 1 (not exported)</td></tr> <tr><td style="background-color: green;"> Table 2 Header, column 1 (exported with colors)</td> <td>Table 2 Header, column 2 (exported)</td></tr> </thead> <tbody> <tr><td style="background-color: red;"> Row 1, column 1 data of table2</td> <td>Row 1 column 2 data of table2</td></tr> <tr><td>Row 2, column 1 data of table2</td> <td>Row 2, column 2 data of table2</td></tr> </tbody> <tfoot> <tr><td colspan="2"> This is the footer of table 2</td></tr> </tfoot> </table> <button class="exportBtnClass"> Export to XLS file </button> <script> $(function() { $(".exportBtnClass").click(function(e){ var table = $(this).prev('.table2excel'); if(table && table.length){ var preserveColors = (table.hasClass('colorClass') ? true : false); $(table).table2excel({ // This class's content is excluded from getting exported exclude: ".noExl", name: "Output excel file ", filename: "outputFile-" + new Date().toString().replace(/[\-\:\.]/g, "") + ".xls", fileext: ".xls", //File extension type exclude_img: true, exclude_links: true, exclude_inputs: true, preserveColors: preserveColors }); } }); }); </script> </body></html> Output: Before export : Before export : After export of table 1 : After export of table 1 : After export of table 2: After export of table 2: jQuery-Plugin JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scroll to the top of the page using JavaScript/jQuery jQuery | children() with Examples How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? How to redirect to a particular section of a page using HTML or jQuery? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26926, "s": 26898, "text": "\n28 May, 2020" }, { "code": null, "e": 27122, "s": 26926, "text": "In the process of web design and development, taking regular backups is an important practice followed. jQuery provides table2excel plugin which helps to export HTML tables to excel (.xls) files." }, { "code": null, "e": 27274, "s": 27122, "text": "Please download the required library files from the jQuery table2excel plugin and include it in your working folder as shown in the following examples." }, { "code": null, "e": 27336, "s": 27274, "text": "Download link: https://github.com/rainabba/jquery-table2excel" }, { "code": null, "e": 27520, "s": 27336, "text": "Example 1: The following example demonstrates the very basic functionality of the table2excel plugin. The table contents along with the headers are exported to the “GFGFile.xls” file." }, { "code": "<!DOCTYPE html><html> <head> <title>jQuery table2excel plugin</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"> </script> <script src=\"jquery.table2excel.js\"></script> </head> <body> <h1 style=\"color:green\">GeeksForGeeks</h1> <b>jQuery table2excel plugin </b> <p></p> <table id=\"myTable\" class=\"table2excel\"> <tr> <th>Company</th> <th>Name</th> <th>Country</th> </tr> <tr> <td>IBM</td> <td>Maria</td> <td>Germany</td> </tr> <tr> <td>TCS</td> <td>Yen Chang</td> <td>Mexico</td> </tr> <tr> <td>Microsoft</td> <td>Roland</td> <td>Austria</td> </tr> <tr> <td>Wipro</td> <td>Helen</td> <td>UK</td> </tr> <tr> <td>Samsung</td> <td>Yoshwini</td> <td>Canada</td> </tr> <tr> <td>Virtusa</td> <td>Rovelli</td> <td>Italy</td> </tr> </table> <script> $(function() { $(\"#myTable\").table2excel({ name: \"Backup file for HTML content\", // include extension also filename: \"GFGFile.xls\", // 'True' is set if background and font colors preserved preserveColors: false }); }); </script> </body></html>", "e": 29303, "s": 27520, "text": null }, { "code": null, "e": 29311, "s": 29303, "text": "Output:" }, { "code": null, "e": 29326, "s": 29311, "text": "Before export:" }, { "code": null, "e": 29341, "s": 29326, "text": "Before export:" }, { "code": null, "e": 29372, "s": 29341, "text": "After export in ‘GFGFile.xls’:" }, { "code": null, "e": 29403, "s": 29372, "text": "After export in ‘GFGFile.xls’:" }, { "code": null, "e": 29947, "s": 29403, "text": "Example 2: In the following example, table2excel plugin is explained along with showing more options setting. In the HTML structure, two tables are taken for showing different results in export files. The table’s row 1 headers are not exported in the output excel files as they have been assigned class “noExl” as shown in the below program. Table 2 is assigned with class “colorClass” so that the colors assigned to any HTML controls are preserved as shown in the code. Programmers can set options depending on the application’s requirements." }, { "code": "<!DOCTYPE html><html> <head> <title>jQuery table2excel plugin</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"> </script> <script src=\"jquery.table2excel.js\"></script> </head> <body> <h1 style=\"color:green\">GeeksForGeeks</h1> <b>jQuery table2excel plugin </b> <p></p> <table class=\"table2excel\"> <thead> <tr class=\"noExl\"> <td> Table 1 Header, column 1 (not exported)</td> <td>Table 1 Header, column 2(not exported) </td> </tr> <tr><td>Table 1 Header, column 1 (exported)</td> <td>Table 1 Header, column 2 (exported)</td></tr> </thead> <tbody> <tr><td>Row 1, column 1 data of table1</td> <td>Row 1 column 2 data of table 1</td></tr> <tr><td>Row 2, column 1 data of table1</td> <td>Row 2, column 2 dataof table1</td></tr> </tbody> <tfoot> <tr><td colspan=\"2\">This is the footer of table 1.</td></tr> </tfoot> </table> <button class=\"exportBtnClass\">Export to XLS file</button><p></p> <table class=\"table2excel colorClass\"> <thead> <tr class=\"noExl\"> <td>Table 2 Header, column 1 (not exported)</td> <td>Table 2 Header, column 1 (not exported)</td></tr> <tr><td style=\"background-color: green;\"> Table 2 Header, column 1 (exported with colors)</td> <td>Table 2 Header, column 2 (exported)</td></tr> </thead> <tbody> <tr><td style=\"background-color: red;\"> Row 1, column 1 data of table2</td> <td>Row 1 column 2 data of table2</td></tr> <tr><td>Row 2, column 1 data of table2</td> <td>Row 2, column 2 data of table2</td></tr> </tbody> <tfoot> <tr><td colspan=\"2\"> This is the footer of table 2</td></tr> </tfoot> </table> <button class=\"exportBtnClass\"> Export to XLS file </button> <script> $(function() { $(\".exportBtnClass\").click(function(e){ var table = $(this).prev('.table2excel'); if(table && table.length){ var preserveColors = (table.hasClass('colorClass') ? true : false); $(table).table2excel({ // This class's content is excluded from getting exported exclude: \".noExl\", name: \"Output excel file \", filename: \"outputFile-\" + new Date().toString().replace(/[\\-\\:\\.]/g, \"\") + \".xls\", fileext: \".xls\", //File extension type exclude_img: true, exclude_links: true, exclude_inputs: true, preserveColors: preserveColors }); } }); }); </script> </body></html>", "e": 33271, "s": 29947, "text": null }, { "code": null, "e": 33279, "s": 33271, "text": "Output:" }, { "code": null, "e": 33295, "s": 33279, "text": "Before export :" }, { "code": null, "e": 33311, "s": 33295, "text": "Before export :" }, { "code": null, "e": 33337, "s": 33311, "text": "After export of table 1 :" }, { "code": null, "e": 33363, "s": 33337, "text": "After export of table 1 :" }, { "code": null, "e": 33388, "s": 33363, "text": "After export of table 2:" }, { "code": null, "e": 33413, "s": 33388, "text": "After export of table 2:" }, { "code": null, "e": 33427, "s": 33413, "text": "jQuery-Plugin" }, { "code": null, "e": 33434, "s": 33427, "text": "JQuery" }, { "code": null, "e": 33451, "s": 33434, "text": "Web Technologies" }, { "code": null, "e": 33549, "s": 33451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33603, "s": 33549, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 33637, "s": 33603, "text": "jQuery | children() with Examples" }, { "code": null, "e": 33692, "s": 33637, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 33765, "s": 33692, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 33837, "s": 33765, "text": "How to redirect to a particular section of a page using HTML or jQuery?" }, { "code": null, "e": 33877, "s": 33837, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33910, "s": 33877, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33955, "s": 33910, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33998, "s": 33955, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | fmod() function - GeeksforGeeks
21 Sep, 2018 fmod() function is one of the Standard math library function in Python, which is used to calculate the Module of the specified given arguments. Syntax: math.fmod( x, y ) Parameters:x any valid number (positive or negative).y any valid number(positive or negative). Returns: Return a floating point number value after calculating module of given parameters x and y. Example #1: # Python3 program to demonstrate fmod() function import math # Tuple DeclarationTup = (15, 22, -2, -40 ) # List DeclarationLis = [-89, 38, -39, 16] # modulus of +ve integer numberprint(math.fmod(4, 5))print(math.fmod(43.50, 4.5)) # modulus of -ve integer numberprint(math.fmod(-17, 5))print('%.2f' %math.fmod(-10, 4.78)) # modulus of tuple itemprint("\nModulus of tuple items:")print(math.fmod(Tup[2], 5))print(math.fmod(Tup[2], -6)) # modulus of list itemprint("\nModulus of list items:")print(math.fmod(Lis[3], 4))print(math.fmod(Lis[0], -15)) Output: 4.0 3.0 -2.0 -0.44 Modulus of tuple items: -2.0 -2.0 Modulus of list items: 0.0 -14.0 Example #2: ValueError and TypeError If both the x and y arguments are Zero, fmod() function will return the output as ValueError. If y argument (second argument) is Zero, fmod() function will return the output as ValueError. If the x value or y value is not a number, fmod() function will return TypeError. # Python3 program to demonstrate # errors in fmod() function import math # will give ValueErrorprint(math.fmod(0, 0))print(math.fmod(2, 0)) # it will give TypeErrorprint(math.fmod('2', 3)) Output: ValueError: math domain error ValueError: math domain error TypeError: a float is required Python math-library Python math-library-functions Python-Built-in-functions Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n21 Sep, 2018" }, { "code": null, "e": 25681, "s": 25537, "text": "fmod() function is one of the Standard math library function in Python, which is used to calculate the Module of the specified given arguments." }, { "code": null, "e": 25707, "s": 25681, "text": "Syntax: math.fmod( x, y )" }, { "code": null, "e": 25802, "s": 25707, "text": "Parameters:x any valid number (positive or negative).y any valid number(positive or negative)." }, { "code": null, "e": 25902, "s": 25802, "text": "Returns: Return a floating point number value after calculating module of given parameters x and y." }, { "code": null, "e": 25914, "s": 25902, "text": "Example #1:" }, { "code": "# Python3 program to demonstrate fmod() function import math # Tuple DeclarationTup = (15, 22, -2, -40 ) # List DeclarationLis = [-89, 38, -39, 16] # modulus of +ve integer numberprint(math.fmod(4, 5))print(math.fmod(43.50, 4.5)) # modulus of -ve integer numberprint(math.fmod(-17, 5))print('%.2f' %math.fmod(-10, 4.78)) # modulus of tuple itemprint(\"\\nModulus of tuple items:\")print(math.fmod(Tup[2], 5))print(math.fmod(Tup[2], -6)) # modulus of list itemprint(\"\\nModulus of list items:\")print(math.fmod(Lis[3], 4))print(math.fmod(Lis[0], -15))", "e": 26468, "s": 25914, "text": null }, { "code": null, "e": 26476, "s": 26468, "text": "Output:" }, { "code": null, "e": 26565, "s": 26476, "text": "4.0\n3.0\n-2.0\n-0.44\n\nModulus of tuple items:\n-2.0\n-2.0\n\nModulus of list items:\n0.0\n-14.0\n" }, { "code": null, "e": 26603, "s": 26565, "text": " Example #2: ValueError and TypeError" }, { "code": null, "e": 26697, "s": 26603, "text": "If both the x and y arguments are Zero, fmod() function will return the output as ValueError." }, { "code": null, "e": 26792, "s": 26697, "text": "If y argument (second argument) is Zero, fmod() function will return the output as ValueError." }, { "code": null, "e": 26874, "s": 26792, "text": "If the x value or y value is not a number, fmod() function will return TypeError." }, { "code": "# Python3 program to demonstrate # errors in fmod() function import math # will give ValueErrorprint(math.fmod(0, 0))print(math.fmod(2, 0)) # it will give TypeErrorprint(math.fmod('2', 3))", "e": 27066, "s": 26874, "text": null }, { "code": null, "e": 27074, "s": 27066, "text": "Output:" }, { "code": null, "e": 27166, "s": 27074, "text": "ValueError: math domain error\nValueError: math domain error\nTypeError: a float is required\n" }, { "code": null, "e": 27186, "s": 27166, "text": "Python math-library" }, { "code": null, "e": 27216, "s": 27186, "text": "Python math-library-functions" }, { "code": null, "e": 27242, "s": 27216, "text": "Python-Built-in-functions" }, { "code": null, "e": 27257, "s": 27242, "text": "Python-Library" }, { "code": null, "e": 27264, "s": 27257, "text": "Python" }, { "code": null, "e": 27362, "s": 27264, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27394, "s": 27362, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27436, "s": 27394, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27478, "s": 27436, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27534, "s": 27478, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27561, "s": 27534, "text": "Python Classes and Objects" }, { "code": null, "e": 27592, "s": 27561, "text": "Python | os.path.join() method" }, { "code": null, "e": 27631, "s": 27592, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27660, "s": 27631, "text": "Create a directory in Python" }, { "code": null, "e": 27682, "s": 27660, "text": "Defaultdict in Python" } ]
Underscore.js _.countBy Function - GeeksforGeeks
24 Nov, 2021 The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects.The _.countBy() function is used to sort a list into groups and returns a count for the number of objects in each group. It works by matching the value of each element to the other. If they matches then the count of one collection increases by 1 otherwise the count of another collections/groups which has that value increases by 1. It can also pass a function based on who’s result will collect the elements and increase the count of each group. It can match both on the basis of number and also by string. Syntax: _.countBy(list, iteratee, [context]) Parameters: This function accepts three parameters as mentioned above and described below: List: This parameter is used to hold the list of items. Iteratee: This parameter is used to hold the test condition. Context: The text content which need to display. Return values: It returns the collections as the different arrays. Passing Math.ceil() function to the _.countBy() function: The _.countBy() function takes the element from the list one by one and pass it to the other function mentioned here. Here the function is taking the ceil of each number and returning it’s values. So, all the value of the array are counted one by one after their ceil has been taken and then counted according to whether they are same or different. Example: <html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> console.log(_.countBy([2.7, 3.4, 6.6, 1.2, 2.0, 2.4], function(num){ return Math.ceil(num); })); </script> </body></html> Output: Using length() in the _.countBy() function: Passing the array elements to the countBy() function. Then, find out the length of each element and make collections of the lengths that are same. Finally, display the count of each collection with the respective lengths along the left. Example: <html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> console.log(_.countBy(['HTML', 'CSS3', 'JS', 'PHP'], 'length')); </script> </body></html> Output: Using one property of the array passed in the _.countBy() function: First declare the array (here array is ‘arr’). Choose one condition on which need to count like here ‘prop3’. Then the elements which have the same value in the ‘prop3’ will be grouped in 1 collection. The final result will contain the prop3 in the left side along with their count on the right. Like here in prop3, “Geeks” is coming two times, so it’s count will be 2. Console.log the final answer. Example: <html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var arr = [ {prop1:"10", prop2:"07", prop3: "Geeks"}, {prop1:"12", prop2:"86", prop3: "for"}, {prop1:"11", prop2:"58", prop3: "Geeks"} ]; console.log(_.countBy(arr, 'prop3')); </script> </body></html> Output: Passing ‘date’ as property of the array to the _.countBy() function together: First define an array with one property as ‘date’ of the format ‘dd-mm-yy’. Then pass the array and the ‘date’ property to the _.countBy() function. The elements having the same date will be grouped as one collection and then the count of each group will be displayed in the result. Example: <html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var orders = [ { date:"30-60-90 Day", Name:"Kim", amount:415 }, { date:"30-60-90 Day", Name:"Kelly", amount:175 }, { date:"30 Day", Name:"Shelly", amount:400 }, { date:"30 Day", Name:"Sarvesh", amount:180 } ]; console.log(_.countBy(orders, "date")); </script> </body></html> Output: Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them. <script type="text/javascript" src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> JavaScript - Underscore.js javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array 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 Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26297, "s": 26269, "text": "\n24 Nov, 2021" }, { "code": null, "e": 27003, "s": 26297, "text": "The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects.The _.countBy() function is used to sort a list into groups and returns a count for the number of objects in each group. It works by matching the value of each element to the other. If they matches then the count of one collection increases by 1 otherwise the count of another collections/groups which has that value increases by 1. It can also pass a function based on who’s result will collect the elements and increase the count of each group. It can match both on the basis of number and also by string." }, { "code": null, "e": 27011, "s": 27003, "text": "Syntax:" }, { "code": null, "e": 27049, "s": 27011, "text": "_.countBy(list, iteratee, [context]) " }, { "code": null, "e": 27140, "s": 27049, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 27196, "s": 27140, "text": "List: This parameter is used to hold the list of items." }, { "code": null, "e": 27257, "s": 27196, "text": "Iteratee: This parameter is used to hold the test condition." }, { "code": null, "e": 27306, "s": 27257, "text": "Context: The text content which need to display." }, { "code": null, "e": 27373, "s": 27306, "text": "Return values: It returns the collections as the different arrays." }, { "code": null, "e": 27780, "s": 27373, "text": "Passing Math.ceil() function to the _.countBy() function: The _.countBy() function takes the element from the list one by one and pass it to the other function mentioned here. Here the function is taking the ceil of each number and returning it’s values. So, all the value of the array are counted one by one after their ceil has been taken and then counted according to whether they are same or different." }, { "code": null, "e": 27789, "s": 27780, "text": "Example:" }, { "code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> console.log(_.countBy([2.7, 3.4, 6.6, 1.2, 2.0, 2.4], function(num){ return Math.ceil(num); })); </script> </body></html> ", "e": 28186, "s": 27789, "text": null }, { "code": null, "e": 28194, "s": 28186, "text": "Output:" }, { "code": null, "e": 28475, "s": 28194, "text": "Using length() in the _.countBy() function: Passing the array elements to the countBy() function. Then, find out the length of each element and make collections of the lengths that are same. Finally, display the count of each collection with the respective lengths along the left." }, { "code": null, "e": 28484, "s": 28475, "text": "Example:" }, { "code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> console.log(_.countBy(['HTML', 'CSS3', 'JS', 'PHP'], 'length')); </script> </body></html>", "e": 28814, "s": 28484, "text": null }, { "code": null, "e": 28822, "s": 28814, "text": "Output:" }, { "code": null, "e": 29290, "s": 28822, "text": "Using one property of the array passed in the _.countBy() function: First declare the array (here array is ‘arr’). Choose one condition on which need to count like here ‘prop3’. Then the elements which have the same value in the ‘prop3’ will be grouped in 1 collection. The final result will contain the prop3 in the left side along with their count on the right. Like here in prop3, “Geeks” is coming two times, so it’s count will be 2. Console.log the final answer." }, { "code": null, "e": 29299, "s": 29290, "text": "Example:" }, { "code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var arr = [ {prop1:\"10\", prop2:\"07\", prop3: \"Geeks\"}, {prop1:\"12\", prop2:\"86\", prop3: \"for\"}, {prop1:\"11\", prop2:\"58\", prop3: \"Geeks\"} ]; console.log(_.countBy(arr, 'prop3')); </script> </body></html>", "e": 29809, "s": 29299, "text": null }, { "code": null, "e": 29817, "s": 29809, "text": "Output:" }, { "code": null, "e": 30178, "s": 29817, "text": "Passing ‘date’ as property of the array to the _.countBy() function together: First define an array with one property as ‘date’ of the format ‘dd-mm-yy’. Then pass the array and the ‘date’ property to the _.countBy() function. The elements having the same date will be grouped as one collection and then the count of each group will be displayed in the result." }, { "code": null, "e": 30187, "s": 30178, "text": "Example:" }, { "code": "<html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var orders = [ { date:\"30-60-90 Day\", Name:\"Kim\", amount:415 }, { date:\"30-60-90 Day\", Name:\"Kelly\", amount:175 }, { date:\"30 Day\", Name:\"Shelly\", amount:400 }, { date:\"30 Day\", Name:\"Sarvesh\", amount:180 } ]; console.log(_.countBy(orders, \"date\")); </script> </body></html>", "e": 30814, "s": 30187, "text": null }, { "code": null, "e": 30822, "s": 30814, "text": "Output:" }, { "code": null, "e": 31027, "s": 30822, "text": "Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them." }, { "code": "<script type=\"text/javascript\" src =\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"></script>", "e": 31152, "s": 31027, "text": null }, { "code": null, "e": 31179, "s": 31152, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 31200, "s": 31179, "text": "javascript-functions" }, { "code": null, "e": 31211, "s": 31200, "text": "JavaScript" }, { "code": null, "e": 31228, "s": 31211, "text": "Web Technologies" }, { "code": null, "e": 31326, "s": 31228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31366, "s": 31326, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31411, "s": 31366, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31472, "s": 31411, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31544, "s": 31472, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31590, "s": 31544, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 31630, "s": 31590, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31663, "s": 31630, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31708, "s": 31663, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31751, "s": 31708, "text": "How to fetch data from an API in ReactJS ?" } ]
How to redirect a user to the registration if he has not logged in? - GeeksforGeeks
04 Jul, 2021 Not all content on a website is accessible to all users. There exist some confidential content where only authorized members can access.When a user searches for an IEEE Paper, the IEEE.org displays only the abstract of the paper. To read the whole paper, according to the organization’s protocol user requires membership authentication from the organization. Thus, non-members will be redirected to the login page. It is an act of protecting information and validating users. Functions and Variables Used: Session: Session is a temporary database in an application to capture who is the user and what he does on every page of the web application. This information is stored as variables that can be accessed across multiple pages in one application. Once the user closes the browser, the database gets aborted. Isset: Function to check if a variable is set or not. Header: Function used to send information via HTTP header to client or server. Timeout: Timeout function in javascript used to execute a function after a specified time delay. Example: We have to design a resistor you can say filter that will stop the non-login user to visit the confidential content.PHP-Redirect to Login page : The basicpage.php code displays the abstract content that can be viewed by any user. Whereas, when the user clicks read more to view the whole content the program checks if the user is logged in. In this program, the session variable loggedin is used to store a valid authenticated token. The variable is validated whether it stores a value or not using isset function. If a value is not set, the user is redirected to the login page. The location parameter within the header function is used to define the page to be redirected when the condition holds true. basicpage.php Code php // To check if a user is logged in else,// redirect to the login page.<?php session_start(); if(isset($_POST['read'])){ if (!isset($_SESSION['loggedin'])) { header('Location: login.php'); } else { if (isset($_POST['read'])) { header('location:https://www.geeksforgeeks.org/about/'); session_destroy(); } } }?><html> <body> <img src="GFG.png" style="float:left;width:100px;height:100px;"> <h1>GeeksForGeeks</h1> <h2>A computer science portal for geeks</h2> <p>How many times were you frustrated while looking out for a</p> <p>good collection of programming/algorithm/interview questions? <p>What did you expect and what did you get?</p> <p>This portal has been created to provide well written, </p> <p>well thought and well explained solutions for selected questions.</p> <form action="basicpage.php" method="POST"> <input type="submit" name="read" value="Read More..." style="background-color:#4CAF50; color:white; padding:10px 25px; text-align:center; font-size:15px; cursor:pointer;" /> </form></body> </html> Login page: The session_start() function used here, is to transfer the variable content from one page (basicpage.php) to other page.After the form submission via the POST method, if the login credentials are valid, then the variable is set to TRUE. Using the header function, the page is redirected to basicpage.php where the session variables are transferred along with HTTP request URI. This allows the user to view the whole content when read more button is clicked again in that session. Using the timeout function, the page redirection is executed after(1500milliseconds) the validation message of the login page is printed. Loginpage.php Code php // To Validate the user credentials and to sent// session variables via HTTP request.<?phpsession_start();if(isset($_POST['submit'])){ if($_POST['password'] == "admin") { $_SESSION['loggedin'] = True; echo "Valid Token, GFG Authenticated User";?> <script>setTimeout(function(){window.location ="http://localhost/GFG/basicpage.php";}, 1000); </script> <?php } else { echo "Not a Valid Token, Requires GFG Authentication to log in";?> <script>setTimeout(function(){window.location ="http://localhost/GFG/basicpage.php";}, 4000); </script> <?php }} ?><html> <body> <h1 style="color:green"> Requires Authentication Token to View Content </h1> <form method="POST" action="login.php"> <strong>Password:</strong> <input type="password" name="password" id="password" /> <input type="submit" name="submit" value="Log In" style="background-color:#4CAF50; color:white;padding:10px 25px; text-align:center;font-size:15px; cursor:pointer;" /> <br> <input type="checkbox" onclick="showPassword()"> Show password <script> function showPassword() { var x = document.getElementById("password"); if (x.type == "password") { x.type = "text"; } } </script> </form></body> </html> During the very first execution before logged in, the session started for this application. In that case, if the user clicks read more in basicpage.php implies that the session variable logged in is not set (i.e. Null). Page is redirected to loginpage.php. If the user enters incorrect password, the page is redirected to basicpage.php without setting the session variable true and by displaying the validation message “Not a Valid Token, Requires GFG Authentication to log in”. Now, if the user clicks read more, again will be redirected to loginpage.php. In loginpage.php when the user enters correct password admin. The session variable, logged-in is set true and redirected to basicpage.php after displaying the validation message “Valid Token, GFG Authenticated User”. Now, if the user clicks read more, the page is redirected to view the whole content. anikaseth98 PHP-Misc PHP PHP Programs PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Different ways for passing data to view in Laravel How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? How to pass form variables from one page to other page in PHP ? PHP | Ternary Operator
[ { "code": null, "e": 26217, "s": 26189, "text": "\n04 Jul, 2021" }, { "code": null, "e": 26725, "s": 26217, "text": "Not all content on a website is accessible to all users. There exist some confidential content where only authorized members can access.When a user searches for an IEEE Paper, the IEEE.org displays only the abstract of the paper. To read the whole paper, according to the organization’s protocol user requires membership authentication from the organization. Thus, non-members will be redirected to the login page. It is an act of protecting information and validating users. Functions and Variables Used: " }, { "code": null, "e": 27030, "s": 26725, "text": "Session: Session is a temporary database in an application to capture who is the user and what he does on every page of the web application. This information is stored as variables that can be accessed across multiple pages in one application. Once the user closes the browser, the database gets aborted." }, { "code": null, "e": 27084, "s": 27030, "text": "Isset: Function to check if a variable is set or not." }, { "code": null, "e": 27163, "s": 27084, "text": "Header: Function used to send information via HTTP header to client or server." }, { "code": null, "e": 27260, "s": 27163, "text": "Timeout: Timeout function in javascript used to execute a function after a specified time delay." }, { "code": null, "e": 27975, "s": 27260, "text": "Example: We have to design a resistor you can say filter that will stop the non-login user to visit the confidential content.PHP-Redirect to Login page : The basicpage.php code displays the abstract content that can be viewed by any user. Whereas, when the user clicks read more to view the whole content the program checks if the user is logged in. In this program, the session variable loggedin is used to store a valid authenticated token. The variable is validated whether it stores a value or not using isset function. If a value is not set, the user is redirected to the login page. The location parameter within the header function is used to define the page to be redirected when the condition holds true. " }, { "code": null, "e": 27996, "s": 27975, "text": "basicpage.php Code " }, { "code": null, "e": 28000, "s": 27996, "text": "php" }, { "code": "// To check if a user is logged in else,// redirect to the login page.<?php session_start(); if(isset($_POST['read'])){ if (!isset($_SESSION['loggedin'])) { header('Location: login.php'); } else { if (isset($_POST['read'])) { header('location:https://www.geeksforgeeks.org/about/'); session_destroy(); } } }?><html> <body> <img src=\"GFG.png\" style=\"float:left;width:100px;height:100px;\"> <h1>GeeksForGeeks</h1> <h2>A computer science portal for geeks</h2> <p>How many times were you frustrated while looking out for a</p> <p>good collection of programming/algorithm/interview questions? <p>What did you expect and what did you get?</p> <p>This portal has been created to provide well written, </p> <p>well thought and well explained solutions for selected questions.</p> <form action=\"basicpage.php\" method=\"POST\"> <input type=\"submit\" name=\"read\" value=\"Read More...\" style=\"background-color:#4CAF50; color:white; padding:10px 25px; text-align:center; font-size:15px; cursor:pointer;\" /> </form></body> </html>", "e": 29407, "s": 28000, "text": null }, { "code": null, "e": 30040, "s": 29409, "text": "Login page: The session_start() function used here, is to transfer the variable content from one page (basicpage.php) to other page.After the form submission via the POST method, if the login credentials are valid, then the variable is set to TRUE. Using the header function, the page is redirected to basicpage.php where the session variables are transferred along with HTTP request URI. This allows the user to view the whole content when read more button is clicked again in that session. Using the timeout function, the page redirection is executed after(1500milliseconds) the validation message of the login page is printed. " }, { "code": null, "e": 30061, "s": 30040, "text": "Loginpage.php Code " }, { "code": null, "e": 30065, "s": 30061, "text": "php" }, { "code": "// To Validate the user credentials and to sent// session variables via HTTP request.<?phpsession_start();if(isset($_POST['submit'])){ if($_POST['password'] == \"admin\") { $_SESSION['loggedin'] = True; echo \"Valid Token, GFG Authenticated User\";?> <script>setTimeout(function(){window.location =\"http://localhost/GFG/basicpage.php\";}, 1000); </script> <?php } else { echo \"Not a Valid Token, Requires GFG Authentication to log in\";?> <script>setTimeout(function(){window.location =\"http://localhost/GFG/basicpage.php\";}, 4000); </script> <?php }} ?><html> <body> <h1 style=\"color:green\"> Requires Authentication Token to View Content </h1> <form method=\"POST\" action=\"login.php\"> <strong>Password:</strong> <input type=\"password\" name=\"password\" id=\"password\" /> <input type=\"submit\" name=\"submit\" value=\"Log In\" style=\"background-color:#4CAF50; color:white;padding:10px 25px; text-align:center;font-size:15px; cursor:pointer;\" /> <br> <input type=\"checkbox\" onclick=\"showPassword()\"> Show password <script> function showPassword() { var x = document.getElementById(\"password\"); if (x.type == \"password\") { x.type = \"text\"; } } </script> </form></body> </html>", "e": 31563, "s": 30065, "text": null }, { "code": null, "e": 31822, "s": 31563, "text": "During the very first execution before logged in, the session started for this application. In that case, if the user clicks read more in basicpage.php implies that the session variable logged in is not set (i.e. Null). Page is redirected to loginpage.php. " }, { "code": null, "e": 32124, "s": 31822, "text": "If the user enters incorrect password, the page is redirected to basicpage.php without setting the session variable true and by displaying the validation message “Not a Valid Token, Requires GFG Authentication to log in”. Now, if the user clicks read more, again will be redirected to loginpage.php. " }, { "code": null, "e": 32426, "s": 32124, "text": "In loginpage.php when the user enters correct password admin. The session variable, logged-in is set true and redirected to basicpage.php after displaying the validation message “Valid Token, GFG Authenticated User”. Now, if the user clicks read more, the page is redirected to view the whole content." }, { "code": null, "e": 32438, "s": 32426, "text": "anikaseth98" }, { "code": null, "e": 32447, "s": 32438, "text": "PHP-Misc" }, { "code": null, "e": 32451, "s": 32447, "text": "PHP" }, { "code": null, "e": 32464, "s": 32451, "text": "PHP Programs" }, { "code": null, "e": 32468, "s": 32464, "text": "PHP" }, { "code": null, "e": 32566, "s": 32468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32648, "s": 32566, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 32690, "s": 32648, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 32717, "s": 32690, "text": "PHP str_replace() Function" }, { "code": null, "e": 32781, "s": 32717, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 32832, "s": 32781, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 32884, "s": 32832, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 32966, "s": 32884, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 33008, "s": 32966, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 33072, "s": 33008, "text": "How to pass form variables from one page to other page in PHP ?" } ]
How to change link color in CSS ? - GeeksforGeeks
20 Jun, 2021 In HTML hyperlinks are added into the webpage by using the anchor tag <a>Name</a>. It creates the link navigate to another webpage from the current webpage. The default HTML links are in blue color and when mouse hovered they get an underline. When the link is visited, it becomes violet. These default properties can be changed and can be customized by using different CSS properties. Example 1: Create a basic customization of HTML link using CSS selector. HTML <!DOCTYPE html><html lang="en"> <head> <!--Meta data--> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> h1 { color: #006600; text-align: center; } a{ color:#006600; text-decoration: none; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <a href = "https://practice.geeksforgeeks.org/home/"> Click me, I am a href link </a> </center> </body></html> Output: The links can be further customized based on the state. The links basically have 4 states. unvisited (a:link) hover (a: hover) visited (a: visited) active (a: active) Example 2: We can give different color to the links on change of their states. HTML <!DOCTYPE html><html lang="en"> <head> <!--Meta data--> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> h1 { color: #006600; text-align: center; } /* If the link is unvisited you see this color*/ a:link { color: #006600; text-decoration: none; } /* If the link is visited you see this color*/ a:visited { color: rgb(255, 105, 223); } /* On placing mouse over the link */ a:hover { color: rgb(128, 105, 255); text-decoration: underline; } /* If the click the link, you see this color*/ a:active { color: rgb(255, 105, 138); } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Click the links</p> <ul> <li><a href="https://www.geeksforgeeks.org/dbms/?ref=ghm"> DBMS </a> </li> <li><a href="https://www.geeksforgeeks.org/computer-network-tutorials/?ref=ghm"> Computer Networks</a> </li> <li> <a href="https://www.geeksforgeeks.org/operating-systems/?ref=ghm"> Operating Systems</a> </li> <li><a href="https://www.geeksforgeeks.org/data-structures/?ref=ghm"> Data Structures</a> </li> <li><a href="https://www.geeksforgeeks.org/"> And many more</a> </li> </ul></body> </html> Output: The unvisited and visited links have different colors. On placing the mouse over the second link, we see the change in color and style of the link. The order for placing a: hover must be after a: link and a: visited. The style a: active should come after a: hover. Example 3: The links can be further styled by applying different CSS properties like background-colour, font-size, font-style, text-decoration and many. HTML <!DOCTYPE html><html lang="en"> <head> <!--Meta data--> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> h1 { color: #006600; text-align: center; } a:link { color: #006600; text-decoration: none; } a:visited { color: rgb(255, 105, 223); } a:hover { color: white; text-decoration: underline; font-size: larger; font-style: italic; background-color:#006600; } a:active { color: rgb(255, 105, 138); } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click these links</p> <ul> <li><a href="https://www.geeksforgeeks.org/dbms/?ref=ghm"> DBMS</a> </li> <li><a href="https://www.geeksforgeeks.org/computer-network-tutorials/?ref=ghm"> Computer Networks</a> </li> <li> <a href="https://www.geeksforgeeks.org/operating-systems/?ref=ghm"> Operating Systems</a> </li> <li><a href="https://www.geeksforgeeks.org/data-structures/?ref=ghm"> Data Structures</a> </li> <li><a href="https://www.geeksforgeeks.org/">And many more</a> </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-Properties CSS-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": "\n20 Jun, 2021" }, { "code": null, "e": 26779, "s": 26621, "text": "In HTML hyperlinks are added into the webpage by using the anchor tag <a>Name</a>. It creates the link navigate to another webpage from the current webpage. " }, { "code": null, "e": 27008, "s": 26779, "text": "The default HTML links are in blue color and when mouse hovered they get an underline. When the link is visited, it becomes violet. These default properties can be changed and can be customized by using different CSS properties." }, { "code": null, "e": 27082, "s": 27008, "text": "Example 1: Create a basic customization of HTML link using CSS selector. " }, { "code": null, "e": 27087, "s": 27082, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!--Meta data--> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> h1 { color: #006600; text-align: center; } a{ color:#006600; text-decoration: none; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <a href = \"https://practice.geeksforgeeks.org/home/\"> Click me, I am a href link </a> </center> </body></html>", "e": 27696, "s": 27087, "text": null }, { "code": null, "e": 27704, "s": 27696, "text": "Output:" }, { "code": null, "e": 27760, "s": 27704, "text": "The links can be further customized based on the state." }, { "code": null, "e": 27795, "s": 27760, "text": "The links basically have 4 states." }, { "code": null, "e": 27814, "s": 27795, "text": "unvisited (a:link)" }, { "code": null, "e": 27831, "s": 27814, "text": "hover (a: hover)" }, { "code": null, "e": 27852, "s": 27831, "text": "visited (a: visited)" }, { "code": null, "e": 27871, "s": 27852, "text": "active (a: active)" }, { "code": null, "e": 27950, "s": 27871, "text": "Example 2: We can give different color to the links on change of their states." }, { "code": null, "e": 27955, "s": 27950, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!--Meta data--> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> h1 { color: #006600; text-align: center; } /* If the link is unvisited you see this color*/ a:link { color: #006600; text-decoration: none; } /* If the link is visited you see this color*/ a:visited { color: rgb(255, 105, 223); } /* On placing mouse over the link */ a:hover { color: rgb(128, 105, 255); text-decoration: underline; } /* If the click the link, you see this color*/ a:active { color: rgb(255, 105, 138); } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Click the links</p> <ul> <li><a href=\"https://www.geeksforgeeks.org/dbms/?ref=ghm\"> DBMS </a> </li> <li><a href=\"https://www.geeksforgeeks.org/computer-network-tutorials/?ref=ghm\"> Computer Networks</a> </li> <li> <a href=\"https://www.geeksforgeeks.org/operating-systems/?ref=ghm\"> Operating Systems</a> </li> <li><a href=\"https://www.geeksforgeeks.org/data-structures/?ref=ghm\"> Data Structures</a> </li> <li><a href=\"https://www.geeksforgeeks.org/\"> And many more</a> </li> </ul></body> </html>", "e": 29501, "s": 27955, "text": null }, { "code": null, "e": 29774, "s": 29501, "text": "Output: The unvisited and visited links have different colors. On placing the mouse over the second link, we see the change in color and style of the link. The order for placing a: hover must be after a: link and a: visited. The style a: active should come after a: hover." }, { "code": null, "e": 29927, "s": 29774, "text": "Example 3: The links can be further styled by applying different CSS properties like background-colour, font-size, font-style, text-decoration and many." }, { "code": null, "e": 29932, "s": 29927, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!--Meta data--> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> h1 { color: #006600; text-align: center; } a:link { color: #006600; text-decoration: none; } a:visited { color: rgb(255, 105, 223); } a:hover { color: white; text-decoration: underline; font-size: larger; font-style: italic; background-color:#006600; } a:active { color: rgb(255, 105, 138); } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click these links</p> <ul> <li><a href=\"https://www.geeksforgeeks.org/dbms/?ref=ghm\"> DBMS</a> </li> <li><a href=\"https://www.geeksforgeeks.org/computer-network-tutorials/?ref=ghm\"> Computer Networks</a> </li> <li> <a href=\"https://www.geeksforgeeks.org/operating-systems/?ref=ghm\"> Operating Systems</a> </li> <li><a href=\"https://www.geeksforgeeks.org/data-structures/?ref=ghm\"> Data Structures</a> </li> <li><a href=\"https://www.geeksforgeeks.org/\">And many more</a> </li> </ul></body> </html>", "e": 31338, "s": 29932, "text": null }, { "code": null, "e": 31346, "s": 31338, "text": "Output:" }, { "code": null, "e": 31483, "s": 31346, "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": 31498, "s": 31483, "text": "CSS-Properties" }, { "code": null, "e": 31512, "s": 31498, "text": "CSS-Questions" }, { "code": null, "e": 31519, "s": 31512, "text": "Picked" }, { "code": null, "e": 31523, "s": 31519, "text": "CSS" }, { "code": null, "e": 31528, "s": 31523, "text": "HTML" }, { "code": null, "e": 31545, "s": 31528, "text": "Web Technologies" }, { "code": null, "e": 31550, "s": 31545, "text": "HTML" }, { "code": null, "e": 31648, "s": 31550, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31687, "s": 31648, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31724, "s": 31687, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31753, "s": 31724, "text": "Form validation using jQuery" }, { "code": null, "e": 31788, "s": 31753, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 31830, "s": 31788, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31890, "s": 31830, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31943, "s": 31890, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32004, "s": 31943, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32028, "s": 32004, "text": "REST API (Introduction)" } ]
How to find Nth smallest value in vector in R ? - GeeksforGeeks
07 Apr, 2021 In this article, we will discuss how to find the Nth smallest in vector in the R programming language. Create vector Take input from the user using the function readline(). Convert data from string to int using the function as.integer(). In this step, we are finding nth largest number using Syntax: sort(vector name ) [n value]) Parameter: Vector name is the vector which we created. N value is which largest number you want to print. Example 1: R a<- c(1,3,4) x = readline();x = as.integer(x); print(sort(a)[x]) Output: [1] 1 Example 2: R a<- c(3453,39898,-997784) x = readline();x = as.integer(x); print(sort(a)[x]) Output: [1] 39898 R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n07 Apr, 2021" }, { "code": null, "e": 26590, "s": 26487, "text": "In this article, we will discuss how to find the Nth smallest in vector in the R programming language." }, { "code": null, "e": 26604, "s": 26590, "text": "Create vector" }, { "code": null, "e": 26660, "s": 26604, "text": "Take input from the user using the function readline()." }, { "code": null, "e": 26725, "s": 26660, "text": "Convert data from string to int using the function as.integer()." }, { "code": null, "e": 26779, "s": 26725, "text": "In this step, we are finding nth largest number using" }, { "code": null, "e": 26787, "s": 26779, "text": "Syntax:" }, { "code": null, "e": 26817, "s": 26787, "text": "sort(vector name ) [n value])" }, { "code": null, "e": 26828, "s": 26817, "text": "Parameter:" }, { "code": null, "e": 26872, "s": 26828, "text": "Vector name is the vector which we created." }, { "code": null, "e": 26923, "s": 26872, "text": "N value is which largest number you want to print." }, { "code": null, "e": 26934, "s": 26923, "text": "Example 1:" }, { "code": null, "e": 26936, "s": 26934, "text": "R" }, { "code": "a<- c(1,3,4) x = readline();x = as.integer(x); print(sort(a)[x])", "e": 27003, "s": 26936, "text": null }, { "code": null, "e": 27011, "s": 27003, "text": "Output:" }, { "code": null, "e": 27017, "s": 27011, "text": "[1] 1" }, { "code": null, "e": 27028, "s": 27017, "text": "Example 2:" }, { "code": null, "e": 27030, "s": 27028, "text": "R" }, { "code": "a<- c(3453,39898,-997784) x = readline();x = as.integer(x); print(sort(a)[x])", "e": 27110, "s": 27030, "text": null }, { "code": null, "e": 27118, "s": 27110, "text": "Output:" }, { "code": null, "e": 27128, "s": 27118, "text": "[1] 39898" }, { "code": null, "e": 27146, "s": 27128, "text": "R Vector-Programs" }, { "code": null, "e": 27156, "s": 27146, "text": "R-Vectors" }, { "code": null, "e": 27167, "s": 27156, "text": "R Language" }, { "code": null, "e": 27178, "s": 27167, "text": "R Programs" }, { "code": null, "e": 27276, "s": 27178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27328, "s": 27276, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27363, "s": 27328, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27401, "s": 27363, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27459, "s": 27401, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27502, "s": 27459, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27560, "s": 27502, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27603, "s": 27560, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27652, "s": 27603, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27702, "s": 27652, "text": "How to filter R dataframe by multiple conditions?" } ]
Count Divisors of Factorial - GeeksforGeeks
24 Sep, 2021 Given a number n, count the total number of divisors of n!. Examples: Input : n = 4Output: 8Explanation:4! is 24. Divisors of 24 are 1, 2, 3, 4, 6,8, 12 and 24. Input : n = 5Output : 16Explanation:5! is 120. Divisors of 120 are 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24 30, 40, 60 and 12 A Simple Solution is to first compute the factorial of the given number, then count the number of divisors of the factorial. This solution is not efficient and may cause overflow due to factorial computation.A better solution is based on Legendre’s formula. Below are the step: Find all prime numbers less than or equal to n (input number). We can use Sieve Algorithm for this. Let n be 6. All prime numbers less than 6 are {2, 3, 5}.For each prime number, p find the largest power of it that divides n!. We use Legendre’s formula for this purpose. The value of largest power that divides n! is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ...... Let these values be exp1, exp2, exp3,... Using the above formula, we get the below values for n = 6.The largest power of 2 that divides 6!, exp1 = 4.The largest power of 3 that divides 6!, exp2 = 2.The largest power of 5 that divides 6!, exp3 = 1.The result is (exp1 + 1) * (exp2 + 1) * (exp3 + 1) ... for all prime numbers, For n = 6, the values exp1, exp2, and exp3 are 4 2 and 1 respectively (computed in above step 2). So our result is (4 + 1)*(2 + 1) * (1 + 1) = 30 Find all prime numbers less than or equal to n (input number). We can use Sieve Algorithm for this. Let n be 6. All prime numbers less than 6 are {2, 3, 5}. For each prime number, p find the largest power of it that divides n!. We use Legendre’s formula for this purpose. The value of largest power that divides n! is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ...... Let these values be exp1, exp2, exp3,... Using the above formula, we get the below values for n = 6.The largest power of 2 that divides 6!, exp1 = 4.The largest power of 3 that divides 6!, exp2 = 2.The largest power of 5 that divides 6!, exp3 = 1. The largest power of 2 that divides 6!, exp1 = 4. The largest power of 3 that divides 6!, exp2 = 2. The largest power of 5 that divides 6!, exp3 = 1. The result is (exp1 + 1) * (exp2 + 1) * (exp3 + 1) ... for all prime numbers, For n = 6, the values exp1, exp2, and exp3 are 4 2 and 1 respectively (computed in above step 2). So our result is (4 + 1)*(2 + 1) * (1 + 1) = 30 Below is the implementation of the above idea. C++ Java Python3 C# PHP Javascript // C++ program to find count of divisors in n!#include<bits/stdc++.h>using namespace std;typedef unsigned long long int ull; // allPrimes[] stores all prime numbers less// than or equal to n.vector<ull> allPrimes; // Fills above vector allPrimes[] for a given nvoid sieve(int n){ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. vector<bool> prime(n+1, true); // Loop to update prime[] for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (int p=2; p<=n; p++) if (prime[p]) allPrimes.push_back(p);} // Function to find all result of factorial numberull factorialDivisors(ull n){ sieve(n); // create sieve // Initialize result ull result = 1; // find exponents of all primes which divides n // and less than n for (int i=0; i < allPrimes.size(); i++) { // Current divisor ull p = allPrimes[i]; // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. ull exp = 0; while (p <= n) { exp = exp + (n/p); p = p*allPrimes[i]; } // Multiply exponents of all primes less // than n result = result*(exp+1); } // return total divisors return result;} // Driver codeint main(){ cout << factorialDivisors(6); return 0;} // JAVA program to find count of divisors in n! import java.util.*;class GFG{ // allPrimes[] stores all prime numbers less // than or equal to n. static Vector<Integer> allPrimes=new Vector<Integer>(); // Fills above vector allPrimes[] for a given n static void sieve(int n){ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. boolean []prime=new boolean[n+1]; for(int i=0;i<=n;i++) prime[i]=true; // Loop to update prime[] for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (int p=2; p<=n; p++) if (prime[p]) allPrimes.add(p); } // Function to find all result of factorial number static long factorialDivisors(int n) { sieve(n); // create sieve // Initialize result long result = 1; // find exponents of all primes which divides n // and less than n for (int i=0; i < allPrimes.size(); i++) { // Current divisor long p = allPrimes.get(i); // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. long exp = 0; while (p <= n) { exp = exp + (n/p); p = p*allPrimes.get(i); } // Multiply exponents of all primes less // than n result = result*(exp+1); } // return total divisors return result; } // Driver code public static void main(String []args) { System.out.println(factorialDivisors(6)); } } //This code is contributed by ihritik # Python3 program to find count# of divisors in n! # allPrimes[] stores all prime# numbers less than or equal to n.allPrimes = []; # Fills above vector allPrimes[]# for a given ndef sieve(n): # Create a boolean array "prime[0..n]" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is not a prime, else true. prime = [True] * (n + 1); # Loop to update prime[] p = 2; while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p i = p * 2; while(i <= n): prime[i] = False; i += p; p += 1; # Store primes in the vector allPrimes for p in range(2, n + 1): if (prime[p]): allPrimes.append(p); # Function to find all result of# factorial numberdef factorialDivisors(n): sieve(n); # create sieve # Initialize result result = 1; # find exponents of all primes # which divides n and less than n for i in range(len(allPrimes)): # Current divisor p = allPrimes[i]; # Find the highest power (stored in exp)' # of allPrimes[i] that divides n using # Legendre's formula. exp = 0; while (p <= n): exp = exp + int(n / p); p = p * allPrimes[i]; # Multiply exponents of all # primes less than n result = result * (exp + 1); # return total divisors return result; # Driver Codeprint(factorialDivisors(6)); # This code is contributed by mits // C# program to find count of divisors in n!using System;using System.Collections; class GFG{ // allPrimes[] stores all prime numbers less // than or equal to n. static ArrayList allPrimes = new ArrayList(); // Fills above vector allPrimes[] for a given n static void sieve(int n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. bool[] prime = new bool[n+1]; for(int i = 0; i <= n; i++) prime[i] = true; // Loop to update prime[] for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.Add(p); } // Function to find all result of factorial number static int factorialDivisors(int n) { sieve(n); // create sieve // Initialize result int result = 1; // find exponents of all primes which divides n // and less than n for (int i = 0; i < allPrimes.Count; i++) { // Current divisor int p = (int)allPrimes[i]; // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. int exp = 0; while (p <= n) { exp = exp + (n / p); p = p * (int)allPrimes[i]; } // Multiply exponents of all primes less // than n result = result * (exp + 1); } // return total divisors return result; } // Driver code public static void Main() { Console.WriteLine(factorialDivisors(6)); }} //This code is contributed by chandan_jnu <?php// PHP program to find count of// divisors in n! // allPrimes[] stores all prime numbers// less than or equal to n.$allPrimes = array(); // Fills above vector allPrimes[]// for a given nfunction sieve($n){ global $allPrimes; // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. $prime = array_fill(0, $n + 1, true); // Loop to update prime[] for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Store primes in the vector allPrimes for ($p = 2; $p <= $n; $p++) if ($prime[$p]) array_push($allPrimes, $p);} // Function to find all result// of factorial numberfunction factorialDivisors($n){ global $allPrimes; sieve($n); // create sieve // Initialize result $result = 1; // find exponents of all primes // which divides n and less than n for ($i = 0; $i < count($allPrimes); $i++) { // Current divisor $p = $allPrimes[$i]; // Find the highest power (stored in exp) // of allPrimes[i] that divides n using // Legendre's formula. $exp = 0; while ($p <= $n) { $exp = $exp + (int)($n / $p); $p = $p * $allPrimes[$i]; } // Multiply exponents of all primes // less than n $result = $result * ($exp + 1); } // return total divisors return $result;} // Driver Codeecho factorialDivisors(6); // This code is contributed by mits?> <script> // JavaScript program to find count of divisors in n! // allPrimes[] stores all prime numbers less // than or equal to n. let allPrimes = []; // Fills above vector allPrimes[] for a given n function sieve(n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. let prime = new Array(n+1); for(let i = 0; i <= n; i++) prime[i] = true; // Loop to update prime[] for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p*2; i <= n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (let p = 2; p <= n; p++) if (prime[p]) allPrimes.push(p); } // Function to find all result of factorial number function factorialDivisors(n) { sieve(n); // create sieve // Initialize result let result = 1; // find exponents of all primes which divides n // and less than n for (let i = 0; i < allPrimes.length; i++) { // Current divisor let p = allPrimes[i]; // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. let exp = 0; while (p <= n) { exp = exp + parseInt(n / p, 10); p = p * allPrimes[i]; } // Multiply exponents of all primes less // than n result = result * (exp + 1); } // return total divisors return result; } document.write(factorialDivisors(6)); </script> 30 This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team GeeksforGeeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ihritik Mithun Kumar Chandan_Kumar yashbeersingh42 mukesh07 prithvirajpatil2511 divisors factorial Prime Number prime-factor sieve Mathematical Mathematical Prime Number sieve factorial 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 Operators in C / C++ Program for factorial of a number The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Program for Decimal to Binary Conversion Program to find sum of elements in a given array
[ { "code": null, "e": 26091, "s": 26063, "text": "\n24 Sep, 2021" }, { "code": null, "e": 26151, "s": 26091, "text": "Given a number n, count the total number of divisors of n!." }, { "code": null, "e": 26162, "s": 26151, "text": "Examples: " }, { "code": null, "e": 26253, "s": 26162, "text": "Input : n = 4Output: 8Explanation:4! is 24. Divisors of 24 are 1, 2, 3, 4, 6,8, 12 and 24." }, { "code": null, "e": 26379, "s": 26253, "text": "Input : n = 5Output : 16Explanation:5! is 120. Divisors of 120 are 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24 30, 40, 60 and 12 " }, { "code": null, "e": 26657, "s": 26379, "text": "A Simple Solution is to first compute the factorial of the given number, then count the number of divisors of the factorial. This solution is not efficient and may cause overflow due to factorial computation.A better solution is based on Legendre’s formula. Below are the step:" }, { "code": null, "e": 27482, "s": 26657, "text": "Find all prime numbers less than or equal to n (input number). We can use Sieve Algorithm for this. Let n be 6. All prime numbers less than 6 are {2, 3, 5}.For each prime number, p find the largest power of it that divides n!. We use Legendre’s formula for this purpose. The value of largest power that divides n! is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ...... Let these values be exp1, exp2, exp3,... Using the above formula, we get the below values for n = 6.The largest power of 2 that divides 6!, exp1 = 4.The largest power of 3 that divides 6!, exp2 = 2.The largest power of 5 that divides 6!, exp3 = 1.The result is (exp1 + 1) * (exp2 + 1) * (exp3 + 1) ... for all prime numbers, For n = 6, the values exp1, exp2, and exp3 are 4 2 and 1 respectively (computed in above step 2). So our result is (4 + 1)*(2 + 1) * (1 + 1) = 30" }, { "code": null, "e": 27639, "s": 27482, "text": "Find all prime numbers less than or equal to n (input number). We can use Sieve Algorithm for this. Let n be 6. All prime numbers less than 6 are {2, 3, 5}." }, { "code": null, "e": 28085, "s": 27639, "text": "For each prime number, p find the largest power of it that divides n!. We use Legendre’s formula for this purpose. The value of largest power that divides n! is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ...... Let these values be exp1, exp2, exp3,... Using the above formula, we get the below values for n = 6.The largest power of 2 that divides 6!, exp1 = 4.The largest power of 3 that divides 6!, exp2 = 2.The largest power of 5 that divides 6!, exp3 = 1." }, { "code": null, "e": 28135, "s": 28085, "text": "The largest power of 2 that divides 6!, exp1 = 4." }, { "code": null, "e": 28185, "s": 28135, "text": "The largest power of 3 that divides 6!, exp2 = 2." }, { "code": null, "e": 28235, "s": 28185, "text": "The largest power of 5 that divides 6!, exp3 = 1." }, { "code": null, "e": 28459, "s": 28235, "text": "The result is (exp1 + 1) * (exp2 + 1) * (exp3 + 1) ... for all prime numbers, For n = 6, the values exp1, exp2, and exp3 are 4 2 and 1 respectively (computed in above step 2). So our result is (4 + 1)*(2 + 1) * (1 + 1) = 30" }, { "code": null, "e": 28507, "s": 28459, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 28511, "s": 28507, "text": "C++" }, { "code": null, "e": 28516, "s": 28511, "text": "Java" }, { "code": null, "e": 28524, "s": 28516, "text": "Python3" }, { "code": null, "e": 28527, "s": 28524, "text": "C#" }, { "code": null, "e": 28531, "s": 28527, "text": "PHP" }, { "code": null, "e": 28542, "s": 28531, "text": "Javascript" }, { "code": "// C++ program to find count of divisors in n!#include<bits/stdc++.h>using namespace std;typedef unsigned long long int ull; // allPrimes[] stores all prime numbers less// than or equal to n.vector<ull> allPrimes; // Fills above vector allPrimes[] for a given nvoid sieve(int n){ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. vector<bool> prime(n+1, true); // Loop to update prime[] for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (int p=2; p<=n; p++) if (prime[p]) allPrimes.push_back(p);} // Function to find all result of factorial numberull factorialDivisors(ull n){ sieve(n); // create sieve // Initialize result ull result = 1; // find exponents of all primes which divides n // and less than n for (int i=0; i < allPrimes.size(); i++) { // Current divisor ull p = allPrimes[i]; // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. ull exp = 0; while (p <= n) { exp = exp + (n/p); p = p*allPrimes[i]; } // Multiply exponents of all primes less // than n result = result*(exp+1); } // return total divisors return result;} // Driver codeint main(){ cout << factorialDivisors(6); return 0;}", "e": 30262, "s": 28542, "text": null }, { "code": "// JAVA program to find count of divisors in n! import java.util.*;class GFG{ // allPrimes[] stores all prime numbers less // than or equal to n. static Vector<Integer> allPrimes=new Vector<Integer>(); // Fills above vector allPrimes[] for a given n static void sieve(int n){ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. boolean []prime=new boolean[n+1]; for(int i=0;i<=n;i++) prime[i]=true; // Loop to update prime[] for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (int p=2; p<=n; p++) if (prime[p]) allPrimes.add(p); } // Function to find all result of factorial number static long factorialDivisors(int n) { sieve(n); // create sieve // Initialize result long result = 1; // find exponents of all primes which divides n // and less than n for (int i=0; i < allPrimes.size(); i++) { // Current divisor long p = allPrimes.get(i); // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. long exp = 0; while (p <= n) { exp = exp + (n/p); p = p*allPrimes.get(i); } // Multiply exponents of all primes less // than n result = result*(exp+1); } // return total divisors return result; } // Driver code public static void main(String []args) { System.out.println(factorialDivisors(6)); } } //This code is contributed by ihritik", "e": 32548, "s": 30262, "text": null }, { "code": "# Python3 program to find count# of divisors in n! # allPrimes[] stores all prime# numbers less than or equal to n.allPrimes = []; # Fills above vector allPrimes[]# for a given ndef sieve(n): # Create a boolean array \"prime[0..n]\" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is not a prime, else true. prime = [True] * (n + 1); # Loop to update prime[] p = 2; while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p i = p * 2; while(i <= n): prime[i] = False; i += p; p += 1; # Store primes in the vector allPrimes for p in range(2, n + 1): if (prime[p]): allPrimes.append(p); # Function to find all result of# factorial numberdef factorialDivisors(n): sieve(n); # create sieve # Initialize result result = 1; # find exponents of all primes # which divides n and less than n for i in range(len(allPrimes)): # Current divisor p = allPrimes[i]; # Find the highest power (stored in exp)' # of allPrimes[i] that divides n using # Legendre's formula. exp = 0; while (p <= n): exp = exp + int(n / p); p = p * allPrimes[i]; # Multiply exponents of all # primes less than n result = result * (exp + 1); # return total divisors return result; # Driver Codeprint(factorialDivisors(6)); # This code is contributed by mits", "e": 34167, "s": 32548, "text": null }, { "code": "// C# program to find count of divisors in n!using System;using System.Collections; class GFG{ // allPrimes[] stores all prime numbers less // than or equal to n. static ArrayList allPrimes = new ArrayList(); // Fills above vector allPrimes[] for a given n static void sieve(int n) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. bool[] prime = new bool[n+1]; for(int i = 0; i <= n; i++) prime[i] = true; // Loop to update prime[] for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (int p = 2; p <= n; p++) if (prime[p]) allPrimes.Add(p); } // Function to find all result of factorial number static int factorialDivisors(int n) { sieve(n); // create sieve // Initialize result int result = 1; // find exponents of all primes which divides n // and less than n for (int i = 0; i < allPrimes.Count; i++) { // Current divisor int p = (int)allPrimes[i]; // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. int exp = 0; while (p <= n) { exp = exp + (n / p); p = p * (int)allPrimes[i]; } // Multiply exponents of all primes less // than n result = result * (exp + 1); } // return total divisors return result; } // Driver code public static void Main() { Console.WriteLine(factorialDivisors(6)); }} //This code is contributed by chandan_jnu", "e": 36474, "s": 34167, "text": null }, { "code": "<?php// PHP program to find count of// divisors in n! // allPrimes[] stores all prime numbers// less than or equal to n.$allPrimes = array(); // Fills above vector allPrimes[]// for a given nfunction sieve($n){ global $allPrimes; // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. $prime = array_fill(0, $n + 1, true); // Loop to update prime[] for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Store primes in the vector allPrimes for ($p = 2; $p <= $n; $p++) if ($prime[$p]) array_push($allPrimes, $p);} // Function to find all result// of factorial numberfunction factorialDivisors($n){ global $allPrimes; sieve($n); // create sieve // Initialize result $result = 1; // find exponents of all primes // which divides n and less than n for ($i = 0; $i < count($allPrimes); $i++) { // Current divisor $p = $allPrimes[$i]; // Find the highest power (stored in exp) // of allPrimes[i] that divides n using // Legendre's formula. $exp = 0; while ($p <= $n) { $exp = $exp + (int)($n / $p); $p = $p * $allPrimes[$i]; } // Multiply exponents of all primes // less than n $result = $result * ($exp + 1); } // return total divisors return $result;} // Driver Codeecho factorialDivisors(6); // This code is contributed by mits?>", "e": 38241, "s": 36474, "text": null }, { "code": "<script> // JavaScript program to find count of divisors in n! // allPrimes[] stores all prime numbers less // than or equal to n. let allPrimes = []; // Fills above vector allPrimes[] for a given n function sieve(n) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // not a prime, else true. let prime = new Array(n+1); for(let i = 0; i <= n; i++) prime[i] = true; // Loop to update prime[] for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p*2; i <= n; i += p) prime[i] = false; } } // Store primes in the vector allPrimes for (let p = 2; p <= n; p++) if (prime[p]) allPrimes.push(p); } // Function to find all result of factorial number function factorialDivisors(n) { sieve(n); // create sieve // Initialize result let result = 1; // find exponents of all primes which divides n // and less than n for (let i = 0; i < allPrimes.length; i++) { // Current divisor let p = allPrimes[i]; // Find the highest power (stored in exp)' // of allPrimes[i] that divides n using // Legendre's formula. let exp = 0; while (p <= n) { exp = exp + parseInt(n / p, 10); p = p * allPrimes[i]; } // Multiply exponents of all primes less // than n result = result * (exp + 1); } // return total divisors return result; } document.write(factorialDivisors(6)); </script>", "e": 40135, "s": 38241, "text": null }, { "code": null, "e": 40138, "s": 40135, "text": "30" }, { "code": null, "e": 40369, "s": 40138, "text": "This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team GeeksforGeeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 40377, "s": 40369, "text": "ihritik" }, { "code": null, "e": 40390, "s": 40377, "text": "Mithun Kumar" }, { "code": null, "e": 40404, "s": 40390, "text": "Chandan_Kumar" }, { "code": null, "e": 40420, "s": 40404, "text": "yashbeersingh42" }, { "code": null, "e": 40429, "s": 40420, "text": "mukesh07" }, { "code": null, "e": 40449, "s": 40429, "text": "prithvirajpatil2511" }, { "code": null, "e": 40458, "s": 40449, "text": "divisors" }, { "code": null, "e": 40468, "s": 40458, "text": "factorial" }, { "code": null, "e": 40481, "s": 40468, "text": "Prime Number" }, { "code": null, "e": 40494, "s": 40481, "text": "prime-factor" }, { "code": null, "e": 40500, "s": 40494, "text": "sieve" }, { "code": null, "e": 40513, "s": 40500, "text": "Mathematical" }, { "code": null, "e": 40526, "s": 40513, "text": "Mathematical" }, { "code": null, "e": 40539, "s": 40526, "text": "Prime Number" }, { "code": null, "e": 40545, "s": 40539, "text": "sieve" }, { "code": null, "e": 40555, "s": 40545, "text": "factorial" }, { "code": null, "e": 40653, "s": 40555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40677, "s": 40653, "text": "Merge two sorted arrays" }, { "code": null, "e": 40720, "s": 40677, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 40734, "s": 40720, "text": "Prime Numbers" }, { "code": null, "e": 40807, "s": 40734, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 40828, "s": 40807, "text": "Operators in C / C++" }, { "code": null, "e": 40862, "s": 40828, "text": "Program for factorial of a number" }, { "code": null, "e": 40905, "s": 40862, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 40958, "s": 40905, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 40999, "s": 40958, "text": "Program for Decimal to Binary Conversion" } ]
Perl | Reading Excel Files - GeeksforGeeks
11 Jul, 2019 Excel sheets are one of the most commonly used methods for maintaining office records, especially to work on applications where non-developers and even managers can provide input to the systems in batches. However, the issue is to read the content from a file created by Microsoft Excel using Perl. Few modules for reading from Excel files are offered by CPAN. There is Spreadsheet::Read that will be able to handle all types of spreadsheets. There are other low-level libraries reading files by different versions of Excel: Spreadsheet::ParseExcel Excel 95-2003 files, Spreadsheet::ParseXLSX Excel 2007 Open XML XLSX Excel files can be created with the use of Perl by the help of an inbuilt module Excel::Writer::XLSX which is used to create Excel files.Further, write() function is used to add content to the excel file.Example: #!/usr/bin/perluse Excel::Writer::XLSX;my $Excel_book1 = Excel::Writer::XLSX->new('new_excel.xlsx' );my $Excel_sheet1 = $Excel_book1->add_worksheet();my @data_row = (1, 2, 3, 4);my @table_data = ( ["l", "m"], ["n", "o"], ["p", "q"],);my @data_column = (1, 2, 3, 4, 5, 6, 7); # Using write() to write values in sheet$Excel_sheet1->write( "A1", "Geeks For Geeks" );$Excel_sheet1->write( "A2", "Perl|Reading Files in Excel" );$Excel_sheet1->write( "A3", \@data_row );$Excel_sheet1->write( 4, 0, \@table_data );$Excel_sheet1->write( 0, 4, [ \@data_column ] );$Excel_book1->close; Reading of an Excel File in Perl is done by using Spreadsheet::Read module in a Perl script. This module exports a number of function that you either import or use in your Perl code script. ReadData() function is used to read from an excel file.The ReadData() function accepts a filename which in this case is an Excel file, but it also accepts various other file types. Based on the file-extension, it will load the appropriate back-end module, then parses the file. It creates an array reference which represents the whole file:Example: use 5.016;use Spreadsheet::Read qw(ReadData);my $book_data = ReadData (‘new_excel.xlsx');say 'A2: ' . $book_data->[1]{A2}; In the above code, the first element of the array which has been returned contains general information about the file. The remaining elements represent the other sheets in the file. In other words, $book_data->[1] represents the first sheet of the ‘new_excel.xlsx’. This can be used to access the content of the cells as it is a hash reference. $book_data->[1]{A2} returns a hash reference for A2 element Output: A2: Perl|Reading Files in Excel The arguments of the function of Spreadsheet::Read are a sheet, and the number of the rows to be fetched. The return type is an array with the values of the rows passed in the argument.The following program demonstrates how to read the first row of the first sheet, and then displays the content in each field of the row. my @rowsingle = Spreadsheet::Read::row($book_data->[1], 1);for my $i (0 .. $#rowsingle){ say 'A' . ($i + 1) . ' ' . ($rowsingle[$i] // '');} Output: Fetching a single row is not nearly enough. We need to fetch all the rows for efficient programming. We accomplish this using the rows() function. This function takes a sheet as an argument. It returns an array of elements or array of references as a matrix(2-D array). Each element in the matrix represents a row in the spreadsheet.The script to fetch all rows is as follows: my @rowsmulti = Spreadsheet::Read::rows($book_data->[1]);foreach my $m (1 .. scalar @rowsmulti) { foreach my $n (1 .. scalar @{$rowsmulti[$m - 1]}) { say chr(64 + $m) . " $m " . ($rowsmulti[$m - 1][$n - 1] // ''); }} Output: Putting it all togetherFollowing Perl script illustrates the use of all the above explained Features of Reading an Excel File in Perl: #!/usr/bin/perluse strict;use warnings;use 5.010; use Spreadsheet::Read qw(ReadData); my $bookdata = ReadData('simplecreate.xlsx'); say 'A1: ' . $bookdata->[1]{A1}; # Fetching a single rowmy @rowsingle = Spreadsheet::Read::row($bookdata->[1], 1);for my $i (0 .. $#row) { say 'A' . ($i + 1) . ' ' . ($rowsingle[$i] // '');} # Fetching all file contentmy @rowsmulti = Spreadsheet::Read::rows($bookdata->[1]);foreach my $i (1 .. scalar @rowsmulti) { foreach my $j (1 .. scalar @{$rows[$i-1]}) { say chr(64 + $i) . " $j " . ($rows[$i - 1][$j - 1] // ''); }} OutPut: Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | grep() Function Perl | Regular Expressions Perl | Polymorphism in OOPs Perl Tutorial - Learn Perl With Examples Perl | length() Function Perl | Basic Syntax of a Perl Program Perl | substitution Operator Perl | Regex Cheat Sheet Perl | Boolean Values Perl | sleep() Function
[ { "code": null, "e": 25227, "s": 25199, "text": "\n11 Jul, 2019" }, { "code": null, "e": 25433, "s": 25227, "text": "Excel sheets are one of the most commonly used methods for maintaining office records, especially to work on applications where non-developers and even managers can provide input to the systems in batches." }, { "code": null, "e": 25526, "s": 25433, "text": "However, the issue is to read the content from a file created by Microsoft Excel using Perl." }, { "code": null, "e": 25752, "s": 25526, "text": "Few modules for reading from Excel files are offered by CPAN. There is Spreadsheet::Read that will be able to handle all types of spreadsheets. There are other low-level libraries reading files by different versions of Excel:" }, { "code": null, "e": 25797, "s": 25752, "text": "Spreadsheet::ParseExcel Excel 95-2003 files," }, { "code": null, "e": 25845, "s": 25797, "text": "Spreadsheet::ParseXLSX Excel 2007 Open XML XLSX" }, { "code": null, "e": 26058, "s": 25845, "text": "Excel files can be created with the use of Perl by the help of an inbuilt module Excel::Writer::XLSX which is used to create Excel files.Further, write() function is used to add content to the excel file.Example:" }, { "code": "#!/usr/bin/perluse Excel::Writer::XLSX;my $Excel_book1 = Excel::Writer::XLSX->new('new_excel.xlsx' );my $Excel_sheet1 = $Excel_book1->add_worksheet();my @data_row = (1, 2, 3, 4);my @table_data = ( [\"l\", \"m\"], [\"n\", \"o\"], [\"p\", \"q\"],);my @data_column = (1, 2, 3, 4, 5, 6, 7); # Using write() to write values in sheet$Excel_sheet1->write( \"A1\", \"Geeks For Geeks\" );$Excel_sheet1->write( \"A2\", \"Perl|Reading Files in Excel\" );$Excel_sheet1->write( \"A3\", \\@data_row );$Excel_sheet1->write( 4, 0, \\@table_data );$Excel_sheet1->write( 0, 4, [ \\@data_column ] );$Excel_book1->close;", "e": 26645, "s": 26058, "text": null }, { "code": null, "e": 27186, "s": 26647, "text": "Reading of an Excel File in Perl is done by using Spreadsheet::Read module in a Perl script. This module exports a number of function that you either import or use in your Perl code script. ReadData() function is used to read from an excel file.The ReadData() function accepts a filename which in this case is an Excel file, but it also accepts various other file types. Based on the file-extension, it will load the appropriate back-end module, then parses the file. It creates an array reference which represents the whole file:Example:" }, { "code": "use 5.016;use Spreadsheet::Read qw(ReadData);my $book_data = ReadData (‘new_excel.xlsx');say 'A2: ' . $book_data->[1]{A2};", "e": 27309, "s": 27186, "text": null }, { "code": null, "e": 27714, "s": 27309, "text": "In the above code, the first element of the array which has been returned contains general information about the file. The remaining elements represent the other sheets in the file. In other words, $book_data->[1] represents the first sheet of the ‘new_excel.xlsx’. This can be used to access the content of the cells as it is a hash reference. $book_data->[1]{A2} returns a hash reference for A2 element" }, { "code": null, "e": 27722, "s": 27714, "text": "Output:" }, { "code": null, "e": 27754, "s": 27722, "text": "A2: Perl|Reading Files in Excel" }, { "code": null, "e": 28076, "s": 27754, "text": "The arguments of the function of Spreadsheet::Read are a sheet, and the number of the rows to be fetched. The return type is an array with the values of the rows passed in the argument.The following program demonstrates how to read the first row of the first sheet, and then displays the content in each field of the row." }, { "code": "my @rowsingle = Spreadsheet::Read::row($book_data->[1], 1);for my $i (0 .. $#rowsingle){ say 'A' . ($i + 1) . ' ' . ($rowsingle[$i] // '');}", "e": 28234, "s": 28076, "text": null }, { "code": null, "e": 28242, "s": 28234, "text": "Output:" }, { "code": null, "e": 28619, "s": 28242, "text": "Fetching a single row is not nearly enough. We need to fetch all the rows for efficient programming. We accomplish this using the rows() function. This function takes a sheet as an argument. It returns an array of elements or array of references as a matrix(2-D array). Each element in the matrix represents a row in the spreadsheet.The script to fetch all rows is as follows:" }, { "code": "my @rowsmulti = Spreadsheet::Read::rows($book_data->[1]);foreach my $m (1 .. scalar @rowsmulti) { foreach my $n (1 .. scalar @{$rowsmulti[$m - 1]}) { say chr(64 + $m) . \" $m \" . ($rowsmulti[$m - 1][$n - 1] // ''); }}", "e": 28867, "s": 28619, "text": null }, { "code": null, "e": 28875, "s": 28867, "text": "Output:" }, { "code": null, "e": 29010, "s": 28875, "text": "Putting it all togetherFollowing Perl script illustrates the use of all the above explained Features of Reading an Excel File in Perl:" }, { "code": "#!/usr/bin/perluse strict;use warnings;use 5.010; use Spreadsheet::Read qw(ReadData); my $bookdata = ReadData('simplecreate.xlsx'); say 'A1: ' . $bookdata->[1]{A1}; # Fetching a single rowmy @rowsingle = Spreadsheet::Read::row($bookdata->[1], 1);for my $i (0 .. $#row) { say 'A' . ($i + 1) . ' ' . ($rowsingle[$i] // '');} # Fetching all file contentmy @rowsmulti = Spreadsheet::Read::rows($bookdata->[1]);foreach my $i (1 .. scalar @rowsmulti) { foreach my $j (1 .. scalar @{$rows[$i-1]}) { say chr(64 + $i) . \" $j \" . ($rows[$i - 1][$j - 1] // ''); }}", "e": 29619, "s": 29010, "text": null }, { "code": null, "e": 29627, "s": 29619, "text": "OutPut:" }, { "code": null, "e": 29634, "s": 29627, "text": "Picked" }, { "code": null, "e": 29639, "s": 29634, "text": "Perl" }, { "code": null, "e": 29644, "s": 29639, "text": "Perl" }, { "code": null, "e": 29742, "s": 29644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29765, "s": 29742, "text": "Perl | grep() Function" }, { "code": null, "e": 29792, "s": 29765, "text": "Perl | Regular Expressions" }, { "code": null, "e": 29820, "s": 29792, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 29861, "s": 29820, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 29886, "s": 29861, "text": "Perl | length() Function" }, { "code": null, "e": 29924, "s": 29886, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 29953, "s": 29924, "text": "Perl | substitution Operator" }, { "code": null, "e": 29978, "s": 29953, "text": "Perl | Regex Cheat Sheet" }, { "code": null, "e": 30000, "s": 29978, "text": "Perl | Boolean Values" } ]
How to change selected value of a drop-down list using jQuery? - GeeksforGeeks
03 Aug, 2021 With jQuery, it is easy to writing one line of code to change the selected value from a drop-down list. Suppose, you have a select element and you need to select one of its options based on one of its values. To achieve this feat you can use various methods, two of those methods will be explained below. Used Function: val() function: It sets or returns the value attribute of the selected elements. attr() function: It sets or returns the attributes and values of the selected elements. Example 1: This example uses val() function to set the option corresponding to the passed value. <!DOCTYPE html><html> <head> <title> Change selected value of a drop-down list </title> <style> div { width:15%; background-color:green; padding:8px; color:azure; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(()=>{ $("#select").val('2'); }); </script></head> <body> <div> <p id="gfg">GeeksforGeeks courses:</p> <select id="select"> <option value="0">System Design</option> <option value="1">DSA-Online</option> <option value="2">Fork Python</option> <option value="3">Fork Java</option> </select> </div></body> </html> Output: Example 2: This example uses attr() function to assign the selected attribute to the corresponding option. <!DOCTYPE html><html> <head> <title> Change selected value of a drop-down list </title> <style> div { width:15%; background-color:green; padding:8px; color:azure; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(()=>{ $("#select option[value=3]").attr('selected', 'selected'); }); </script></head> <body> <div> <p id="gfg">GeeksforGeeks courses:</p> <select id="select"> <option value="0">System Design</option> <option value="1">DSA-Online</option> <option value="2">Fork Python</option> <option value="3">Fork Java</option> </select> </div></body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Misc Picked JavaScript JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request JQuery | Set the value of an input text field Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 26412, "s": 26384, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26717, "s": 26412, "text": "With jQuery, it is easy to writing one line of code to change the selected value from a drop-down list. Suppose, you have a select element and you need to select one of its options based on one of its values. To achieve this feat you can use various methods, two of those methods will be explained below." }, { "code": null, "e": 26732, "s": 26717, "text": "Used Function:" }, { "code": null, "e": 26813, "s": 26732, "text": "val() function: It sets or returns the value attribute of the selected elements." }, { "code": null, "e": 26901, "s": 26813, "text": "attr() function: It sets or returns the attributes and values of the selected elements." }, { "code": null, "e": 26998, "s": 26901, "text": "Example 1: This example uses val() function to set the option corresponding to the passed value." }, { "code": "<!DOCTYPE html><html> <head> <title> Change selected value of a drop-down list </title> <style> div { width:15%; background-color:green; padding:8px; color:azure; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(()=>{ $(\"#select\").val('2'); }); </script></head> <body> <div> <p id=\"gfg\">GeeksforGeeks courses:</p> <select id=\"select\"> <option value=\"0\">System Design</option> <option value=\"1\">DSA-Online</option> <option value=\"2\">Fork Python</option> <option value=\"3\">Fork Java</option> </select> </div></body> </html> ", "e": 27913, "s": 26998, "text": null }, { "code": null, "e": 27921, "s": 27913, "text": "Output:" }, { "code": null, "e": 28028, "s": 27921, "text": "Example 2: This example uses attr() function to assign the selected attribute to the corresponding option." }, { "code": "<!DOCTYPE html><html> <head> <title> Change selected value of a drop-down list </title> <style> div { width:15%; background-color:green; padding:8px; color:azure; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(()=>{ $(\"#select option[value=3]\").attr('selected', 'selected'); }); </script></head> <body> <div> <p id=\"gfg\">GeeksforGeeks courses:</p> <select id=\"select\"> <option value=\"0\">System Design</option> <option value=\"1\">DSA-Online</option> <option value=\"2\">Fork Python</option> <option value=\"3\">Fork Java</option> </select> </div></body> </html> ", "e": 28976, "s": 28028, "text": null }, { "code": null, "e": 28984, "s": 28976, "text": "Output:" }, { "code": null, "e": 29252, "s": 28984, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 29264, "s": 29252, "text": "jQuery-Misc" }, { "code": null, "e": 29271, "s": 29264, "text": "Picked" }, { "code": null, "e": 29282, "s": 29271, "text": "JavaScript" }, { "code": null, "e": 29289, "s": 29282, "text": "JQuery" }, { "code": null, "e": 29306, "s": 29289, "text": "Web Technologies" }, { "code": null, "e": 29333, "s": 29306, "text": "Web technologies Questions" }, { "code": null, "e": 29431, "s": 29333, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29471, "s": 29431, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29516, "s": 29471, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29577, "s": 29516, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29649, "s": 29577, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29690, "s": 29649, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29736, "s": 29690, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 29765, "s": 29736, "text": "Form validation using jQuery" }, { "code": null, "e": 29842, "s": 29765, "text": "How to change the background color after clicking the button in JavaScript ?" }, { "code": null, "e": 29916, "s": 29842, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" } ]
Populating a Network Graph with Named-Entities | by Ednalyn C. De Dios | Towards Data Science
I do a lot of natural language processing and usually, the results are pretty boring to the eye. When I learned about network graphs, it got me thinking, why not use keywords as nodes and connect them together to create a network graph? Yupp, why not! In this post, we’ll do exactly that. We’re going to extract named-entities from news articles about coronavirus and then use their relationships to connect them together in a network graph. Network graphs are a cool visual that contains nodes (vertices) and edges (lines). It’s often used in social network analysis and network analysis but data scientists also use it for natural language processing. Natural Language Processing or NLP is a branch of artificial intelligence that deals with programming computers to process and analyze large volumes of text and derive meaning out of them.1 In other words, it’s all about teaching computers how to understand human language... like a boss! Enough introduction, let’s get to coding! To get started, let’s make sure to take care of all dependencies. Open up a terminal and execute the following commands: pip install -U spacypython -m spacy download enpip install networkxpip install fuzzywuzzy This will install spaCy and download the trained model for English. The third command installs networkx. This should work for most systems. If it doesn’t work for you, check out the documentation for spaCy and networkx. Also, we’re using fuzzywuzzy for some text preprocessing. With that out of the way, let’s fire up a Jupyter notebook and get started! Run the following code block into a cell to get all the necessary imports into our Python environment. import pandas as pdimport numpy as npimport picklefrom operator import itemgetterfrom fuzzywuzzy import process, fuzz# for natural language processingimport spacyimport en_core_web_sm# for visualizations%matplotlib inlinefrom matplotlib.pyplot import figureimport networkx as nx If you want to follow along, you can download the sample dataset here. The file was created using newspaper to import news articles from the npr.org. If you’re feeling adventurous, use the code snippet below to build your own dataset. Let’s get our data. with open('npr_coronavirus.txt', 'rb') as fp: # Unpickling corpus = pickle.load(fp) Next, we’ll start by loading spaCy’s English model: nlp = en_core_web_sm.load() Then, we’ll extract the entities: entities = []for article in corpus[:50]: tokens = nlp(''.join(article)) gpe_list = [] for ent in tokens.ents: if ent.label_ == 'GPE': gpe_list.append(ent.text) entities.append(gpe_list) In the above code block, we created an empty list called entities to store a list of lists that contains the extracted entities from each of the articles. In the for-loop, we looped through the first 50 articles of the corpus. For each iteration, we converted each articles into tokens (words) and then we looped through all those words to get the entities that are labeled as GPE for countries, states, and cities. We used ent.text to extract the actual entity and appended them one by one to entities. Here’s the result: Note that North Carolina has several variations of its name and some have “the” prefixed in their names. Let’s get rid of them. articles = []for entity_list in entities: cleaned_entity_list = [] for entity in entity_list: cleaned_entity_list.append(entity.lstrip('the ').replace("'s", "").replace("’s","")) articles.append(cleaned_entity_list) In the code block above, we’re simply traversing the list of lists articles and cleaning the entities one by one. With each iteration, we’re stripping the prefix “the” and getting rid of 's. Looking at the entities, I’ve noticed that there are also variations in the “United States” is represented. There exists “United States of America” while some are just “United States”. We can trim these down into a more standard naming convention. FuzzyWuzzy can help with this. Described by pypi.org as “string matching like a boss,” FiuzzyWuzzy uses Levenshtein distance to calculate the similarities between words.1 For a really good tutorial on how to use FuzzyWuzzy, check out Thanh Huynh’s article. towardsdatascience.com Here’s the optional code for using FuzzyWuzzy: For the final step before creating the network graph, let’s get rid of the empty lists within our list of list that were generated by articles who didn’t have any GPE entity types. articles = [article for article in articles if article != []] For the next step, we’ll create the world into which the graph will exist. G = nx.Graph() Then, we’ll manually add the nodes with G.add_nodes_from(). for entities in articles: G.add_nodes_from(entities) Let’s see what the graph looks like with: figure(figsize=(10, 8))nx.draw(G, node_size=15) Next, let’s add the edges that will connect the nodes. for entities in articles: if len(entities) > 1: for i in range(len(entities)-1): G.add_edges_from([(str(entities[i]),str(entities[i+1]))]) For each iteration of the code above, we used a conditional that will only entertain a list of entities that has two or more entities. Then, we manually connect each of the entities with G.add_edges_from(). Let’s see what the graph looks like now: figure(figsize=(10, 8))nx.draw(G, node_size=10) This graph reminds me of spiders! LOL. To organize it a bit, I decided to use the shell version of the network graph: figure(figsize=(10, 8))nx.draw_shell(G, node_size=15) We can tell that some nodes are heavier on connections than others. To see which nodes have the most connections, let’s use G.degree(). G.degree() This gives the following degree view: Let’s find out which node or entity has the most number of connections. max(dict(G.degree()).items(), key = lambda x : x[1]) To find out which other nodes have the most number of connections, let’s check the top 5: degree_dict = dict(G.degree(G.nodes()))nx.set_node_attributes(G, degree_dict, 'degree')sorted_degree = sorted(degree_dict.items(), key=itemgetter(1), reverse=True) Above, sorted_degrees is a list that contains all the nodes and their degree values. We only wanted the top 5 like so: print("Top 5 nodes by degree:")for d in sorted_degree[:5]: print(d) Gephi is an open-source and free desktop application that lets us visualize, explore, and analyze all kinds of graphs and networks.2 Let’s export our graph data into a file so we can import it into Gephi. nx.write_gexf(G, "npr_coronavirus_GPE_50.gexf") Cool beans! This time, we only processed 50 articles from npr.org. What would happen if we processed all 300 articles from our dataset? What will we see if we change the entity type from GPE to PERSON? How else can we use network graphs to visualize natural language processing results? There’s always more to do. The possibilities are endless! I hope you enjoyed today’s post. The code is not perfect and we have a long way to go towards realizing insights from the data. I encourage you to dive deeper and learn more about spaCy, networkx, fuzzywuzzy, and even Gephi. Stay tuned! You can reach me on Twitter or LinkedIn. [1]: Wikipedia. (May 25, 2020). Natural language processing https://en.wikipedia.org/wiki/Natural_language_processing [2]: Gephi. (May 25, 2020). The Open Graph Viz Platform https://gephi.org/
[ { "code": null, "e": 284, "s": 47, "text": "I do a lot of natural language processing and usually, the results are pretty boring to the eye. When I learned about network graphs, it got me thinking, why not use keywords as nodes and connect them together to create a network graph?" }, { "code": null, "e": 299, "s": 284, "text": "Yupp, why not!" }, { "code": null, "e": 489, "s": 299, "text": "In this post, we’ll do exactly that. We’re going to extract named-entities from news articles about coronavirus and then use their relationships to connect them together in a network graph." }, { "code": null, "e": 701, "s": 489, "text": "Network graphs are a cool visual that contains nodes (vertices) and edges (lines). It’s often used in social network analysis and network analysis but data scientists also use it for natural language processing." }, { "code": null, "e": 990, "s": 701, "text": "Natural Language Processing or NLP is a branch of artificial intelligence that deals with programming computers to process and analyze large volumes of text and derive meaning out of them.1 In other words, it’s all about teaching computers how to understand human language... like a boss!" }, { "code": null, "e": 1032, "s": 990, "text": "Enough introduction, let’s get to coding!" }, { "code": null, "e": 1153, "s": 1032, "text": "To get started, let’s make sure to take care of all dependencies. Open up a terminal and execute the following commands:" }, { "code": null, "e": 1243, "s": 1153, "text": "pip install -U spacypython -m spacy download enpip install networkxpip install fuzzywuzzy" }, { "code": null, "e": 1521, "s": 1243, "text": "This will install spaCy and download the trained model for English. The third command installs networkx. This should work for most systems. If it doesn’t work for you, check out the documentation for spaCy and networkx. Also, we’re using fuzzywuzzy for some text preprocessing." }, { "code": null, "e": 1597, "s": 1521, "text": "With that out of the way, let’s fire up a Jupyter notebook and get started!" }, { "code": null, "e": 1700, "s": 1597, "text": "Run the following code block into a cell to get all the necessary imports into our Python environment." }, { "code": null, "e": 1979, "s": 1700, "text": "import pandas as pdimport numpy as npimport picklefrom operator import itemgetterfrom fuzzywuzzy import process, fuzz# for natural language processingimport spacyimport en_core_web_sm# for visualizations%matplotlib inlinefrom matplotlib.pyplot import figureimport networkx as nx" }, { "code": null, "e": 2214, "s": 1979, "text": "If you want to follow along, you can download the sample dataset here. The file was created using newspaper to import news articles from the npr.org. If you’re feeling adventurous, use the code snippet below to build your own dataset." }, { "code": null, "e": 2234, "s": 2214, "text": "Let’s get our data." }, { "code": null, "e": 2323, "s": 2234, "text": "with open('npr_coronavirus.txt', 'rb') as fp: # Unpickling corpus = pickle.load(fp)" }, { "code": null, "e": 2375, "s": 2323, "text": "Next, we’ll start by loading spaCy’s English model:" }, { "code": null, "e": 2403, "s": 2375, "text": "nlp = en_core_web_sm.load()" }, { "code": null, "e": 2437, "s": 2403, "text": "Then, we’ll extract the entities:" }, { "code": null, "e": 2653, "s": 2437, "text": "entities = []for article in corpus[:50]: tokens = nlp(''.join(article)) gpe_list = [] for ent in tokens.ents: if ent.label_ == 'GPE': gpe_list.append(ent.text) entities.append(gpe_list)" }, { "code": null, "e": 3157, "s": 2653, "text": "In the above code block, we created an empty list called entities to store a list of lists that contains the extracted entities from each of the articles. In the for-loop, we looped through the first 50 articles of the corpus. For each iteration, we converted each articles into tokens (words) and then we looped through all those words to get the entities that are labeled as GPE for countries, states, and cities. We used ent.text to extract the actual entity and appended them one by one to entities." }, { "code": null, "e": 3176, "s": 3157, "text": "Here’s the result:" }, { "code": null, "e": 3304, "s": 3176, "text": "Note that North Carolina has several variations of its name and some have “the” prefixed in their names. Let’s get rid of them." }, { "code": null, "e": 3536, "s": 3304, "text": "articles = []for entity_list in entities: cleaned_entity_list = [] for entity in entity_list: cleaned_entity_list.append(entity.lstrip('the ').replace(\"'s\", \"\").replace(\"’s\",\"\")) articles.append(cleaned_entity_list)" }, { "code": null, "e": 3727, "s": 3536, "text": "In the code block above, we’re simply traversing the list of lists articles and cleaning the entities one by one. With each iteration, we’re stripping the prefix “the” and getting rid of 's." }, { "code": null, "e": 3975, "s": 3727, "text": "Looking at the entities, I’ve noticed that there are also variations in the “United States” is represented. There exists “United States of America” while some are just “United States”. We can trim these down into a more standard naming convention." }, { "code": null, "e": 4006, "s": 3975, "text": "FuzzyWuzzy can help with this." }, { "code": null, "e": 4232, "s": 4006, "text": "Described by pypi.org as “string matching like a boss,” FiuzzyWuzzy uses Levenshtein distance to calculate the similarities between words.1 For a really good tutorial on how to use FuzzyWuzzy, check out Thanh Huynh’s article." }, { "code": null, "e": 4255, "s": 4232, "text": "towardsdatascience.com" }, { "code": null, "e": 4302, "s": 4255, "text": "Here’s the optional code for using FuzzyWuzzy:" }, { "code": null, "e": 4483, "s": 4302, "text": "For the final step before creating the network graph, let’s get rid of the empty lists within our list of list that were generated by articles who didn’t have any GPE entity types." }, { "code": null, "e": 4545, "s": 4483, "text": "articles = [article for article in articles if article != []]" }, { "code": null, "e": 4620, "s": 4545, "text": "For the next step, we’ll create the world into which the graph will exist." }, { "code": null, "e": 4635, "s": 4620, "text": "G = nx.Graph()" }, { "code": null, "e": 4695, "s": 4635, "text": "Then, we’ll manually add the nodes with G.add_nodes_from()." }, { "code": null, "e": 4751, "s": 4695, "text": "for entities in articles: G.add_nodes_from(entities)" }, { "code": null, "e": 4793, "s": 4751, "text": "Let’s see what the graph looks like with:" }, { "code": null, "e": 4841, "s": 4793, "text": "figure(figsize=(10, 8))nx.draw(G, node_size=15)" }, { "code": null, "e": 4896, "s": 4841, "text": "Next, let’s add the edges that will connect the nodes." }, { "code": null, "e": 5055, "s": 4896, "text": "for entities in articles: if len(entities) > 1: for i in range(len(entities)-1): G.add_edges_from([(str(entities[i]),str(entities[i+1]))])" }, { "code": null, "e": 5262, "s": 5055, "text": "For each iteration of the code above, we used a conditional that will only entertain a list of entities that has two or more entities. Then, we manually connect each of the entities with G.add_edges_from()." }, { "code": null, "e": 5303, "s": 5262, "text": "Let’s see what the graph looks like now:" }, { "code": null, "e": 5351, "s": 5303, "text": "figure(figsize=(10, 8))nx.draw(G, node_size=10)" }, { "code": null, "e": 5390, "s": 5351, "text": "This graph reminds me of spiders! LOL." }, { "code": null, "e": 5469, "s": 5390, "text": "To organize it a bit, I decided to use the shell version of the network graph:" }, { "code": null, "e": 5523, "s": 5469, "text": "figure(figsize=(10, 8))nx.draw_shell(G, node_size=15)" }, { "code": null, "e": 5659, "s": 5523, "text": "We can tell that some nodes are heavier on connections than others. To see which nodes have the most connections, let’s use G.degree()." }, { "code": null, "e": 5670, "s": 5659, "text": "G.degree()" }, { "code": null, "e": 5708, "s": 5670, "text": "This gives the following degree view:" }, { "code": null, "e": 5780, "s": 5708, "text": "Let’s find out which node or entity has the most number of connections." }, { "code": null, "e": 5833, "s": 5780, "text": "max(dict(G.degree()).items(), key = lambda x : x[1])" }, { "code": null, "e": 5923, "s": 5833, "text": "To find out which other nodes have the most number of connections, let’s check the top 5:" }, { "code": null, "e": 6087, "s": 5923, "text": "degree_dict = dict(G.degree(G.nodes()))nx.set_node_attributes(G, degree_dict, 'degree')sorted_degree = sorted(degree_dict.items(), key=itemgetter(1), reverse=True)" }, { "code": null, "e": 6206, "s": 6087, "text": "Above, sorted_degrees is a list that contains all the nodes and their degree values. We only wanted the top 5 like so:" }, { "code": null, "e": 6277, "s": 6206, "text": "print(\"Top 5 nodes by degree:\")for d in sorted_degree[:5]: print(d)" }, { "code": null, "e": 6410, "s": 6277, "text": "Gephi is an open-source and free desktop application that lets us visualize, explore, and analyze all kinds of graphs and networks.2" }, { "code": null, "e": 6482, "s": 6410, "text": "Let’s export our graph data into a file so we can import it into Gephi." }, { "code": null, "e": 6530, "s": 6482, "text": "nx.write_gexf(G, \"npr_coronavirus_GPE_50.gexf\")" }, { "code": null, "e": 6542, "s": 6530, "text": "Cool beans!" }, { "code": null, "e": 6817, "s": 6542, "text": "This time, we only processed 50 articles from npr.org. What would happen if we processed all 300 articles from our dataset? What will we see if we change the entity type from GPE to PERSON? How else can we use network graphs to visualize natural language processing results?" }, { "code": null, "e": 6875, "s": 6817, "text": "There’s always more to do. The possibilities are endless!" }, { "code": null, "e": 7100, "s": 6875, "text": "I hope you enjoyed today’s post. The code is not perfect and we have a long way to go towards realizing insights from the data. I encourage you to dive deeper and learn more about spaCy, networkx, fuzzywuzzy, and even Gephi." }, { "code": null, "e": 7112, "s": 7100, "text": "Stay tuned!" }, { "code": null, "e": 7153, "s": 7112, "text": "You can reach me on Twitter or LinkedIn." }, { "code": null, "e": 7271, "s": 7153, "text": "[1]: Wikipedia. (May 25, 2020). Natural language processing https://en.wikipedia.org/wiki/Natural_language_processing" } ]
Check whether the two numbers differ at one bit position only - GeeksforGeeks
13 Apr, 2021 Given two non-negative integers a and b. The problem is to check whether the two numbers differ at one bit position only or not.Examples: Input : a = 13, b = 9 Output : Yes (13)10 = (1101)2 (9)10 = (1001)2 Both the numbers differ at one bit position only, i.e, differ at the 3rd bit from the right. Input : a = 15, b = 8 Output : No Approach: Following are the steps: Calculate num = a ^ b.Check whether num is a power of 2 or not. Refer this post. Calculate num = a ^ b. Check whether num is a power of 2 or not. Refer this post. C++ Java Python3 C# PHP Javascript // C++ implementation to check whether the two// numbers differ at one bit position only#include <bits/stdc++.h>using namespace std; // function to check if x is power of 2bool isPowerOfTwo(unsigned int x){ // First x in the below expression is // for the case when x is 0 return x && (!(x & (x - 1)));} // function to check whether the two numbers// differ at one bit position onlybool differAtOneBitPos(unsigned int a, unsigned int b){ return isPowerOfTwo(a ^ b);} // Driver program to test aboveint main(){ unsigned int a = 13, b = 9; if (differAtOneBitPos(a, b)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation to check whether the two // numbers differ at one bit position onlyimport java.io.*;import java.util.*; class GFG { // function to check if x is power of 2 static boolean isPowerOfTwo(int x) { // First x in the below expression is // for the case when x is 0 return x!= 0 && ((x & (x - 1)) == 0); } // function to check whether the two numbers // differ at one bit position only static boolean differAtOneBitPos(int a, int b) { return isPowerOfTwo(a ^ b); } // Driver code public static void main(String args[]) { int a = 13, b = 9; if (differAtOneBitPos(a, b) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by rachana soma # Python3 implementation to check whether the two# numbers differ at one bit position only # function to check if x is power of 2def isPowerOfTwo( x ): # First x in the below expression is # for the case when x is 0 return x and (not(x & (x - 1))) # function to check whether the two numbers# differ at one bit position onlydef differAtOneBitPos( a , b ): return isPowerOfTwo(a ^ b) # Driver code to test abovea = 13b = 9if (differAtOneBitPos(a, b)): print("Yes")else: print( "No") # This code is contributed by "Sharad_Bhardwaj". // C# implementation to check whether the two// numbers differ at one bit position onlyusing System;class GFG{ // function to check if x is power of 2 static bool isPowerOfTwo(int x) { // First x in the below expression is // for the case when x is 0 return x != 0 && ((x & (x - 1)) == 0); } // function to check whether the two numbers // differ at one bit position only static bool differAtOneBitPos(int a, int b) { return isPowerOfTwo(a ^ b); } // Driver code public static void Main() { int a = 13, b = 9; if (differAtOneBitPos(a, b) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by ihritik <?php// PHP implementation to check// whether the two numbers differ// at one bit position only // function to check if x is power of 2 function isPowerOfTwo($x) { $y = 0; // First x in the below expression is // for the case when x is 0 if($x && (!($x & ($x - 1)))) $y = 1; return $y; } // function to check whether // the two numbers differ at // one bit position only function differAtOneBitPos($a,$b) { return isPowerOfTwo($a ^ $b); } // Driver Code $a = 13; $b = 9; if (differAtOneBitPos($a, $b)) echo "Yes"; else echo "No"; // This code is contributed by Sam007?> <script> // JavaScript program to check whether the two // numbers differ at one bit position only // function to check if x is power of 2 function isPowerOfTwo(x) { // First x in the below expression is // for the case when x is 0 return x!= 0 && ((x & (x - 1)) == 0); } // function to check whether the two numbers // differ at one bit position only function differAtOneBitPos(a, b) { return isPowerOfTwo(a ^ b); } // Driver code let a = 13, b = 9; if (differAtOneBitPos(a, b) == true) document.write("Yes"); else document.write("No"); // This code is contributed by code_hunt.</script> Output: Yes Time Complexity: O(1). Sam007 rachana soma ihritik code_hunt Numbers Operators Bit Magic Bit Magic Numbers Operators Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Binary representation of a given number Bits manipulation (Important tactics) Bit Fields in C Add two numbers without using arithmetic operators Find the element that appears once Set, Clear and Toggle a given bit of a number in C Josephus problem | Set 1 (A O(n) Solution) C++ bitset and its application
[ { "code": null, "e": 25368, "s": 25340, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25508, "s": 25368, "text": "Given two non-negative integers a and b. The problem is to check whether the two numbers differ at one bit position only or not.Examples: " }, { "code": null, "e": 25704, "s": 25508, "text": "Input : a = 13, b = 9\nOutput : Yes\n(13)10 = (1101)2\n(9)10 = (1001)2\nBoth the numbers differ at one bit position only, i.e,\ndiffer at the 3rd bit from the right.\n\nInput : a = 15, b = 8\nOutput : No" }, { "code": null, "e": 25742, "s": 25706, "text": "Approach: Following are the steps: " }, { "code": null, "e": 25823, "s": 25742, "text": "Calculate num = a ^ b.Check whether num is a power of 2 or not. Refer this post." }, { "code": null, "e": 25846, "s": 25823, "text": "Calculate num = a ^ b." }, { "code": null, "e": 25905, "s": 25846, "text": "Check whether num is a power of 2 or not. Refer this post." }, { "code": null, "e": 25911, "s": 25907, "text": "C++" }, { "code": null, "e": 25916, "s": 25911, "text": "Java" }, { "code": null, "e": 25924, "s": 25916, "text": "Python3" }, { "code": null, "e": 25927, "s": 25924, "text": "C#" }, { "code": null, "e": 25931, "s": 25927, "text": "PHP" }, { "code": null, "e": 25942, "s": 25931, "text": "Javascript" }, { "code": "// C++ implementation to check whether the two// numbers differ at one bit position only#include <bits/stdc++.h>using namespace std; // function to check if x is power of 2bool isPowerOfTwo(unsigned int x){ // First x in the below expression is // for the case when x is 0 return x && (!(x & (x - 1)));} // function to check whether the two numbers// differ at one bit position onlybool differAtOneBitPos(unsigned int a, unsigned int b){ return isPowerOfTwo(a ^ b);} // Driver program to test aboveint main(){ unsigned int a = 13, b = 9; if (differAtOneBitPos(a, b)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 26614, "s": 25942, "text": null }, { "code": "// Java implementation to check whether the two // numbers differ at one bit position onlyimport java.io.*;import java.util.*; class GFG { // function to check if x is power of 2 static boolean isPowerOfTwo(int x) { // First x in the below expression is // for the case when x is 0 return x!= 0 && ((x & (x - 1)) == 0); } // function to check whether the two numbers // differ at one bit position only static boolean differAtOneBitPos(int a, int b) { return isPowerOfTwo(a ^ b); } // Driver code public static void main(String args[]) { int a = 13, b = 9; if (differAtOneBitPos(a, b) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by rachana soma", "e": 27494, "s": 26614, "text": null }, { "code": "# Python3 implementation to check whether the two# numbers differ at one bit position only # function to check if x is power of 2def isPowerOfTwo( x ): # First x in the below expression is # for the case when x is 0 return x and (not(x & (x - 1))) # function to check whether the two numbers# differ at one bit position onlydef differAtOneBitPos( a , b ): return isPowerOfTwo(a ^ b) # Driver code to test abovea = 13b = 9if (differAtOneBitPos(a, b)): print(\"Yes\")else: print( \"No\") # This code is contributed by \"Sharad_Bhardwaj\".", "e": 28048, "s": 27494, "text": null }, { "code": "// C# implementation to check whether the two// numbers differ at one bit position onlyusing System;class GFG{ // function to check if x is power of 2 static bool isPowerOfTwo(int x) { // First x in the below expression is // for the case when x is 0 return x != 0 && ((x & (x - 1)) == 0); } // function to check whether the two numbers // differ at one bit position only static bool differAtOneBitPos(int a, int b) { return isPowerOfTwo(a ^ b); } // Driver code public static void Main() { int a = 13, b = 9; if (differAtOneBitPos(a, b) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by ihritik", "e": 28814, "s": 28048, "text": null }, { "code": "<?php// PHP implementation to check// whether the two numbers differ// at one bit position only // function to check if x is power of 2 function isPowerOfTwo($x) { $y = 0; // First x in the below expression is // for the case when x is 0 if($x && (!($x & ($x - 1)))) $y = 1; return $y; } // function to check whether // the two numbers differ at // one bit position only function differAtOneBitPos($a,$b) { return isPowerOfTwo($a ^ $b); } // Driver Code $a = 13; $b = 9; if (differAtOneBitPos($a, $b)) echo \"Yes\"; else echo \"No\"; // This code is contributed by Sam007?>", "e": 29544, "s": 28814, "text": null }, { "code": "<script> // JavaScript program to check whether the two // numbers differ at one bit position only // function to check if x is power of 2 function isPowerOfTwo(x) { // First x in the below expression is // for the case when x is 0 return x!= 0 && ((x & (x - 1)) == 0); } // function to check whether the two numbers // differ at one bit position only function differAtOneBitPos(a, b) { return isPowerOfTwo(a ^ b); } // Driver code let a = 13, b = 9; if (differAtOneBitPos(a, b) == true) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by code_hunt.</script>", "e": 30324, "s": 29544, "text": null }, { "code": null, "e": 30334, "s": 30324, "text": "Output: " }, { "code": null, "e": 30338, "s": 30334, "text": "Yes" }, { "code": null, "e": 30362, "s": 30338, "text": "Time Complexity: O(1). " }, { "code": null, "e": 30369, "s": 30362, "text": "Sam007" }, { "code": null, "e": 30382, "s": 30369, "text": "rachana soma" }, { "code": null, "e": 30390, "s": 30382, "text": "ihritik" }, { "code": null, "e": 30400, "s": 30390, "text": "code_hunt" }, { "code": null, "e": 30408, "s": 30400, "text": "Numbers" }, { "code": null, "e": 30418, "s": 30408, "text": "Operators" }, { "code": null, "e": 30428, "s": 30418, "text": "Bit Magic" }, { "code": null, "e": 30438, "s": 30428, "text": "Bit Magic" }, { "code": null, "e": 30446, "s": 30438, "text": "Numbers" }, { "code": null, "e": 30456, "s": 30446, "text": "Operators" }, { "code": null, "e": 30554, "s": 30456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30600, "s": 30554, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 30630, "s": 30600, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 30670, "s": 30630, "text": "Binary representation of a given number" }, { "code": null, "e": 30708, "s": 30670, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 30724, "s": 30708, "text": "Bit Fields in C" }, { "code": null, "e": 30775, "s": 30724, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 30810, "s": 30775, "text": "Find the element that appears once" }, { "code": null, "e": 30861, "s": 30810, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 30904, "s": 30861, "text": "Josephus problem | Set 1 (A O(n) Solution)" } ]
How to display a PDF as an image in React app using URL? - GeeksforGeeks
13 Aug, 2020 If we use the fetch method then it will open a new window for displaying the PDF file and let users download the PDF. But if you don’t want that then there is a way to do so. You can use the package called react-pdf, by using this package you can render the PDF in your React app by using the PDF URL. Prerequisites: Your project needs to use React 16.3 or later. Basic knowledge of packages React-pdf: It lets you display PDF in your React app as easily as if they were images. It helps to create custom components that you can use to create and structure your PDF documents. Step 1: Create React App npx create-react-app appname cd appname npm start Step 2: Install react-pdf package. npm install react-pdf Step 3: First make a separate component PDF (name of the component, can be anything) and render the PDF component in App.js. App.js: Javascript import React from 'react';import Pdf from './Pdf' const App = ()=> { return ( <div className="App"> //Rendering a pdf component <Pdf /> </div> );} export default App; After creating a pdf component your project directory will look like this. Step 4: In this section, we load the PDF and render it on your app. Document: Loads a document passed using file prop. File Prop: It tells what PDF should be displayed, In the above code, we pass URL to it. URL: The URL consists of two parts here. The 1st part is due to preventing cors error, you may refer docs to read more about the core. 1st part: https://cors-anywhere.herokuapp.com/ The 2nd part is our actual URL of PDF. 2nd part: http://www.pdf995.com/samples/pdf.pdf One more thing we need to do is ENABLE PDF.JS WORKER, you could use pdf.worker.js from an external CDN. onDocumentLoadSuccess: When the document gets successfully loaded we set the state of page number to tells on which page number of pdf the user is. Pdf.js: Now open the PDF component. Javascript import React, { useState } from 'react';import { Document, Page,pdfjs } from 'react-pdf';import './pdf.css' //PDFjs worker from an external cdnconst url = "https://cors-anywhere.herokuapp.com/http://www.pdf995.com/samples/pdf.pdf" export default function Test() { pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1); function onDocumentLoadSuccess({ numPages }) { setNumPages(numPages); setPageNumber(1); } return ( <> <div className="main"> <Document file={url} onLoadSuccess={onDocumentLoadSuccess} > <Page pageNumber={pageNumber} /> </Document> </div> </> );} Step 5: Now the last thing add NEXT and PREVIOUS buttons to PDF file. Pdf.js: Here we added two buttons NEXT AND PREVIOUS and their functions named previousPage() and nextPage() which change the state of the current page. Javascript import React, { useState } from 'react';import { Document, Page,pdfjs } from 'react-pdf'; const url = "https://cors-anywhere.herokuapp.com/http://www.pdf995.com/samples/pdf.pdf" export default function Test() { pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1); /*To Prevent right click on screen*/ document.addEventListener("contextmenu", (event) => { event.preventDefault(); }); /*When document gets loaded successfully*/ function onDocumentLoadSuccess({ numPages }) { setNumPages(numPages); setPageNumber(1); } function changePage(offset) { setPageNumber(prevPageNumber => prevPageNumber + offset); } function previousPage() { changePage(-1); } function nextPage() { changePage(1); } return ( <> <div className="main"> <Document file={url} onLoadSuccess={onDocumentLoadSuccess} > <Page pageNumber={pageNumber} /> </Document> <div> <div className="pagec"> Page {pageNumber || (numPages ? 1 : '--')} of {numPages || '--'} </div> <div className="buttonc"> <button type="button" disabled={pageNumber <= 1} onClick={previousPage} className="Pre" > Previous </button> <button type="button" disabled={pageNumber >= numPages} onClick={nextPage} > Next </button> </div> </div> </div> </> );} Output: react-js 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 Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? File uploading in React.js How to append HTML code to a div using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26751, "s": 26723, "text": "\n13 Aug, 2020" }, { "code": null, "e": 27053, "s": 26751, "text": "If we use the fetch method then it will open a new window for displaying the PDF file and let users download the PDF. But if you don’t want that then there is a way to do so. You can use the package called react-pdf, by using this package you can render the PDF in your React app by using the PDF URL." }, { "code": null, "e": 27069, "s": 27053, "text": "Prerequisites: " }, { "code": null, "e": 27116, "s": 27069, "text": "Your project needs to use React 16.3 or later." }, { "code": null, "e": 27145, "s": 27116, "text": "Basic knowledge of packages " }, { "code": null, "e": 27330, "s": 27145, "text": "React-pdf: It lets you display PDF in your React app as easily as if they were images. It helps to create custom components that you can use to create and structure your PDF documents." }, { "code": null, "e": 27356, "s": 27330, "text": "Step 1: Create React App " }, { "code": null, "e": 27385, "s": 27356, "text": "npx create-react-app appname" }, { "code": null, "e": 27396, "s": 27385, "text": "cd appname" }, { "code": null, "e": 27406, "s": 27396, "text": "npm start" }, { "code": null, "e": 27441, "s": 27406, "text": "Step 2: Install react-pdf package." }, { "code": null, "e": 27463, "s": 27441, "text": "npm install react-pdf" }, { "code": null, "e": 27588, "s": 27463, "text": "Step 3: First make a separate component PDF (name of the component, can be anything) and render the PDF component in App.js." }, { "code": null, "e": 27596, "s": 27588, "text": "App.js:" }, { "code": null, "e": 27607, "s": 27596, "text": "Javascript" }, { "code": "import React from 'react';import Pdf from './Pdf' const App = ()=> { return ( <div className=\"App\"> //Rendering a pdf component <Pdf /> </div> );} export default App;", "e": 27802, "s": 27607, "text": null }, { "code": null, "e": 27877, "s": 27802, "text": "After creating a pdf component your project directory will look like this." }, { "code": null, "e": 27945, "s": 27877, "text": "Step 4: In this section, we load the PDF and render it on your app." }, { "code": null, "e": 27996, "s": 27945, "text": "Document: Loads a document passed using file prop." }, { "code": null, "e": 28084, "s": 27996, "text": "File Prop: It tells what PDF should be displayed, In the above code, we pass URL to it." }, { "code": null, "e": 28125, "s": 28084, "text": "URL: The URL consists of two parts here." }, { "code": null, "e": 28219, "s": 28125, "text": "The 1st part is due to preventing cors error, you may refer docs to read more about the core." }, { "code": null, "e": 28267, "s": 28219, "text": "1st part: https://cors-anywhere.herokuapp.com/ " }, { "code": null, "e": 28306, "s": 28267, "text": "The 2nd part is our actual URL of PDF." }, { "code": null, "e": 28354, "s": 28306, "text": "2nd part: http://www.pdf995.com/samples/pdf.pdf" }, { "code": null, "e": 28458, "s": 28354, "text": "One more thing we need to do is ENABLE PDF.JS WORKER, you could use pdf.worker.js from an external CDN." }, { "code": null, "e": 28606, "s": 28458, "text": "onDocumentLoadSuccess: When the document gets successfully loaded we set the state of page number to tells on which page number of pdf the user is." }, { "code": null, "e": 28642, "s": 28606, "text": "Pdf.js: Now open the PDF component." }, { "code": null, "e": 28653, "s": 28642, "text": "Javascript" }, { "code": "import React, { useState } from 'react';import { Document, Page,pdfjs } from 'react-pdf';import './pdf.css' //PDFjs worker from an external cdnconst url = \"https://cors-anywhere.herokuapp.com/http://www.pdf995.com/samples/pdf.pdf\" export default function Test() { pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1); function onDocumentLoadSuccess({ numPages }) { setNumPages(numPages); setPageNumber(1); } return ( <> <div className=\"main\"> <Document file={url} onLoadSuccess={onDocumentLoadSuccess} > <Page pageNumber={pageNumber} /> </Document> </div> </> );}", "e": 29461, "s": 28653, "text": null }, { "code": null, "e": 29531, "s": 29461, "text": "Step 5: Now the last thing add NEXT and PREVIOUS buttons to PDF file." }, { "code": null, "e": 29683, "s": 29531, "text": "Pdf.js: Here we added two buttons NEXT AND PREVIOUS and their functions named previousPage() and nextPage() which change the state of the current page." }, { "code": null, "e": 29694, "s": 29683, "text": "Javascript" }, { "code": "import React, { useState } from 'react';import { Document, Page,pdfjs } from 'react-pdf'; const url = \"https://cors-anywhere.herokuapp.com/http://www.pdf995.com/samples/pdf.pdf\" export default function Test() { pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1); /*To Prevent right click on screen*/ document.addEventListener(\"contextmenu\", (event) => { event.preventDefault(); }); /*When document gets loaded successfully*/ function onDocumentLoadSuccess({ numPages }) { setNumPages(numPages); setPageNumber(1); } function changePage(offset) { setPageNumber(prevPageNumber => prevPageNumber + offset); } function previousPage() { changePage(-1); } function nextPage() { changePage(1); } return ( <> <div className=\"main\"> <Document file={url} onLoadSuccess={onDocumentLoadSuccess} > <Page pageNumber={pageNumber} /> </Document> <div> <div className=\"pagec\"> Page {pageNumber || (numPages ? 1 : '--')} of {numPages || '--'} </div> <div className=\"buttonc\"> <button type=\"button\" disabled={pageNumber <= 1} onClick={previousPage} className=\"Pre\" > Previous </button> <button type=\"button\" disabled={pageNumber >= numPages} onClick={nextPage} > Next </button> </div> </div> </div> </> );}", "e": 31342, "s": 29694, "text": null }, { "code": null, "e": 31350, "s": 31342, "text": "Output:" }, { "code": null, "e": 31359, "s": 31350, "text": "react-js" }, { "code": null, "e": 31370, "s": 31359, "text": "JavaScript" }, { "code": null, "e": 31387, "s": 31370, "text": "Web Technologies" }, { "code": null, "e": 31414, "s": 31387, "text": "Web technologies Questions" }, { "code": null, "e": 31512, "s": 31414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31521, "s": 31512, "text": "Comments" }, { "code": null, "e": 31534, "s": 31521, "text": "Old Comments" }, { "code": null, "e": 31595, "s": 31534, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31640, "s": 31595, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31709, "s": 31640, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 31736, "s": 31709, "text": "File uploading in React.js" }, { "code": null, "e": 31788, "s": 31736, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31844, "s": 31788, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31877, "s": 31844, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31939, "s": 31877, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31982, "s": 31939, "text": "How to fetch data from an API in ReactJS ?" } ]
Angular 8 - Angular Components and Templates
As we learned earlier, Components are building block of Angular application. The main job of Angular Component is to generate a section of web page called view. Every component will have an associated template and it will be used to generate views. Let us learn the basic concept of component and template in this chapter. Let us create a new component in our ExpenseManager application. Open command prompt and go to ExpenseManager application. cd /go/to/expense-manager Create a new component using ng generate component command as specified below − ng generate component expense-entry The output is mentioned below − CREATE src/app/expense-entry/expense-entry.component.html (28 bytes) CREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes) CREATE src/app/expense-entry/expense-entry.component.ts (296 bytes) CREATE src/app/expense-entry/expense-entry.component.css (0 bytes) UPDATE src/app/app.module.ts (431 bytes) Here, ExpenseEntryComponent is created under src/app/expense-entry folder. Component class, Template and stylesheet are created. AppModule is updated with new component. Add title property to ExpenseEntryComponent (src/app/expense-entry/expense-entry.component.ts) component. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-expense-entry', templateUrl: './expense-entry.component.html', styleUrls: ['./expense-entry.component.css'] }) export class ExpenseEntryComponent implements OnInit { title: string; constructor() { } ngOnInit() { this.title = "Expense Entry" } } Update template, src/app/expense-entry/expense-entry.component.htmlwith below content. <p>{{ title }}</p> Open src/app/app.component.html and include newly created component. <h1>{{ title }}</h1> <app-expense-entry></app-expense-entry> Here, app-expense-entry is the selector value and it can be used as regular HTML Tag. Finally, the output of the application is as shown below − We will update the content of the component during the course of learning more about templates. The integral part of Angular component is Template. It is used to generate the HTML content. Templates are plain HTML with additional functionality. Template can be attached to Angular component using @component decorator’s meta data. Angular provides two meta data to attach template to components. templateUrl We already know how to use templateUrl. It expects the relative path of the template file. For example, AppComponent set its template as app.component.html. templateUrl: './app.component.html', template template enables to place the HTML string inside the component itself. If the template content is minimal, then it will be easy to have it Component class itself for easy tracking and maintenance purpose. @Component({ selector: 'app-root', templateUrl: `<h1>{{ title }}</h1>`, styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Expense Manager'; constructor(private debugService : DebugService) {} ngOnInit() { this.debugService.info("Angular Application starts"); } } Angular Templates can use CSS styles similar to HTML. Template gets its style information from two sources, a) from its component b) from application configuration. Component configuration Component decorator provides two option, styles and styleUrls to provide CSS style information to its template. Styles − styles option is used to place the CSS inside the component itself. styles: ['h1 { color: '#ff0000'; }'] styleUrls − styleUrls is used to refer external CSS stylesheet. We can use multiple stylesheet as well. styleUrls: ['./app.component.css', './custom_style.css'] Angular provides an option in project configuration (angular.json) to specify the CSS stylesheets. The styles specified in angular.json will be applicable for all templates. Let us check our angular.json as shown below − { "projects": { "expense-manager": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/expense-manager", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": false, "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.css" ], "scripts": [] }, }, } }}, "defaultProject": "expense-manager" } Here, styles option setssrc/styles.css as global CSS stylesheet. We can include any number of CSS stylesheets as it supports multiple values. Let us include bootstrap into our ExpenseManager application using styles option and change the default template to use bootstrap components. Open command prompt and go to ExpenseManager application. cd /go/to/expense-manager Install bootstrap and JQuery library using below commands npm install --save bootstrap@4.5.0 jquery@3.5.1 Here, We have installed JQuery, because, bootstrap uses jquery extensively for advanced components. Option angular.json and set bootstrap and jquery library path. { "projects": { "expense-manager": { "architect": { "build": { "builder":"@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/expense-manager", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": false, "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "./node_modules/bootstrap/dist/css/bootstrap.css", "src/styles.css" ], "scripts": [ "./node_modules/jquery/dist/jquery.js", "./node_modules/bootstrap/dist/js/bootstrap.js" ] }, }, } }}, "defaultProject": "expense-manager" } Here, scripts option is used to include JavaScript library. JavaScript registered through scripts will be available to all Angular components in the application. Open app.component.html and change the content as specified below <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#">{{ title }}</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"> </span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Report</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Add Expense</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> <app-expense-entry></app-expense-entry> Here, Used bootstrap navigation and containers. Open src/app/expense-entry/expense-entry.component.html and place below content. <!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container" style="padding-left: 0px; padding-right: 0px;"> <div class="row"> <div class="col-sm" style="text-align: left;"> {{ title }} </div> <div class="col-sm" style="text-align: right;"> <button type="button" class="btn btn-primary">Edit</button> </div> </div> </div> <div class="container box" style="margin-top: 10px;"> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Item:</em></strong> </div> <div class="col" style="text-align: left;"> Pizza </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Amount:</em></strong> </div> <div class="col" style="text-align: left;"> 20 </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Category:</em></strong> </div> <div class="col" style="text-align: left;"> Food </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Location:</em></strong> </div> <div class="col" style="text-align: left;"> Zomato </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Spend On:</em></strong> </div> <div class="col" style="text-align: left;"> June 20, 2020 </div> </div> </div> </div> </div> </div> Restart the application. The output of the application is as follows − We will improve the application to handle dynamic expense entry in next chapter. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2637, "s": 2388, "text": "As we learned earlier, Components are building block of Angular application. The main job of Angular Component is to generate a section of web page called view. Every component will have an associated template and it will be used to generate views." }, { "code": null, "e": 2711, "s": 2637, "text": "Let us learn the basic concept of component and template in this chapter." }, { "code": null, "e": 2776, "s": 2711, "text": "Let us create a new component in our ExpenseManager application." }, { "code": null, "e": 2834, "s": 2776, "text": "Open command prompt and go to ExpenseManager application." }, { "code": null, "e": 2861, "s": 2834, "text": "cd /go/to/expense-manager\n" }, { "code": null, "e": 2941, "s": 2861, "text": "Create a new component using ng generate component command as specified below −" }, { "code": null, "e": 2978, "s": 2941, "text": "ng generate component expense-entry\n" }, { "code": null, "e": 3010, "s": 2978, "text": "The output is mentioned below −" }, { "code": null, "e": 3333, "s": 3010, "text": "CREATE src/app/expense-entry/expense-entry.component.html (28 bytes) \nCREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes) \nCREATE src/app/expense-entry/expense-entry.component.ts (296 bytes) \nCREATE src/app/expense-entry/expense-entry.component.css (0 bytes) \nUPDATE src/app/app.module.ts (431 bytes)\n" }, { "code": null, "e": 3339, "s": 3333, "text": "Here," }, { "code": null, "e": 3408, "s": 3339, "text": "ExpenseEntryComponent is created under src/app/expense-entry folder." }, { "code": null, "e": 3462, "s": 3408, "text": "Component class, Template and stylesheet are created." }, { "code": null, "e": 3503, "s": 3462, "text": "AppModule is updated with new component." }, { "code": null, "e": 3609, "s": 3503, "text": "Add title property to ExpenseEntryComponent (src/app/expense-entry/expense-entry.component.ts) component." }, { "code": null, "e": 3965, "s": 3609, "text": "import { Component, OnInit } from '@angular/core'; @Component({ \n selector: 'app-expense-entry', \n templateUrl: './expense-entry.component.html', styleUrls: ['./expense-entry.component.css'] \n}) \nexport class ExpenseEntryComponent implements OnInit {\n title: string;\n constructor() { } \n ngOnInit() { \n this.title = \"Expense Entry\" \n } \n}" }, { "code": null, "e": 4052, "s": 3965, "text": "Update template, src/app/expense-entry/expense-entry.component.htmlwith below content." }, { "code": null, "e": 4072, "s": 4052, "text": "<p>{{ title }}</p>\n" }, { "code": null, "e": 4141, "s": 4072, "text": "Open src/app/app.component.html and include newly created component." }, { "code": null, "e": 4203, "s": 4141, "text": "<h1>{{ title }}</h1>\n<app-expense-entry></app-expense-entry>\n" }, { "code": null, "e": 4209, "s": 4203, "text": "Here," }, { "code": null, "e": 4289, "s": 4209, "text": "app-expense-entry is the selector value and it can be used as regular HTML Tag." }, { "code": null, "e": 4348, "s": 4289, "text": "Finally, the output of the application is as shown below −" }, { "code": null, "e": 4444, "s": 4348, "text": "We will update the content of the component during the course of learning more about templates." }, { "code": null, "e": 4593, "s": 4444, "text": "The integral part of Angular component is Template. It is used to generate the HTML content. Templates are plain HTML with additional functionality." }, { "code": null, "e": 4744, "s": 4593, "text": "Template can be attached to Angular component using @component decorator’s meta data. Angular provides two meta data to attach template to components." }, { "code": null, "e": 4756, "s": 4744, "text": "templateUrl" }, { "code": null, "e": 4913, "s": 4756, "text": "We already know how to use templateUrl. It expects the relative path of the template file. For example, AppComponent set its template as app.component.html." }, { "code": null, "e": 4951, "s": 4913, "text": "templateUrl: './app.component.html',\n" }, { "code": null, "e": 4960, "s": 4951, "text": "template" }, { "code": null, "e": 5165, "s": 4960, "text": "template enables to place the HTML string inside the component itself. If the template content is minimal, then it will be easy to have it Component class itself for easy tracking and maintenance purpose." }, { "code": null, "e": 5505, "s": 5165, "text": "@Component({ \n selector: 'app-root', \n templateUrl: `<h1>{{ title }}</h1>`, \n styleUrls: ['./app.component.css'] \n}) \nexport class AppComponent implements OnInit { \n title = 'Expense Manager'; \n constructor(private debugService : DebugService) {} ngOnInit() { \n this.debugService.info(\"Angular Application starts\"); \n } \n}" }, { "code": null, "e": 5670, "s": 5505, "text": "Angular Templates can use CSS styles similar to HTML. Template gets its style information from two sources, a) from its component b) from application configuration." }, { "code": null, "e": 5694, "s": 5670, "text": "Component configuration" }, { "code": null, "e": 5806, "s": 5694, "text": "Component decorator provides two option, styles and styleUrls to provide CSS style information to its template." }, { "code": null, "e": 5883, "s": 5806, "text": "Styles − styles option is used to place the CSS inside the component itself." }, { "code": null, "e": 5921, "s": 5883, "text": "styles: ['h1 { color: '#ff0000'; }']\n" }, { "code": null, "e": 6025, "s": 5921, "text": "styleUrls − styleUrls is used to refer external CSS stylesheet. We can use multiple stylesheet as well." }, { "code": null, "e": 6083, "s": 6025, "text": "styleUrls: ['./app.component.css', './custom_style.css']\n" }, { "code": null, "e": 6304, "s": 6083, "text": "Angular provides an option in project configuration (angular.json) to specify the CSS stylesheets. The styles specified in angular.json will be applicable for all templates. Let us check our angular.json as shown below −" }, { "code": null, "e": 7049, "s": 6304, "text": "{\n\"projects\": { \n \"expense-manager\": { \n \"architect\": { \n \"build\": { \n \"builder\": \"@angular-devkit/build-angular:browser\", \"options\": { \n \"outputPath\": \"dist/expense-manager\", \n \"index\": \"src/index.html\", \n \"main\": \"src/main.ts\", \n \"polyfills\": \"src/polyfills.ts\", \n \"tsConfig\": \"tsconfig.app.json\", \n \"aot\": false, \n \"assets\": [ \n \"src/favicon.ico\", \n \"src/assets\" \n ], \n \"styles\": [ \n \"src/styles.css\" \n ], \n \"scripts\": [] \n }, \n }, \n } \n }}, \n \"defaultProject\": \"expense-manager\" \n}" }, { "code": null, "e": 7055, "s": 7049, "text": "Here," }, { "code": null, "e": 7191, "s": 7055, "text": "styles option setssrc/styles.css as global CSS stylesheet. We can include any number of CSS stylesheets as it supports multiple values." }, { "code": null, "e": 7333, "s": 7191, "text": "Let us include bootstrap into our ExpenseManager application using styles option and change the default template to use bootstrap components." }, { "code": null, "e": 7391, "s": 7333, "text": "Open command prompt and go to ExpenseManager application." }, { "code": null, "e": 7418, "s": 7391, "text": "cd /go/to/expense-manager\n" }, { "code": null, "e": 7476, "s": 7418, "text": "Install bootstrap and JQuery library using below commands" }, { "code": null, "e": 7525, "s": 7476, "text": "npm install --save bootstrap@4.5.0 jquery@3.5.1\n" }, { "code": null, "e": 7531, "s": 7525, "text": "Here," }, { "code": null, "e": 7625, "s": 7531, "text": "We have installed JQuery, because, bootstrap uses jquery extensively for advanced components." }, { "code": null, "e": 7688, "s": 7625, "text": "Option angular.json and set bootstrap and jquery library path." }, { "code": null, "e": 8679, "s": 7688, "text": "{ \n \"projects\": { \n \"expense-manager\": { \n \"architect\": { \n \"build\": {\n \"builder\":\"@angular-devkit/build-angular:browser\", \"options\": { \n \"outputPath\": \"dist/expense-manager\", \n \"index\": \"src/index.html\", \n \"main\": \"src/main.ts\", \n \"polyfills\": \"src/polyfills.ts\", \n \"tsConfig\": \"tsconfig.app.json\", \n \"aot\": false, \n \"assets\": [ \n \"src/favicon.ico\", \n \"src/assets\" \n ], \n \"styles\": [ \n \"./node_modules/bootstrap/dist/css/bootstrap.css\", \"src/styles.css\" \n ], \n \"scripts\": [ \n \"./node_modules/jquery/dist/jquery.js\", \"./node_modules/bootstrap/dist/js/bootstrap.js\" \n ] \n }, \n }, \n } \n }}, \n \"defaultProject\": \"expense-manager\" \n}" }, { "code": null, "e": 8685, "s": 8679, "text": "Here," }, { "code": null, "e": 8841, "s": 8685, "text": "scripts option is used to include JavaScript library. JavaScript registered through scripts will be available to all Angular components in the application." }, { "code": null, "e": 8907, "s": 8841, "text": "Open app.component.html and change the content as specified below" }, { "code": null, "e": 10067, "s": 8907, "text": "<!-- Navigation --> \n<nav class=\"navbar navbar-expand-lg navbar-dark bg-dark static-top\"> \n <div class=\"container\"> \n <a class=\"navbar-brand\" href=\"#\">{{ title }}</a> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarResponsive\" aria-controls=\"navbarResponsive\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> \n <span class=\"navbar-toggler-icon\">\n </span> \n </button> \n <div class=\"collapse navbar-collapse\" id=\"navbarResponsive\"> \n <ul class=\"navbar-nav ml-auto\"> \n <li class=\"nav-item active\"> \n <a class=\"nav-link\" href=\"#\">Home\n <span class=\"sr-only\">(current)\n </span>\n </a> \n </li> \n <li class=\"nav-item\"> \n <a class=\"nav-link\" href=\"#\">Report</a> \n </li> \n <li class=\"nav-item\"> \n <a class=\"nav-link\" href=\"#\">Add Expense</a> \n </li> \n <li class=\"nav-item\"> \n <a class=\"nav-link\" href=\"#\">About</a> \n </li> \n </ul> \n </div> \n </div> \n</nav> \n<app-expense-entry></app-expense-entry>" }, { "code": null, "e": 10073, "s": 10067, "text": "Here," }, { "code": null, "e": 10115, "s": 10073, "text": "Used bootstrap navigation and containers." }, { "code": null, "e": 10196, "s": 10115, "text": "Open src/app/expense-entry/expense-entry.component.html and place below content." }, { "code": null, "e": 12125, "s": 10196, "text": "<!-- Page Content --> \n<div class=\"container\"> \n <div class=\"row\"> \n <div class=\"col-lg-12 text-center\" style=\"padding-top: 20px;\"> \n <div class=\"container\" style=\"padding-left: 0px; padding-right: 0px;\"> \n <div class=\"row\"> \n <div class=\"col-sm\" style=\"text-align: left;\"> {{ title }} \n </div> \n <div class=\"col-sm\" style=\"text-align: right;\"> \n <button type=\"button\" class=\"btn btn-primary\">Edit</button> \n </div> \n </div> \n </div> \n <div class=\"container box\" style=\"margin-top: 10px;\"> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Item:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n Pizza \n </div>\n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\">\n <strong><em>Amount:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n 20 \n </div> \n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Category:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n Food \n </div> \n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Location:</em></strong>\n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n Zomato \n </div> \n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Spend On:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n June 20, 2020 \n </div> \n </div> \n </div> \n </div> \n</div> \n</div>" }, { "code": null, "e": 12150, "s": 12125, "text": "Restart the application." }, { "code": null, "e": 12196, "s": 12150, "text": "The output of the application is as follows −" }, { "code": null, "e": 12277, "s": 12196, "text": "We will improve the application to handle dynamic expense entry in next chapter." }, { "code": null, "e": 12312, "s": 12277, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12326, "s": 12312, "text": " Anadi Sharma" }, { "code": null, "e": 12361, "s": 12326, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12375, "s": 12361, "text": " Anadi Sharma" }, { "code": null, "e": 12410, "s": 12375, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12430, "s": 12410, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 12465, "s": 12430, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12482, "s": 12465, "text": " Frahaan Hussain" }, { "code": null, "e": 12515, "s": 12482, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 12527, "s": 12515, "text": " Senol Atac" }, { "code": null, "e": 12562, "s": 12527, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12574, "s": 12562, "text": " Senol Atac" }, { "code": null, "e": 12581, "s": 12574, "text": " Print" }, { "code": null, "e": 12592, "s": 12581, "text": " Add Notes" } ]
Subsets II in C++
Suppose we have a set of numbers; we have to generate all possible subsets of that set. This is also known as power set. We have to keep in mind that the elements may be duplicate. So if the set is like [1,2,2], then the power set will be [[], [1], [2], [1,2], [2,2], [1,2,2]] Let us see the steps − Define one array res and another set called x We will solve this using recursive approach. So if the recursive method name is called solve(), and this takes index, one temporary array, and the array of numbers (nums) The solve() function will work like below − if index = size of v, thenif temp is not present in x, then insert temp into res and also insert temp into xreturn if temp is not present in x, then insert temp into res and also insert temp into x return call solve(index + 1, temp, v) insert v[index] into temp call solve(index + 1, temp, v) remove last element from temp The main function will be like below − clear the res and x, and sort the given array, define an array temp call solve(0, temp, array) sort the res array and return res Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<vector<int> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: vector < vector <int> > res; set < vector <int> > x; static bool cmp(vector <int> a, vector <int> b){ return a < b; } void solve(int idx, vector <int> temp, vector <int> &v){ if(idx == v.size()){ if(x.find(temp) == x.end()){ res.push_back(temp); x.insert(temp); } return; } solve(idx+1, temp, v); temp.push_back(v[idx]); solve(idx+1, temp, v); temp.pop_back(); } vector<vector<int> > subsetsWithDup(vector<int> &a) { res.clear(); x.clear(); sort(a.begin(), a.end()); vector <int> temp; solve(0, temp, a); sort(res.begin(), res.end(), cmp); return res; } }; main(){ Solution ob; vector<int> v = {1,2,2}; print_vector(ob.subsetsWithDup(v)); } [1,2,2] [[],[1, ],[1, 2, ],[1, 2, 2, ],[2, ],[2, 2, ],]
[ { "code": null, "e": 1339, "s": 1062, "text": "Suppose we have a set of numbers; we have to generate all possible subsets of that set. This is also known as power set. We have to keep in mind that the elements may be duplicate. So if the set is like [1,2,2], then the power set will be [[], [1], [2], [1,2], [2,2], [1,2,2]]" }, { "code": null, "e": 1362, "s": 1339, "text": "Let us see the steps −" }, { "code": null, "e": 1408, "s": 1362, "text": "Define one array res and another set called x" }, { "code": null, "e": 1579, "s": 1408, "text": "We will solve this using recursive approach. So if the recursive method name is called solve(), and this takes index, one temporary array, and the array of numbers (nums)" }, { "code": null, "e": 1623, "s": 1579, "text": "The solve() function will work like below −" }, { "code": null, "e": 1738, "s": 1623, "text": "if index = size of v, thenif temp is not present in x, then insert temp into res and also insert temp into xreturn" }, { "code": null, "e": 1821, "s": 1738, "text": "if temp is not present in x, then insert temp into res and also insert temp into x" }, { "code": null, "e": 1828, "s": 1821, "text": "return" }, { "code": null, "e": 1859, "s": 1828, "text": "call solve(index + 1, temp, v)" }, { "code": null, "e": 1885, "s": 1859, "text": "insert v[index] into temp" }, { "code": null, "e": 1916, "s": 1885, "text": "call solve(index + 1, temp, v)" }, { "code": null, "e": 1946, "s": 1916, "text": "remove last element from temp" }, { "code": null, "e": 1985, "s": 1946, "text": "The main function will be like below −" }, { "code": null, "e": 2053, "s": 1985, "text": "clear the res and x, and sort the given array, define an array temp" }, { "code": null, "e": 2080, "s": 2053, "text": "call solve(0, temp, array)" }, { "code": null, "e": 2114, "s": 2080, "text": "sort the res array and return res" }, { "code": null, "e": 2184, "s": 2114, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2195, "s": 2184, "text": " Live Demo" }, { "code": null, "e": 3335, "s": 2195, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<vector<int> > v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << \"[\";\n for(int j = 0; j <v[i].size(); j++){\n cout << v[i][j] << \", \";\n }\n cout << \"],\";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\n public:\n vector < vector <int> > res;\n set < vector <int> > x;\n static bool cmp(vector <int> a, vector <int> b){\n return a < b;\n }\n void solve(int idx, vector <int> temp, vector <int> &v){\n if(idx == v.size()){\n if(x.find(temp) == x.end()){\n res.push_back(temp);\n x.insert(temp);\n }\n return;\n }\n solve(idx+1, temp, v);\n temp.push_back(v[idx]);\n solve(idx+1, temp, v);\n temp.pop_back();\n }\n vector<vector<int> > subsetsWithDup(vector<int> &a) {\n res.clear();\n x.clear();\n sort(a.begin(), a.end());\n vector <int> temp;\n solve(0, temp, a);\n sort(res.begin(), res.end(), cmp);\n return res;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,2,2};\n print_vector(ob.subsetsWithDup(v));\n}" }, { "code": null, "e": 3343, "s": 3335, "text": "[1,2,2]" }, { "code": null, "e": 3391, "s": 3343, "text": "[[],[1, ],[1, 2, ],[1, 2, 2, ],[2, ],[2, 2, ],]" } ]
Count Pairs whose sum is equal to X | Practice | GeeksforGeeks
Given two linked list of size N1 and N2 respectively of distinct elements, your task is to complete the function countPairs(), which returns the count of all pairs from both lists whose sum is equal to the given value X. Note: The 2 numbers of a pair should be parts of different lists. Example 1: Input: L1 = 1->2->3->4->5->6 L2 = 11->12->13 X = 15 Output: 3 Explanation: There are 3 pairs that add up to 15 : (4,11) , (3,12) and (2,13) Example 2: Input: L1 = 7->5->1->3 L2 = 3->5->2->8 X = 10 Output: 2 Explanation: There are 2 pairs that add up to 10 : (7,3) and (5,5) Your Task: You only need to implement the given function countPairs() and return the count. Expected Time Complexity: O(N+M) Expected Auxiliary Space: O(N+M) Constraints: 1<=size of linked list<=10000 1<=X<=10000 Note : All elements in a linked list are unique. +1 shahabuddinbravo405 days ago class Solution{ public: int countPairs(struct Node* head1, struct Node* head2, int x) { Node *ptr1=head1,*ptr2=head2; unordered_set<int>s; while(ptr2) { s.insert(ptr2->data); ptr2=ptr2->next; } int pair=0; while(ptr1) { auto it=s.find(x-ptr1->data); if(it!=s.end()){ pair++; } ptr1=ptr1->next; } return pair; }}; 0 arjunaryagupta2031 week ago #Python Code #Using Hashing dic={} temp=h1 while temp!=None: if temp.data in dic: dic[temp.data]+=1 elif temp.data not in dic: dic[temp.data]=1 temp=temp.next count=0 while h2!=None: if x-h2.data in dic: count=count+dic.get(x-h2.data) h2=h2.next return count +1 sammy101 week ago void solve(struct Node* head,vector<int>&v){ if(head == NULL){ return; } struct Node* temp = head; while(temp != NULL){ v.push_back(temp->data); temp = temp->next; } } int countPairs(struct Node* head1, struct Node* head2, int x) { // Code here vector<int>v; vector<int>r; solve(head1,v); solve(head2,r); sort(v.begin(),v.end()); sort(r.begin(),r.end()); int n = v.size(); int m = r.size(); int i=0; int j=m-1; int count = 0; while(i!=n && j!=-1){ int sum = v[i] + r[j]; if(sum == x){ count++; } if(sum > x){ j--; }else{ i++; } } return count; } +1 velspace012 weeks ago java sol HashMap<Integer,Integer> hm=new HashMap<>(); for(int i=0;i<head1.size();i++){ hm.put(head1.get(i),i); } int count=0; for(int i=0;i<head2.size();i++){ int num=x-head2.get(i); if(hm.containsKey(num)){ count++; } } return count; 0 tthakare732 weeks ago //java Solution public static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { // add your code here HashSet<Integer> map = new HashSet<>(); int count = 0; for (int i = 0; i < head1.size(); i++) { map.add(x - head1.get(i)); } for (int i = 0; i < head2.size(); i++) { if(map.contains(head2.get(i))) count++; } return count; } +1 vikulol1 month ago class Solution{ public: int countPairs(struct Node* head1, struct Node* head2, int x) { unordered_map<int,int> umap; Node* end = head1; while(end != NULL) { umap[end->data] = 0; end = end->next; } Node* start = head2; int count = 0; while(start != NULL) { if(umap.find(x - (start->data)) != umap.end()) { count++; } start = start->next; } return count; } }; 0 as0042301 month ago In C++; int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; unordered_set<int> s; while(head1){ s.insert(head1->data); head1 = head1->next; } while(head2){ if(s.find(x - head2->data) != s.end()) count++; head2 = head2->next; } return count; } 0 tarundhiman851 month ago java 8 code: public static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2,int x) { Set<Integer> set = new HashSet<>(head1); long count = head2.stream().filter(ele -> set.contains(x - ele)).count(); return (int)count; } 0 thiruvazhidhinesh1 month ago JAVA SOLUTION: class Solution { public static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { int count=0; Map<Integer ,Integer> map=new HashMap<>(); Iterator<Integer> i=head1.iterator(); while(i.hasNext()){ int n=i.next(); map.put(x-n,n); } Iterator<Integer> i2=head2.iterator(); while(i2.hasNext()){ if(map.containsKey(i2.next())){ count++; } } return count; }} 0 mashhadihossain2 months ago SIMPLE JAVA SOLUTION class Solution { public static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { HashSet<Integer> set=new HashSet<Integer>(); int count=0; for(int i=0;i<head1.size();i++) { set.add(x-head1.get(i)); } for(int val : head2) { if(set.contains(val)) { count++; } } return count; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 525, "s": 238, "text": "Given two linked list of size N1 and N2 respectively of distinct elements, your task is to complete the function countPairs(), which returns the count of all pairs from both lists whose sum is equal to the given value X.\nNote: The 2 numbers of a pair should be parts of different lists." }, { "code": null, "e": 536, "s": 525, "text": "Example 1:" }, { "code": null, "e": 677, "s": 536, "text": "Input:\nL1 = 1->2->3->4->5->6\nL2 = 11->12->13\nX = 15\nOutput: 3\nExplanation: There are 3 pairs that\nadd up to 15 : (4,11) , (3,12) and (2,13)\n" }, { "code": null, "e": 688, "s": 677, "text": "Example 2:" }, { "code": null, "e": 811, "s": 688, "text": "Input:\nL1 = 7->5->1->3\nL2 = 3->5->2->8\nX = 10\nOutput: 2\nExplanation: There are 2 pairs that add up\nto 10 : (7,3) and (5,5)" }, { "code": null, "e": 903, "s": 811, "text": "Your Task:\nYou only need to implement the given function countPairs() and return the count." }, { "code": null, "e": 969, "s": 903, "text": "Expected Time Complexity: O(N+M)\nExpected Auxiliary Space: O(N+M)" }, { "code": null, "e": 1024, "s": 969, "text": "Constraints:\n1<=size of linked list<=10000\n1<=X<=10000" }, { "code": null, "e": 1073, "s": 1024, "text": "Note : All elements in a linked list are unique." }, { "code": null, "e": 1076, "s": 1073, "text": "+1" }, { "code": null, "e": 1105, "s": 1076, "text": "shahabuddinbravo405 days ago" }, { "code": null, "e": 1571, "s": 1105, "text": "class Solution{ public: int countPairs(struct Node* head1, struct Node* head2, int x) { Node *ptr1=head1,*ptr2=head2; unordered_set<int>s; while(ptr2) { s.insert(ptr2->data); ptr2=ptr2->next; } int pair=0; while(ptr1) { auto it=s.find(x-ptr1->data); if(it!=s.end()){ pair++; } ptr1=ptr1->next; } return pair; }};" }, { "code": null, "e": 1573, "s": 1571, "text": "0" }, { "code": null, "e": 1601, "s": 1573, "text": "arjunaryagupta2031 week ago" }, { "code": null, "e": 1614, "s": 1601, "text": "#Python Code" }, { "code": null, "e": 1630, "s": 1614, "text": "#Using Hashing " }, { "code": null, "e": 2042, "s": 1630, "text": " dic={} temp=h1 while temp!=None: if temp.data in dic: dic[temp.data]+=1 elif temp.data not in dic: dic[temp.data]=1 temp=temp.next count=0 while h2!=None: if x-h2.data in dic: count=count+dic.get(x-h2.data) h2=h2.next return count " }, { "code": null, "e": 2047, "s": 2044, "text": "+1" }, { "code": null, "e": 2065, "s": 2047, "text": "sammy101 week ago" }, { "code": null, "e": 2877, "s": 2065, "text": " void solve(struct Node* head,vector<int>&v){ if(head == NULL){ return; } struct Node* temp = head; while(temp != NULL){ v.push_back(temp->data); temp = temp->next; } } int countPairs(struct Node* head1, struct Node* head2, int x) { // Code here vector<int>v; vector<int>r; solve(head1,v); solve(head2,r); sort(v.begin(),v.end()); sort(r.begin(),r.end()); int n = v.size(); int m = r.size(); int i=0; int j=m-1; int count = 0; while(i!=n && j!=-1){ int sum = v[i] + r[j]; if(sum == x){ count++; } if(sum > x){ j--; }else{ i++; } } return count; }" }, { "code": null, "e": 2880, "s": 2877, "text": "+1" }, { "code": null, "e": 2902, "s": 2880, "text": "velspace012 weeks ago" }, { "code": null, "e": 3250, "s": 2902, "text": "java sol\n HashMap<Integer,Integer> hm=new HashMap<>();\n for(int i=0;i<head1.size();i++){\n hm.put(head1.get(i),i);\n }\n int count=0;\n for(int i=0;i<head2.size();i++){\n int num=x-head2.get(i);\n if(hm.containsKey(num)){\n count++;\n }\n }\n return count;" }, { "code": null, "e": 3252, "s": 3250, "text": "0" }, { "code": null, "e": 3274, "s": 3252, "text": "tthakare732 weeks ago" }, { "code": null, "e": 3740, "s": 3274, "text": "//java Solution \npublic static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) {\n // add your code here\n HashSet<Integer> map = new HashSet<>();\n int count = 0;\n \n for (int i = 0; i < head1.size(); i++) {\n map.add(x - head1.get(i));\n }\n \n for (int i = 0; i < head2.size(); i++) {\n if(map.contains(head2.get(i))) count++;\n }\n return count;\n }" }, { "code": null, "e": 3743, "s": 3740, "text": "+1" }, { "code": null, "e": 3762, "s": 3743, "text": "vikulol1 month ago" }, { "code": null, "e": 4337, "s": 3762, "text": "class Solution{\n public:\n int countPairs(struct Node* head1, struct Node* head2, int x) {\n \n unordered_map<int,int> umap;\n Node* end = head1;\n while(end != NULL)\n {\n umap[end->data] = 0;\n end = end->next;\n }\n Node* start = head2;\n int count = 0;\n while(start != NULL)\n {\n if(umap.find(x - (start->data)) != umap.end())\n {\n count++;\n }\n \n start = start->next;\n }\n \n return count;\n }\n};" }, { "code": null, "e": 4339, "s": 4337, "text": "0" }, { "code": null, "e": 4359, "s": 4339, "text": "as0042301 month ago" }, { "code": null, "e": 4367, "s": 4359, "text": "In C++;" }, { "code": null, "e": 4745, "s": 4367, "text": " int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; unordered_set<int> s; while(head1){ s.insert(head1->data); head1 = head1->next; } while(head2){ if(s.find(x - head2->data) != s.end()) count++; head2 = head2->next; } return count; }" }, { "code": null, "e": 4747, "s": 4745, "text": "0" }, { "code": null, "e": 4772, "s": 4747, "text": "tarundhiman851 month ago" }, { "code": null, "e": 4785, "s": 4772, "text": "java 8 code:" }, { "code": null, "e": 5032, "s": 4785, "text": "public static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2,int x) { Set<Integer> set = new HashSet<>(head1); long count = head2.stream().filter(ele -> set.contains(x - ele)).count(); return (int)count; }" }, { "code": null, "e": 5034, "s": 5032, "text": "0" }, { "code": null, "e": 5063, "s": 5034, "text": "thiruvazhidhinesh1 month ago" }, { "code": null, "e": 5079, "s": 5063, "text": "JAVA SOLUTION: " }, { "code": null, "e": 5096, "s": 5079, "text": "class Solution {" }, { "code": null, "e": 5199, "s": 5096, "text": " public static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { " }, { "code": null, "e": 5602, "s": 5199, "text": " int count=0; Map<Integer ,Integer> map=new HashMap<>(); Iterator<Integer> i=head1.iterator(); while(i.hasNext()){ int n=i.next(); map.put(x-n,n); } Iterator<Integer> i2=head2.iterator(); while(i2.hasNext()){ if(map.containsKey(i2.next())){ count++; } } return count; }}" }, { "code": null, "e": 5604, "s": 5602, "text": "0" }, { "code": null, "e": 5632, "s": 5604, "text": "mashhadihossain2 months ago" }, { "code": null, "e": 5653, "s": 5632, "text": "SIMPLE JAVA SOLUTION" }, { "code": null, "e": 5670, "s": 5653, "text": "class Solution {" }, { "code": null, "e": 6096, "s": 5670, "text": " public static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x) { HashSet<Integer> set=new HashSet<Integer>(); int count=0; for(int i=0;i<head1.size();i++) { set.add(x-head1.get(i)); } for(int val : head2) { if(set.contains(val)) { count++; } } return count; }} " }, { "code": null, "e": 6242, "s": 6096, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6278, "s": 6242, "text": " Login to access your submissions. " }, { "code": null, "e": 6288, "s": 6278, "text": "\nProblem\n" }, { "code": null, "e": 6298, "s": 6288, "text": "\nContest\n" }, { "code": null, "e": 6361, "s": 6298, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6509, "s": 6361, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6717, "s": 6509, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6823, "s": 6717, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]