title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to initialize a dictionary to an empty dictionary in C#?
To initialize a dictionary to an empty dictionary, use the Clear() method. It clears the dictionary and forms it as empty. dict.Clear(); After that, use the Dictionary count property to check whether the list is empty or not − if (dict.Count == 0) { Console.WriteLine("Dictionary is empty!"); } Let us see the complete code − Live Demo using System; using System.Collections.Generic; using System.Linq; namespace Demo { public class Program { public static void Main(string[] args) { var dict = new Dictionary < string, string > (); dict.Clear(); if (dict.Count == 0) { Console.WriteLine("Dictionary is empty!"); } } } } Dictionary is empty!
[ { "code": null, "e": 1185, "s": 1062, "text": "To initialize a dictionary to an empty dictionary, use the Clear() method. It clears the dictionary and forms it as empty." }, { "code": null, "e": 1199, "s": 1185, "text": "dict.Clear();" }, { "code": null, "e": 1289, "s": 1199, "text": "After that, use the Dictionary count property to check whether the list is empty or not −" }, { "code": null, "e": 1360, "s": 1289, "text": "if (dict.Count == 0) {\n Console.WriteLine(\"Dictionary is empty!\");\n}" }, { "code": null, "e": 1391, "s": 1360, "text": "Let us see the complete code −" }, { "code": null, "e": 1402, "s": 1391, "text": " Live Demo" }, { "code": null, "e": 1755, "s": 1402, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n\n var dict = new Dictionary < string, string > ();\n dict.Clear();\n if (dict.Count == 0) {\n Console.WriteLine(\"Dictionary is empty!\");\n }\n }\n }\n}" }, { "code": null, "e": 1776, "s": 1755, "text": "Dictionary is empty!" } ]
How to clear console in C language? - GeeksforGeeks
28 Oct, 2020 It is one of the basic need a program may required i.e clear the console during execution time.There is function named clrscr() which is included in conio.h and is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX.So what should we use there? There are two more ways to clear console: By Using system(“clear”)By using a regex “\e[1;1H\e[2J” By Using system(“clear”) By using a regex “\e[1;1H\e[2J” Now question arises which should we use and why: Using regex is a better way.The reason is its faster execution. By using regex we can perform clear screen operation very fastly in comparison to using system(“clear”). Below c program will demonstrate how fast regex is then the system(“clear”) The system(“clear”) is included in stdlib.h and also work only in linux system to use this in window use system(“cls”). C // C program for clearing console and// comparing two different methods#include <stdio.h>#include <stdlib.h>#include <time.h>int main(){ int i = 0; double time_taken; clock_t t1, t2; // a loop for showing geeks for geeks // repeating by clearing console using // system("clear") // Noting start time t1 = clock(); for (i; i < 10000; i++) { system("clear"); printf("geeks for geeks %d\n", i); } // Calculating total time taken by // system("clear") t1 = clock() - t1; i = 0; // Noting start time of regex t2 = clock(); for (i; i < 10000; i++) { printf("\e[1;1H\e[2J"); printf("geeks for geeks %d\n", i); } // calculating total time taken by regex t2 = clock() - t2; // printing taken by both printf("Time taken by system\(\"clear\") %f\n", ((double)t1) / CLOCKS_PER_SEC); printf("Time taken regex %f", ((double)t2) / CLOCKS_PER_SEC); return 0;} Output: geeks for geeks 9999 Time taken by system("clear") 0.934388 Time taken by regex 0.000001 NOTE:The output time may differ but the difference in both time will always be large.And also run this program only in your system’s console not here. nidhi_biet Akanksha_Rai sidharthkanwaria c-input-output c-puzzle C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ Arrow operator -> in C/C++ with Examples 'this' pointer in C++ UDP Server-Client implementation in C Understanding "extern" keyword in C Smart Pointers in C++ and How to Use Them Multiple Inheritance in C++ How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 24208, "s": 24180, "text": "\n28 Oct, 2020" }, { "code": null, "e": 24638, "s": 24208, "text": "It is one of the basic need a program may required i.e clear the console during execution time.There is function named clrscr() which is included in conio.h and is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX.So what should we use there? There are two more ways to clear console: " }, { "code": null, "e": 24694, "s": 24638, "text": "By Using system(“clear”)By using a regex “\\e[1;1H\\e[2J”" }, { "code": null, "e": 24719, "s": 24694, "text": "By Using system(“clear”)" }, { "code": null, "e": 24751, "s": 24719, "text": "By using a regex “\\e[1;1H\\e[2J”" }, { "code": null, "e": 25166, "s": 24751, "text": "Now question arises which should we use and why: Using regex is a better way.The reason is its faster execution. By using regex we can perform clear screen operation very fastly in comparison to using system(“clear”). Below c program will demonstrate how fast regex is then the system(“clear”) The system(“clear”) is included in stdlib.h and also work only in linux system to use this in window use system(“cls”). " }, { "code": null, "e": 25168, "s": 25166, "text": "C" }, { "code": "// C program for clearing console and// comparing two different methods#include <stdio.h>#include <stdlib.h>#include <time.h>int main(){ int i = 0; double time_taken; clock_t t1, t2; // a loop for showing geeks for geeks // repeating by clearing console using // system(\"clear\") // Noting start time t1 = clock(); for (i; i < 10000; i++) { system(\"clear\"); printf(\"geeks for geeks %d\\n\", i); } // Calculating total time taken by // system(\"clear\") t1 = clock() - t1; i = 0; // Noting start time of regex t2 = clock(); for (i; i < 10000; i++) { printf(\"\\e[1;1H\\e[2J\"); printf(\"geeks for geeks %d\\n\", i); } // calculating total time taken by regex t2 = clock() - t2; // printing taken by both printf(\"Time taken by system\\(\\\"clear\\\") %f\\n\", ((double)t1) / CLOCKS_PER_SEC); printf(\"Time taken regex %f\", ((double)t2) / CLOCKS_PER_SEC); return 0;}", "e": 26145, "s": 25168, "text": null }, { "code": null, "e": 26153, "s": 26145, "text": "Output:" }, { "code": null, "e": 26243, "s": 26153, "text": "geeks for geeks 9999\nTime taken by system(\"clear\") 0.934388\nTime taken by regex 0.000001\n" }, { "code": null, "e": 26395, "s": 26243, "text": "NOTE:The output time may differ but the difference in both time will always be large.And also run this program only in your system’s console not here. " }, { "code": null, "e": 26406, "s": 26395, "text": "nidhi_biet" }, { "code": null, "e": 26419, "s": 26406, "text": "Akanksha_Rai" }, { "code": null, "e": 26436, "s": 26419, "text": "sidharthkanwaria" }, { "code": null, "e": 26451, "s": 26436, "text": "c-input-output" }, { "code": null, "e": 26460, "s": 26451, "text": "c-puzzle" }, { "code": null, "e": 26471, "s": 26460, "text": "C Language" }, { "code": null, "e": 26569, "s": 26471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26607, "s": 26569, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26627, "s": 26607, "text": "Multithreading in C" }, { "code": null, "e": 26653, "s": 26627, "text": "Exception Handling in C++" }, { "code": null, "e": 26694, "s": 26653, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26716, "s": 26694, "text": "'this' pointer in C++" }, { "code": null, "e": 26754, "s": 26716, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26790, "s": 26754, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 26832, "s": 26790, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26860, "s": 26832, "text": "Multiple Inheritance in C++" } ]
Generating Anime Characters with StyleGAN2 | by Fathy Rashad | Towards Data Science
Generative Adversarial Network (GAN) is a generative model that is able to generate new content. The topic has become really popular in the machine learning community due to its interesting applications such as generating synthetic training data, creating arts, style-transfer, image-to-image translation, etc. GAN consisted of 2 networks, the generator, and the discriminator. The generator will try to generate fake samples and fool the discriminator into believing it to be real samples. The discriminator will try to detect the generated samples from both the real and fake samples. This interesting adversarial concept was introduced by Ian Goodfellow in 2014. There are already a lot of resources available to learn GAN, hence I will not explain GAN to avoid redundancy. I recommend reading this beautiful article by Joseph Rocca for understanding GAN. towardsdatascience.com The StyleGAN paper, “A Style-Based Architecture for GANs”, was published by NVIDIA in 2018. The paper proposed a new generator architecture for GAN that allows them to control different levels of details of the generated samples from the coarse details (eg. head shape) to the finer details (eg. eye-color). StyleGAN also incorporates the idea from Progressive GAN, where the networks are trained on lower resolution initially (4x4), then bigger layers are gradually added after it’s stabilized. By doing this, the training time becomes a lot faster and the training is a lot more stable. StyleGAN improves it further by adding a mapping network that encodes the input vectors into an intermediate latent space, w, which then will have separate values be used to control the different levels of details. Why add a mapping network? One of the issues of GAN is its entangled latent representations (the input vectors, z). For example, let’s say we have 2 dimensions latent code which represents the size of the face and the size of the eyes. In this case, the size of the face is highly entangled with the size of the eyes (bigger eyes would mean bigger face as well). On the other hand, we can simplify this by storing the ratio of the face and the eyes instead which would make our model be simpler as unentangled representations are easier for the model to interpret. With entangled representations, the data distribution may not necessarily follow the normal distribution where we want to sample the input vectors z from. For example, the data distribution would have a missing corner like this which represents the region where the ratio of the eyes and the face becomes unrealistic. If we sample the z from the normal distribution, our model will try to also generate the missing region where the ratio is unrealistic and because there Is no training data that have this trait, the generator will generate the image poorly. Therefore, the mapping network aims to disentangle the latent representations and warps the latent space so it is able to be sampled from the normal distribution. Additionally, Having separate input vectors, w, on each level allows the generator to control the different levels of visual features. The first few layers (4x4, 8x8) will control a higher level (coarser) of details such as the head shape, pose, and hairstyle. The last few layers (512x512, 1024x1024) will control the finer level of details such as the hair and eye color. For full details on StyleGAN architecture, I recommend you to read NVIDIA's official paper on their implementation. Here is the illustration of the full architecture from the paper itself. StyleGAN also allows you to control the stochastic variation in different levels of details by giving noise at the respective layer. Stochastic variations are minor randomness on the image that does not change our perception or the identity of the image such as differently combed hair, different hair placement and etc. You can see the effect of variations in the animated images below. StyleGAN also made several other improvements that I will not cover in these articles such as the AdaIN normalization and other regularization. You can read the official paper, this article by Jonathan Hui, or this article by Rani Horev for further details instead. When there is an underrepresented data in the training samples, the generator may not be able to learn the sample and generate it poorly. To avoid this, StyleGAN uses a “truncation trick” by truncating the intermediate latent vector w forcing it to be close to average. The Ψ (psi) is the threshold that is used to truncate and resample the latent vectors that are above the threshold. Hence, with higher Ψ, you can get higher diversity on the generated images but it also has a higher chance of generating weird or broken faces. For this network Ψ value of 0.5 to 0.7 seems to give a good image with adequate diversity according to Gwern. Though, feel free to experiment with the threshold value. I will be using the pre-trained Anime StyleGAN2 by Aaron Gokaslan so that we can load the model straight away and generate the anime faces. So, open your Jupyter notebook or Google Colab, and let’s start coding. Note: You can refer to my Colab notebook if you are stuck So first of all, we should clone the styleGAN repo. $ git clone https://github.com/NVlabs/stylegan2.git If you are using Google Colab, you can prefix the command with ‘!’ to run it as a command: !git clone https://github.com/NVlabs/stylegan2.git Next, we would need to download the pre-trained weights and load the model. Make sure you are running with GPU runtime when you are using Google Colab as the model is configured to use GPU. Now, we need to generate random vectors, z, to be used as the input fo our generator. Let’s create a function to generate the latent code, z, from a given seed. Then, we can create a function that takes the generated random vectors z and generate the images. Now, we can try generating a few images and see the results. The function will return an array of PIL.Image. In Google Colab, you can straight away show the image by printing the variable. Here is the first generated image. Let’s show it in a grid of images, so we can see multiple images at one time. And then we can show the generated images in a 3x3 grid. One of the nice things about GAN is that GAN has a smooth and continuous latent space unlike VAE (Variational Auto Encoder) where it has gaps. Hence, when you take two points in the latent space which will generate two different faces, you can create a transition or interpolation of the two faces by taking a linear path between the two points. Let’s implement this in code and create a function to interpolate between two values of the z vectors. Let’s see the interpolation results. You can see that the first image gradually transitioned to the second image. Now that we’ve done interpolation. We can finally try to make the interpolation animation in the thumbnail above. We will use the moviepy library to create the video or GIF file. When you run the code, it will generate a GIF animation of the interpolation. You can also modify the duration, grid size, or the fps using the variables at the top. If you made it this far, congratulations! You have generated anime faces using StyleGAN2 and learned the basics of GAN and StyleGAN architecture. Now that we have finished, what else can you do and further improve on? Here are a few things that you can do. Other DatasetsObviously, StyleGAN is not limited to anime dataset only, there are many available pre-trained datasets that you can play around such as images of real faces, cats, art, and paintings. Check out this GitHub repo for available pre-trained weights. On the other hand, you can also train the StyleGAN with your own chosen dataset. Conditional GANCurrently, we cannot really control the features that we want to generate such as hair color, eye color, hairstyle, and accessories. Conditional GAN allows you to give a label alongside the input vector, z, and hence conditioning the generated image to what we want. Alternatively, you can try making sense of the latent space either by regression or manually. If you want to go to this direction, Snow Halcy repo maybe be able to help you, as he done it and even made it interactive in this Jupyter notebook. I’d like to thanks Gwern Branwen for his extensive articles and explanation on generating anime faces with StyleGAN which I strongly referred to in my article. I fully recommend you to visit his websites as his writings are a trove of knowledge. Additionally, check out ThisWaifuDoesNotExists website which hosts the StyleGAN model for generating anime faces and a GPT model to generate anime plot. If you enjoy my writing, feel free to check out my other articles! towardsdatascience.com towardsdatascience.com [1] Karras, T., Laine, S., & Aila, T. (2019). A style-based generator architecture for generative adversarial networks. In Proceedings of the IEEE conference on computer vision and pattern recognition (pp. 4401–4410).
[ { "code": null, "e": 483, "s": 172, "text": "Generative Adversarial Network (GAN) is a generative model that is able to generate new content. The topic has become really popular in the machine learning community due to its interesting applications such as generating synthetic training data, creating arts, style-transfer, image-to-image translation, etc." }, { "code": null, "e": 949, "s": 483, "text": "GAN consisted of 2 networks, the generator, and the discriminator. The generator will try to generate fake samples and fool the discriminator into believing it to be real samples. The discriminator will try to detect the generated samples from both the real and fake samples. This interesting adversarial concept was introduced by Ian Goodfellow in 2014. There are already a lot of resources available to learn GAN, hence I will not explain GAN to avoid redundancy." }, { "code": null, "e": 1031, "s": 949, "text": "I recommend reading this beautiful article by Joseph Rocca for understanding GAN." }, { "code": null, "e": 1054, "s": 1031, "text": "towardsdatascience.com" }, { "code": null, "e": 1362, "s": 1054, "text": "The StyleGAN paper, “A Style-Based Architecture for GANs”, was published by NVIDIA in 2018. The paper proposed a new generator architecture for GAN that allows them to control different levels of details of the generated samples from the coarse details (eg. head shape) to the finer details (eg. eye-color)." }, { "code": null, "e": 1643, "s": 1362, "text": "StyleGAN also incorporates the idea from Progressive GAN, where the networks are trained on lower resolution initially (4x4), then bigger layers are gradually added after it’s stabilized. By doing this, the training time becomes a lot faster and the training is a lot more stable." }, { "code": null, "e": 1858, "s": 1643, "text": "StyleGAN improves it further by adding a mapping network that encodes the input vectors into an intermediate latent space, w, which then will have separate values be used to control the different levels of details." }, { "code": null, "e": 2423, "s": 1858, "text": "Why add a mapping network? One of the issues of GAN is its entangled latent representations (the input vectors, z). For example, let’s say we have 2 dimensions latent code which represents the size of the face and the size of the eyes. In this case, the size of the face is highly entangled with the size of the eyes (bigger eyes would mean bigger face as well). On the other hand, we can simplify this by storing the ratio of the face and the eyes instead which would make our model be simpler as unentangled representations are easier for the model to interpret." }, { "code": null, "e": 2741, "s": 2423, "text": "With entangled representations, the data distribution may not necessarily follow the normal distribution where we want to sample the input vectors z from. For example, the data distribution would have a missing corner like this which represents the region where the ratio of the eyes and the face becomes unrealistic." }, { "code": null, "e": 3145, "s": 2741, "text": "If we sample the z from the normal distribution, our model will try to also generate the missing region where the ratio is unrealistic and because there Is no training data that have this trait, the generator will generate the image poorly. Therefore, the mapping network aims to disentangle the latent representations and warps the latent space so it is able to be sampled from the normal distribution." }, { "code": null, "e": 3519, "s": 3145, "text": "Additionally, Having separate input vectors, w, on each level allows the generator to control the different levels of visual features. The first few layers (4x4, 8x8) will control a higher level (coarser) of details such as the head shape, pose, and hairstyle. The last few layers (512x512, 1024x1024) will control the finer level of details such as the hair and eye color." }, { "code": null, "e": 3708, "s": 3519, "text": "For full details on StyleGAN architecture, I recommend you to read NVIDIA's official paper on their implementation. Here is the illustration of the full architecture from the paper itself." }, { "code": null, "e": 4096, "s": 3708, "text": "StyleGAN also allows you to control the stochastic variation in different levels of details by giving noise at the respective layer. Stochastic variations are minor randomness on the image that does not change our perception or the identity of the image such as differently combed hair, different hair placement and etc. You can see the effect of variations in the animated images below." }, { "code": null, "e": 4362, "s": 4096, "text": "StyleGAN also made several other improvements that I will not cover in these articles such as the AdaIN normalization and other regularization. You can read the official paper, this article by Jonathan Hui, or this article by Rani Horev for further details instead." }, { "code": null, "e": 4632, "s": 4362, "text": "When there is an underrepresented data in the training samples, the generator may not be able to learn the sample and generate it poorly. To avoid this, StyleGAN uses a “truncation trick” by truncating the intermediate latent vector w forcing it to be close to average." }, { "code": null, "e": 5060, "s": 4632, "text": "The Ψ (psi) is the threshold that is used to truncate and resample the latent vectors that are above the threshold. Hence, with higher Ψ, you can get higher diversity on the generated images but it also has a higher chance of generating weird or broken faces. For this network Ψ value of 0.5 to 0.7 seems to give a good image with adequate diversity according to Gwern. Though, feel free to experiment with the threshold value." }, { "code": null, "e": 5272, "s": 5060, "text": "I will be using the pre-trained Anime StyleGAN2 by Aaron Gokaslan so that we can load the model straight away and generate the anime faces. So, open your Jupyter notebook or Google Colab, and let’s start coding." }, { "code": null, "e": 5330, "s": 5272, "text": "Note: You can refer to my Colab notebook if you are stuck" }, { "code": null, "e": 5382, "s": 5330, "text": "So first of all, we should clone the styleGAN repo." }, { "code": null, "e": 5434, "s": 5382, "text": "$ git clone https://github.com/NVlabs/stylegan2.git" }, { "code": null, "e": 5576, "s": 5434, "text": "If you are using Google Colab, you can prefix the command with ‘!’ to run it as a command: !git clone https://github.com/NVlabs/stylegan2.git" }, { "code": null, "e": 5766, "s": 5576, "text": "Next, we would need to download the pre-trained weights and load the model. Make sure you are running with GPU runtime when you are using Google Colab as the model is configured to use GPU." }, { "code": null, "e": 5927, "s": 5766, "text": "Now, we need to generate random vectors, z, to be used as the input fo our generator. Let’s create a function to generate the latent code, z, from a given seed." }, { "code": null, "e": 6025, "s": 5927, "text": "Then, we can create a function that takes the generated random vectors z and generate the images." }, { "code": null, "e": 6086, "s": 6025, "text": "Now, we can try generating a few images and see the results." }, { "code": null, "e": 6249, "s": 6086, "text": "The function will return an array of PIL.Image. In Google Colab, you can straight away show the image by printing the variable. Here is the first generated image." }, { "code": null, "e": 6327, "s": 6249, "text": "Let’s show it in a grid of images, so we can see multiple images at one time." }, { "code": null, "e": 6384, "s": 6327, "text": "And then we can show the generated images in a 3x3 grid." }, { "code": null, "e": 6730, "s": 6384, "text": "One of the nice things about GAN is that GAN has a smooth and continuous latent space unlike VAE (Variational Auto Encoder) where it has gaps. Hence, when you take two points in the latent space which will generate two different faces, you can create a transition or interpolation of the two faces by taking a linear path between the two points." }, { "code": null, "e": 6833, "s": 6730, "text": "Let’s implement this in code and create a function to interpolate between two values of the z vectors." }, { "code": null, "e": 6947, "s": 6833, "text": "Let’s see the interpolation results. You can see that the first image gradually transitioned to the second image." }, { "code": null, "e": 7126, "s": 6947, "text": "Now that we’ve done interpolation. We can finally try to make the interpolation animation in the thumbnail above. We will use the moviepy library to create the video or GIF file." }, { "code": null, "e": 7292, "s": 7126, "text": "When you run the code, it will generate a GIF animation of the interpolation. You can also modify the duration, grid size, or the fps using the variables at the top." }, { "code": null, "e": 7438, "s": 7292, "text": "If you made it this far, congratulations! You have generated anime faces using StyleGAN2 and learned the basics of GAN and StyleGAN architecture." }, { "code": null, "e": 7549, "s": 7438, "text": "Now that we have finished, what else can you do and further improve on? Here are a few things that you can do." }, { "code": null, "e": 7891, "s": 7549, "text": "Other DatasetsObviously, StyleGAN is not limited to anime dataset only, there are many available pre-trained datasets that you can play around such as images of real faces, cats, art, and paintings. Check out this GitHub repo for available pre-trained weights. On the other hand, you can also train the StyleGAN with your own chosen dataset." }, { "code": null, "e": 8416, "s": 7891, "text": "Conditional GANCurrently, we cannot really control the features that we want to generate such as hair color, eye color, hairstyle, and accessories. Conditional GAN allows you to give a label alongside the input vector, z, and hence conditioning the generated image to what we want. Alternatively, you can try making sense of the latent space either by regression or manually. If you want to go to this direction, Snow Halcy repo maybe be able to help you, as he done it and even made it interactive in this Jupyter notebook." }, { "code": null, "e": 8815, "s": 8416, "text": "I’d like to thanks Gwern Branwen for his extensive articles and explanation on generating anime faces with StyleGAN which I strongly referred to in my article. I fully recommend you to visit his websites as his writings are a trove of knowledge. Additionally, check out ThisWaifuDoesNotExists website which hosts the StyleGAN model for generating anime faces and a GPT model to generate anime plot." }, { "code": null, "e": 8882, "s": 8815, "text": "If you enjoy my writing, feel free to check out my other articles!" }, { "code": null, "e": 8905, "s": 8882, "text": "towardsdatascience.com" }, { "code": null, "e": 8928, "s": 8905, "text": "towardsdatascience.com" } ]
Create a Pandas DataFrame from List of Dicts - GeeksforGeeks
17 Dec, 2018 Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss how to create a Pandas DataFrame from List of Dicts. Code #1: # Python code demonstrate how to create # Pandas DataFrame by lists of dicts. import pandas as pd # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'}, {'Geeks':10, 'For': 20, 'geeks': 30}] # Creates DataFrame. df = pd.DataFrame(data) # Print the data df Output: Code #2: With index # Python code demonstrate how to create # Pandas DataFrame by lists of dicts. import pandas as pd # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'}, {'Geeks':10, 'For': 20, 'geeks': 30}] # Creates DataFrame. df = pd.DataFrame(data, index =['ind1', 'ind2']) # Print the data df Output: Code #3: With index and columns # Python code demonstrate how to create # Pandas DataFrame by lists of dicts. import pandas as pd # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'}, {'Geeks':10, 'For': 20, 'geeks': 30}] # With two column indices, values same # as dictionary keys df1 = pd.DataFrame(data, index =['ind1', 'ind2'], columns =['Geeks', 'For']) # With two column indices with # one index with other name df2 = pd.DataFrame(data, index =['indx', 'indy']) # print for first data frame print (df1, "\n") # Print for second DataFrame. print (df2) Output: pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24844, "s": 24816, "text": "\n17 Dec, 2018" }, { "code": null, "e": 25002, "s": 24844, "text": "Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object." }, { "code": null, "e": 25119, "s": 25002, "text": "Pandas DataFrame can be created in multiple ways. Let’s discuss how to create a Pandas DataFrame from List of Dicts." }, { "code": null, "e": 25128, "s": 25119, "text": "Code #1:" }, { "code": "# Python code demonstrate how to create # Pandas DataFrame by lists of dicts. import pandas as pd # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'}, {'Geeks':10, 'For': 20, 'geeks': 30}] # Creates DataFrame. df = pd.DataFrame(data) # Print the data df ", "e": 25443, "s": 25128, "text": null }, { "code": null, "e": 25451, "s": 25443, "text": "Output:" }, { "code": null, "e": 25473, "s": 25453, "text": "Code #2: With index" }, { "code": "# Python code demonstrate how to create # Pandas DataFrame by lists of dicts. import pandas as pd # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'}, {'Geeks':10, 'For': 20, 'geeks': 30}] # Creates DataFrame. df = pd.DataFrame(data, index =['ind1', 'ind2']) # Print the data df ", "e": 25813, "s": 25473, "text": null }, { "code": null, "e": 25822, "s": 25813, "text": "Output: " }, { "code": null, "e": 25854, "s": 25822, "text": "Code #3: With index and columns" }, { "code": "# Python code demonstrate how to create # Pandas DataFrame by lists of dicts. import pandas as pd # Initialise data to lists. data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'}, {'Geeks':10, 'For': 20, 'geeks': 30}] # With two column indices, values same # as dictionary keys df1 = pd.DataFrame(data, index =['ind1', 'ind2'], columns =['Geeks', 'For']) # With two column indices with # one index with other name df2 = pd.DataFrame(data, index =['indx', 'indy']) # print for first data frame print (df1, \"\\n\") # Print for second DataFrame. print (df2) ", "e": 26473, "s": 25854, "text": null }, { "code": null, "e": 26481, "s": 26473, "text": "Output:" }, { "code": null, "e": 26506, "s": 26481, "text": "pandas-dataframe-program" }, { "code": null, "e": 26530, "s": 26506, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26544, "s": 26530, "text": "Python-pandas" }, { "code": null, "e": 26551, "s": 26544, "text": "Python" }, { "code": null, "e": 26649, "s": 26551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26658, "s": 26649, "text": "Comments" }, { "code": null, "e": 26671, "s": 26658, "text": "Old Comments" }, { "code": null, "e": 26689, "s": 26671, "text": "Python Dictionary" }, { "code": null, "e": 26724, "s": 26689, "text": "Read a file line by line in Python" }, { "code": null, "e": 26746, "s": 26724, "text": "Enumerate() in Python" }, { "code": null, "e": 26778, "s": 26746, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26808, "s": 26778, "text": "Iterate over a list in Python" }, { "code": null, "e": 26850, "s": 26808, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26893, "s": 26850, "text": "Python program to convert a list to string" }, { "code": null, "e": 26937, "s": 26893, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26966, "s": 26937, "text": "*args and **kwargs in Python" } ]
PERL Regular Expressions
A regular expression is a string of characters that define the pattern or patterns you are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression.supporting programs, such as sed, grep, and awk. The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. The first operator is a test and assignment operator. There are three regular expression operators within Perl Match Regular Expression - m// Substitute Regular Expression - s/// Transliterate Regular Expression - tr/// The forward slashes in each case act as delimiters for the regular expression (regex) that you are specifying. If you are comfortable with any other delimiter then you can use in place of forward slash. The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence "foo" against the scalar $bar, you might use a statement like this: if ($bar =~ /foo/) The m// actually works in the same fashion as the q// operator series.you can use any combination of naturally matching characters to act as delimiters for the expression. For example, m{}, m(), and m>< are all valid. You can omit the m from m// if the delimiters are forward slashes, but for all other delimiters you must use the m prefix. Note that the entire match expression.that is the expression on the left of =~ or !~ and the match operator, returns true (in a scalar context) if the expression matches. Therefore the statement: $true = ($foo =~ m/foo/); Will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list context, the match returns the contents of any grouped expressions. For example, when extracting the hours, minutes, and seconds from a time string, we can use: my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/); The match operator supports its own set of modifiers. The /g modifier allows for global matching. The /i modifier will make the match case insensitive. Here is the complete list of modifiers Modifier Description i Makes the match case insensitive m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary o Evaluates the expression only once s Allows use of . to match a newline character x Allows you to use white space in the expression for clarity g Globally finds all matches cg Allows the search to continue even after a global match fails There is also a simpler version of the match operator - the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset. For example, you can use this to get the first and last elements within a list: #!/usr/bin/perl @list = qw/food foosball subeo footnote terfoot canic footbrdige/; foreach (@list) { $first = $1 if ?(foo.*)?; $last = $1 if /(foo.*)/; } print "First: $first, Last: $last\n"; This will produce following result First: food, Last: footbrdige The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is: s/PATTERN/REPLACEMENT/; The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. For example, we can replace all occurrences of .dog. with .cat. using $string =~ s/dog/cat/; Another example: #/user/bin/perl $string = 'The cat sat on the mat'; $string =~ s/cat/dog/; print "Final Result is $string\n"; This will produce following result The dog sat on the mat Here is the list of all modifiers used with substitution operator Modifier Description i Makes the match case insensitive m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary o Evaluates the expression only once s Allows use of . to match a newline character x Allows you to use white space in the expression for clarity g Replaces all occurrences of the found expression with the replacement text e Evaluates the replacement as if it were a Perl statement, and uses its return value as the replacement text Translation is similar, but not identical, to the principles of substitution, but unlike substitution, translation (or transliteration) does not use regular expressions for its search on replacement values. The translation operators are: tr/SEARCHLIST/REPLACEMENTLIST/cds y/SEARCHLIST/REPLACEMENTLIST/cds The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST. For example, using the "The cat sat on the mat." string we have been using in this chapter: #/user/bin/perl $string = 'The cat sat on the mat'; $string =~ tr/a/o/; print "$string\n"; This will produce following result The cot sot on the mot. $string =~ tr/a-z/A-Z/; Following is the list of operators related to translation Modifier Description c Complement SEARCHLIST. d Delete found but unreplaced characters. s Squash duplicate replaced characters. The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST. For example: #!/usr/bin/perl $string = 'the cat sat on the mat.'; $string =~ tr/a-z/b/d; print "$string\n"; This will produce following result b b b. The last modifier, /s, removes the duplicate sequences of characters that were replaced, so: #!/usr/bin/perl $string = 'food'; $string = 'food'; $string =~ tr/a-z/a-z/s; print $string; This will produce following result fod You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. Here's a quick cheat sheet: Character Description . a single character \s a whitespace character (space, tab, newline) \S non-whitespace character \d a digit (0-9) \D a non-digit \w a word character (a-z, A-Z, 0-9, _) \W a non-word character [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified Quantifiers can be used to specify how many of the previous thing you want to match on, where "thing" means either a literal character, one of the metacharacters listed above, or a group of characters or metacharacters in parentheses. Character Description * zero or more of the previous thing + one or more of the previous thing ? zero or one of the previous thing {3} matches exactly 3 of the previous thing {3,6} matches between 3 and 6 of the previous thing {3,} matches 3 or more of the previous thing The ^ metacharacter matches the beginning of the string and the $ metasymbol matches the end of the string. Here are some brief examples # nothing in the string (start and end are adjacent) /^$/ # a three digits, each followed by a whitespace # character (eg "3 4 5 ") /(\d\s) {3}/ # matches a string in which every # odd-numbered letter is a (eg "abacadaf") /(a.)+/ # string starts with one or more digits /^\d+/ # string that ends with one or more digits /\d+$/ Lets have alook at another example #!/usr/bin/perl $string = "Cats go Catatonic\nWhen given Catnip"; ($start) = ($string =~ /\A(.*?) /); @lines = $string =~ /^(.*?) /gm; print "First word: $start\n","Line starts: @lines\n"; This will produce following result First word: Cats Line starts: Cats When The \b matches at any word boundary, as defined by the difference between the \w class and the \W class. Because \w includes the characters for a word, and \W the opposite, this normally means the termination of a word. The \B assertion matches any position that is not a word boundary. For example: /\bcat\b/ # Matches 'the cat sat' but not 'cat on the mat' /\Bcat\B/ # Matches 'verification' but not 'the cat on the mat' /\bcat\B/ # Matches 'catatonic' but not 'polecat' /\Bcat\b/ # Matches 'polecat' but not 'catatonic' The | character is just like the standard or bitwise OR within Perl. It specifies alternate matches within a regular expression or group. For example, to match "cat" or "dog" in an expression, you might use this: if ($string =~ /cat|dog/) You can group individual elements of an expression together in order to support complex matches. Searching for two people.s names could be achieved with two separate tests, like this: if (($string =~ /Martin Brown/) || ($string =~ /Sharon Brown/)) This could be written as follows if ($string =~ /(Martin|Sharon) Brown/) From a regular-expression point of view, there is no difference between except, perhaps, that the former is slightly clearer. $string =~ /(\S+)\s+(\S+)/; and $string =~ /\S+\s+\S+/; However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string. my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/); As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows: $time =~ m/(\d+):(\d+):(\d+)/; my ($hours, $minutes, $seconds) = ($1, $2, $3); When groups are used in substitution expressions, the $x syntax can be used in the replacement text. Thus, we could reformat a date string using this: #!/usr/bin/perl $date = '03/26/1999'; $date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#; print "$date"; This will produce following result 1999/03/26 The \G assertion allows you to continue searching from the point where the last match occurred. For example, in the following code we have used \G so that we can search to the correct position and then extract some information, without having to create a more complex, single regular expression: #!/usr/bin/perl $string = "The time is: 12:31:02 on 4/12/00"; $string =~ /:\s+/g; ($time) = ($string =~ /\G(\d+:\d+:\d+)/); $string =~ /.+\s+/g; ($date) = ($string =~ m{\G(\d+/\d+/\d+)}); print "Time: $time, Date: $date\n"; This will produce following result Time: 12:31:02, Date: 4/12/00 The \G assertion is actually just the metasymbol equivalent of the pos function, so between regular expression calls you can continue to use pos, and even modify the value of pos (and therefore \G) by using pos as an lvalue subroutine: Regular expression variables include $, which contains whatever the last grouping match matched; $&, which contains the entire matched string; $`, which contains everything before the matched string; and $', which contains everything after the matched string. The following code demonstrates the result: #!/usr/bin/perl $string = "The food is in the salad bar"; $string =~ m/foo/; print "Before: $`\n"; print "Matched: $&\n"; print "After: $'\n"; This code prints the following when executed: Before: The Matched: foo After: d is in the salad bar Advertisements 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2481, "s": 2220, "text": "A regular expression is a string of characters that define the pattern or patterns you are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression.supporting programs, such as sed, grep, and awk." }, { "code": null, "e": 2638, "s": 2481, "text": "The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. The first operator is a test and assignment operator. " }, { "code": null, "e": 2695, "s": 2638, "text": "There are three regular expression operators within Perl" }, { "code": null, "e": 2727, "s": 2695, "text": " Match Regular Expression - m//" }, { "code": null, "e": 2765, "s": 2727, "text": " Substitute Regular Expression - s///" }, { "code": null, "e": 2807, "s": 2765, "text": " Transliterate Regular Expression - tr///" }, { "code": null, "e": 3010, "s": 2807, "text": "The forward slashes in each case act as delimiters for the regular expression (regex) that you are specifying. If you are comfortable with any other delimiter then you can use in place of forward slash." }, { "code": null, "e": 3213, "s": 3010, "text": "The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence \"foo\" against the scalar $bar, you might use a statement like this:" }, { "code": null, "e": 3233, "s": 3213, "text": "if ($bar =~ /foo/)\n" }, { "code": null, "e": 3452, "s": 3233, "text": "The m// actually works in the same fashion as the q// operator series.you can use any combination of naturally matching characters to act as delimiters for the expression. For example, m{}, m(), and m>< are all valid." }, { "code": null, "e": 3575, "s": 3452, "text": "You can omit the m from m// if the delimiters are forward slashes, but for all other delimiters you must use the m prefix." }, { "code": null, "e": 3772, "s": 3575, "text": "Note that the entire match expression.that is the expression on the left of =~ or !~ and the match operator, returns true (in a scalar context) if the expression matches. Therefore the statement:" }, { "code": null, "e": 3799, "s": 3772, "text": "$true = ($foo =~ m/foo/);\n" }, { "code": null, "e": 3871, "s": 3799, "text": "Will set $true to 1 if $foo matches the regex, or 0 if the match fails." }, { "code": null, "e": 4042, "s": 3871, "text": "In a list context, the match returns the contents of any grouped expressions. For example, when\nextracting the hours, minutes, and seconds from a time string, we can use:" }, { "code": null, "e": 4110, "s": 4042, "text": "my ($hours, $minutes, $seconds) = ($time =~ m/(\\d+):(\\d+):(\\d+)/);\n" }, { "code": null, "e": 4301, "s": 4110, "text": "The match operator supports its own set of modifiers. The /g modifier allows for global matching. The /i modifier will make the match case insensitive. Here is the complete list of modifiers" }, { "code": null, "e": 4776, "s": 4301, "text": "Modifier\tDescription\ni \tMakes the match case insensitive\nm \tSpecifies that if the string has newline or carriage\n\treturn characters, the ^ and $ operators will now\n\tmatch against a newline boundary, instead of a\n\tstring boundary\no \tEvaluates the expression only once\ns \tAllows use of . to match a newline character\nx \tAllows you to use white space in the expression for clarity\ng \tGlobally finds all matches\ncg \tAllows the search to continue even after a global match fails\n" }, { "code": null, "e": 5001, "s": 4776, "text": "There is also a simpler version of the match operator - the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset." }, { "code": null, "e": 5081, "s": 5001, "text": "For example, you can use this to get the first and last elements within a list:" }, { "code": null, "e": 5348, "s": 5081, "text": "#!/usr/bin/perl\n\n@list = qw/food foosball subeo footnote terfoot canic footbrdige/;\n\nforeach (@list)\n{\n $first = $1 if ?(foo.*)?;\n $last = $1 if /(foo.*)/;\n}\nprint \"First: $first, Last: $last\\n\";\n\nThis will produce following result\nFirst: food, Last: footbrdige\n" }, { "code": null, "e": 5530, "s": 5348, "text": "The substitution operator, s///, is really just an extension of the match operator that\nallows you to replace the text matched with some new text. The basic form of the\noperator is:" }, { "code": null, "e": 5555, "s": 5530, "text": "s/PATTERN/REPLACEMENT/;\n" }, { "code": null, "e": 5753, "s": 5555, "text": "The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with." }, { "code": null, "e": 5823, "s": 5753, "text": "For example, we can replace all occurrences of .dog. with .cat. using" }, { "code": null, "e": 5847, "s": 5823, "text": "$string =~ s/dog/cat/;\n" }, { "code": null, "e": 5864, "s": 5847, "text": "Another example:" }, { "code": null, "e": 6037, "s": 5864, "text": "#/user/bin/perl\n\n$string = 'The cat sat on the mat';\n$string =~ s/cat/dog/;\n\nprint \"Final Result is $string\\n\";\n\nThis will produce following result\n\nThe dog sat on the mat\n" }, { "code": null, "e": 6103, "s": 6037, "text": "Here is the list of all modifiers used with substitution operator" }, { "code": null, "e": 6674, "s": 6103, "text": "Modifier\tDescription\ni \tMakes the match case insensitive\nm \tSpecifies that if the string has newline or carriage\n\treturn characters, the ^ and $ operators will now\n\tmatch against a newline boundary, instead of a\n\tstring boundary\no \tEvaluates the expression only once\ns \tAllows use of . to match a newline character\nx \tAllows you to use white space in the expression\n\tfor clarity\ng \tReplaces all occurrences of the found expression\n\twith the replacement text\ne \tEvaluates the replacement as if it were a Perl statement,\n\tand uses its return value as the replacement text\n" }, { "code": null, "e": 6912, "s": 6674, "text": "Translation is similar, but not identical, to the principles of substitution, but unlike substitution, translation (or transliteration) does not use regular expressions for its search on replacement values. The translation operators are:" }, { "code": null, "e": 6980, "s": 6912, "text": "tr/SEARCHLIST/REPLACEMENTLIST/cds\ny/SEARCHLIST/REPLACEMENTLIST/cds\n" }, { "code": null, "e": 7199, "s": 6980, "text": "The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST. For example, using the \"The cat sat on the mat.\" string we have been using in this chapter:" }, { "code": null, "e": 7354, "s": 7199, "text": "#/user/bin/perl\n\n$string = 'The cat sat on the mat';\n$string =~ tr/a/o/;\n\nprint \"$string\\n\";\n\nThis will produce following result\n\nThe cot sot on the mot.\n" }, { "code": null, "e": 7379, "s": 7354, "text": "$string =~ tr/a-z/A-Z/;\n" }, { "code": null, "e": 7437, "s": 7379, "text": "Following is the list of operators related to translation" }, { "code": null, "e": 7570, "s": 7437, "text": "Modifier \tDescription\nc \tComplement SEARCHLIST.\nd \tDelete found but unreplaced characters.\ns \tSquash duplicate replaced characters.\n" }, { "code": null, "e": 7701, "s": 7570, "text": "The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST. For example:" }, { "code": null, "e": 7845, "s": 7701, "text": "#!/usr/bin/perl \n\n$string = 'the cat sat on the mat.';\n$string =~ tr/a-z/b/d;\n\nprint \"$string\\n\";\n\nThis will produce following result\nb b b.\n" }, { "code": null, "e": 7938, "s": 7845, "text": "The last modifier, /s, removes the duplicate sequences of characters that were replaced, so:" }, { "code": null, "e": 8073, "s": 7938, "text": "#!/usr/bin/perl\n\n$string = 'food';\n$string = 'food';\n$string =~ tr/a-z/a-z/s;\n\nprint $string;\n\nThis will produce following result\nfod\n" }, { "code": null, "e": 8258, "s": 8073, "text": "You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. Here's a quick cheat sheet:" }, { "code": null, "e": 8739, "s": 8258, "text": "Character\t\tDescription\n. a single character\n\\s a whitespace character (space, tab, newline)\n\\S non-whitespace character\n\\d a digit (0-9)\n\\D a non-digit\n\\w a word character (a-z, A-Z, 0-9, _)\n\\W a non-word character\n[aeiou] matches a single character in the given set\n[^aeiou] matches a single character outside the given set\n(foo|bar|baz) matches any of the alternatives specified\n" }, { "code": null, "e": 8974, "s": 8739, "text": "Quantifiers can be used to specify how many of the previous thing you want to match on, where \"thing\" means either a literal character, one of the metacharacters listed above, or a group of characters or metacharacters in parentheses." }, { "code": null, "e": 9327, "s": 8974, "text": "Character Description\n* zero or more of the previous thing\n+ one or more of the previous thing\n? zero or one of the previous thing\n{3} matches exactly 3 of the previous thing\n{3,6} matches between 3 and 6 of the previous thing\n{3,} matches 3 or more of the previous thing\n" }, { "code": null, "e": 9435, "s": 9327, "text": "The ^ metacharacter matches the beginning of the string and the $ metasymbol matches the end of the string." }, { "code": null, "e": 9464, "s": 9435, "text": "Here are some brief examples" }, { "code": null, "e": 9803, "s": 9464, "text": "# nothing in the string (start and end are adjacent)\n/^$/ \n\n# a three digits, each followed by a whitespace\n# character (eg \"3 4 5 \")\n/(\\d\\s) {3}/ \n\n# matches a string in which every\n# odd-numbered letter is a (eg \"abacadaf\")\n/(a.)+/ \n\n# string starts with one or more digits\n/^\\d+/\n\n# string that ends with one or more digits\n/\\d+$/\n" }, { "code": null, "e": 9838, "s": 9803, "text": "Lets have alook at another example" }, { "code": null, "e": 10106, "s": 9838, "text": "#!/usr/bin/perl\n\n$string = \"Cats go Catatonic\\nWhen given Catnip\";\n($start) = ($string =~ /\\A(.*?) /);\n@lines = $string =~ /^(.*?) /gm;\nprint \"First word: $start\\n\",\"Line starts: @lines\\n\";\n\n\nThis will produce following result\nFirst word: Cats\nLine starts: Cats When\n" }, { "code": null, "e": 10406, "s": 10106, "text": "The \\b matches at any word boundary, as defined by the difference between the \\w class and the \\W class. Because \\w includes the characters for a word, and \\W the opposite, this normally means the termination of a word. The \\B assertion matches any position that is not a word boundary. For example:" }, { "code": null, "e": 10630, "s": 10406, "text": "/\\bcat\\b/ # Matches 'the cat sat' but not 'cat on the mat'\n/\\Bcat\\B/ # Matches 'verification' but not 'the cat on the mat'\n/\\bcat\\B/ # Matches 'catatonic' but not 'polecat'\n/\\Bcat\\b/ # Matches 'polecat' but not 'catatonic'\n" }, { "code": null, "e": 10843, "s": 10630, "text": "The | character is just like the standard or bitwise OR within Perl. It specifies alternate matches within a regular expression or group. For example, to match \"cat\" or \"dog\" in an expression, you might use this:" }, { "code": null, "e": 10870, "s": 10843, "text": "if ($string =~ /cat|dog/)\n" }, { "code": null, "e": 11054, "s": 10870, "text": "You can group individual elements of an expression together in order to support\ncomplex matches. Searching for two people.s names could be achieved with two\nseparate tests, like this:" }, { "code": null, "e": 11197, "s": 11054, "text": "if (($string =~ /Martin Brown/) ||\n ($string =~ /Sharon Brown/))\n\nThis could be written as follows\n\nif ($string =~ /(Martin|Sharon) Brown/)\n" }, { "code": null, "e": 11323, "s": 11197, "text": "From a regular-expression point of view, there is no difference between except, perhaps, that the former is slightly clearer." }, { "code": null, "e": 11383, "s": 11323, "text": "$string =~ /(\\S+)\\s+(\\S+)/;\n\nand \n\n$string =~ /\\S+\\s+\\S+/;\n" }, { "code": null, "e": 11675, "s": 11383, "text": "However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string." }, { "code": null, "e": 11743, "s": 11675, "text": "my ($hours, $minutes, $seconds) = ($time =~ m/(\\d+):(\\d+):(\\d+)/);\n" }, { "code": null, "e": 11968, "s": 11743, "text": "As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows:" }, { "code": null, "e": 12048, "s": 11968, "text": "$time =~ m/(\\d+):(\\d+):(\\d+)/;\nmy ($hours, $minutes, $seconds) = ($1, $2, $3);\n" }, { "code": null, "e": 12199, "s": 12048, "text": "When groups are used in substitution expressions, the $x syntax can be used in the\nreplacement text. Thus, we could reformat a date string using this:" }, { "code": null, "e": 12342, "s": 12199, "text": "#!/usr/bin/perl\n\n$date = '03/26/1999';\n$date =~ s#(\\d+)/(\\d+)/(\\d+)#$3/$1/$2#;\n\nprint \"$date\";\n\nThis will produce following result\n1999/03/26\n" }, { "code": null, "e": 12438, "s": 12342, "text": "The \\G assertion allows you to continue searching from the point where the last match\noccurred." }, { "code": null, "e": 12638, "s": 12438, "text": "For example, in the following code we have used \\G so that we can search to the\ncorrect position and then extract some information, without having to create a more\ncomplex, single regular expression:" }, { "code": null, "e": 12932, "s": 12638, "text": "#!/usr/bin/perl\n\n$string = \"The time is: 12:31:02 on 4/12/00\";\n\n$string =~ /:\\s+/g;\n($time) = ($string =~ /\\G(\\d+:\\d+:\\d+)/);\n$string =~ /.+\\s+/g;\n($date) = ($string =~ m{\\G(\\d+/\\d+/\\d+)});\n\nprint \"Time: $time, Date: $date\\n\";\n\nThis will produce following result\nTime: 12:31:02, Date: 4/12/00\n" }, { "code": null, "e": 13168, "s": 12932, "text": "The \\G assertion is actually just the metasymbol equivalent of the pos function, so between regular expression calls you can continue to use pos, and even modify the value of pos (and therefore \\G) by using pos as an lvalue subroutine:" }, { "code": null, "e": 13428, "s": 13168, "text": "Regular expression variables include $, which contains whatever the last grouping\nmatch matched; $&, which contains the entire matched string; $`, which contains\neverything before the matched string; and $', which contains everything after the\nmatched string." }, { "code": null, "e": 13472, "s": 13428, "text": "The following code demonstrates the result:" }, { "code": null, "e": 13718, "s": 13472, "text": "#!/usr/bin/perl\n\n$string = \"The food is in the salad bar\";\n$string =~ m/foo/;\nprint \"Before: $`\\n\";\nprint \"Matched: $&\\n\";\nprint \"After: $'\\n\";\n\nThis code prints the following when executed:\nBefore: The\nMatched: foo\nAfter: d is in the salad bar\n" }, { "code": null, "e": 13735, "s": 13718, "text": "\nAdvertisements\n" }, { "code": null, "e": 13770, "s": 13735, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13784, "s": 13770, "text": " Devi Killada" }, { "code": null, "e": 13819, "s": 13784, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13839, "s": 13819, "text": " Harshit Srivastava" }, { "code": null, "e": 13872, "s": 13839, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 13888, "s": 13872, "text": " TELCOMA Global" }, { "code": null, "e": 13921, "s": 13888, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 13938, "s": 13921, "text": " Mohammad Nauman" }, { "code": null, "e": 13971, "s": 13938, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 13994, "s": 13971, "text": " Stone River ELearning" }, { "code": null, "e": 14029, "s": 13994, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 14052, "s": 14029, "text": " Stone River ELearning" }, { "code": null, "e": 14059, "s": 14052, "text": " Print" }, { "code": null, "e": 14070, "s": 14059, "text": " Add Notes" } ]
How can CONCAT() function be used with MySQL WHERE clause?
Suppose from the table ‘Student’ we want to concatenate the values of columns, ‘Name’, ‘Address’ and ‘Columns’, based on the condition that is also a concatenation of values from columns, ’Name’, ‘Subject’, provided in WHERE clause with the help of CONCAT() function. We can use the following query to give the output − mysql> Select CONCAT(Name, ' ', 'Resident of', ' ', Address,' ','is',' ', 'Studying',' ', Subject)AS 'Detail of Student' from Student WHERE CONCAT(Name, Subject) = "AaravHistory"; +----------------------------------------------+ | Detail of Student | +----------------------------------------------+ | Aarav Resident of Mumbai is Studying History | +----------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1382, "s": 1062, "text": "Suppose from the table ‘Student’ we want to concatenate the values of columns, ‘Name’, ‘Address’ and ‘Columns’, based on the condition that is also a concatenation of values from columns, ’Name’, ‘Subject’, provided in WHERE clause with the help of CONCAT() function. We can use the following query to give the output −" }, { "code": null, "e": 1831, "s": 1382, "text": "mysql> Select CONCAT(Name, ' ', 'Resident of', ' ', Address,' ','is',' ', 'Studying',' ', Subject)AS 'Detail of Student' from Student WHERE CONCAT(Name, Subject) = \"AaravHistory\";\n+----------------------------------------------+\n| Detail of Student |\n+----------------------------------------------+\n| Aarav Resident of Mumbai is Studying History |\n+----------------------------------------------+\n1 row in set (0.00 sec)" } ]
Maximum count of substrings of length K consisting of same characters in C++
Given the task is to find the maximum count of substrings of length K consisting of same characters. Given a string s and another integer K, we have to count the occurrence of sub-strings of size K that have same characters. Out of the sub-strings that are found, we have to choose the sub-string occurring the maximum number of time. Let’s now understand what we have to do using an example − s = ”tuuxyyuuc”, K = 2 2 Here the sub-strings of length 2 and having same characters are: “uu” and “yy” but as it is seen that “yy” occurs only 1 time and “uu” is present 2 times. Therefore the output becomes 2. s = “hhigggff”, K = 3 1 In Max() function, initialize int ans = 0 to store final answer, size = str.size() to store size of string and declare char c to store the characters we need to check. In Max() function, initialize int ans = 0 to store final answer, size = str.size() to store size of string and declare char c to store the characters we need to check. Loop from j = 0 till j < 26 and put c = ‘a’ + j as we will check for each character. Loop from j = 0 till j < 26 and put c = ‘a’ + j as we will check for each character. Initialize variable int CurrCh = 0 for storing the occurrence of sub-array containing the current character. Initialize variable int CurrCh = 0 for storing the occurrence of sub-array containing the current character. Loop from i = 0 till i <= size – K and check if (str[i] != c). If so, then add continue; statement. Loop from i = 0 till i <= size – K and check if (str[i] != c). If so, then add continue; statement. Initialize count = 0 to store length of the sub-array of the current character. Initialize count = 0 to store length of the sub-array of the current character. Create a while loop with condition (i < size && count != K && str[i] == c) and inside the loop increment i and count. Outside the while loop decrease i by 1. Create a while loop with condition (i < size && count != K && str[i] == c) and inside the loop increment i and count. Outside the while loop decrease i by 1. Check if (count == K). If so, then increment CurrCh. Check if (count == K). If so, then increment CurrCh. Close the second For loop and update the value of ans by putting ans = max(ans, CurrCh). Close the second For loop and update the value of ans by putting ans = max(ans, CurrCh). Finally close the first For loop and return ans. Finally close the first For loop and return ans. Live Demo #include <bits/stdc++.h> using namespace std; int Max(string str, int K){ int ans = 0, size = str.size(); char c; //Checking for all characters for (int j = 0; j < 26; j++){ c = 'a' + j; //checking for current character int CurrCh = 0; for (int i = 0; i <= size - K; i++){ if (str[i] != c) continue; //Counting the size of sub-string int count = 0; while (i < size && count != K && str[i] == c){ i++; count++; } i--; //Increment CurrCh if sub-string has length K if (count == K) CurrCh++; } //Update ans ans = max(ans, CurrCh); } return ans; } //main function int main(){ string str = "tuuuxyuuu"; int K = 3; cout << Max(str, K); return 0; } 2
[ { "code": null, "e": 1287, "s": 1062, "text": "Given the task is to find the maximum count of substrings of length K consisting of same characters. Given a string s and another integer K, we have to count the occurrence of sub-strings of size K that have same characters." }, { "code": null, "e": 1397, "s": 1287, "text": "Out of the sub-strings that are found, we have to choose the sub-string occurring the maximum number of time." }, { "code": null, "e": 1456, "s": 1397, "text": "Let’s now understand what we have to do using an example −" }, { "code": null, "e": 1479, "s": 1456, "text": "s = ”tuuxyyuuc”, K = 2" }, { "code": null, "e": 1481, "s": 1479, "text": "2" }, { "code": null, "e": 1668, "s": 1481, "text": "Here the sub-strings of length 2 and having same characters are: “uu” and “yy” but as it is seen that “yy” occurs only 1 time and “uu” is present 2 times. Therefore the output becomes 2." }, { "code": null, "e": 1690, "s": 1668, "text": "s = “hhigggff”, K = 3" }, { "code": null, "e": 1692, "s": 1690, "text": "1" }, { "code": null, "e": 1860, "s": 1692, "text": "In Max() function, initialize int ans = 0 to store final answer, size = str.size() to store size of string and declare char c to store the characters we need to check." }, { "code": null, "e": 2028, "s": 1860, "text": "In Max() function, initialize int ans = 0 to store final answer, size = str.size() to store size of string and declare char c to store the characters we need to check." }, { "code": null, "e": 2113, "s": 2028, "text": "Loop from j = 0 till j < 26 and put c = ‘a’ + j as we will check for each character." }, { "code": null, "e": 2198, "s": 2113, "text": "Loop from j = 0 till j < 26 and put c = ‘a’ + j as we will check for each character." }, { "code": null, "e": 2307, "s": 2198, "text": "Initialize variable int CurrCh = 0 for storing the occurrence of sub-array containing the current character." }, { "code": null, "e": 2416, "s": 2307, "text": "Initialize variable int CurrCh = 0 for storing the occurrence of sub-array containing the current character." }, { "code": null, "e": 2516, "s": 2416, "text": "Loop from i = 0 till i <= size – K and check if (str[i] != c). If so, then add continue; statement." }, { "code": null, "e": 2616, "s": 2516, "text": "Loop from i = 0 till i <= size – K and check if (str[i] != c). If so, then add continue; statement." }, { "code": null, "e": 2696, "s": 2616, "text": "Initialize count = 0 to store length of the sub-array of the current character." }, { "code": null, "e": 2776, "s": 2696, "text": "Initialize count = 0 to store length of the sub-array of the current character." }, { "code": null, "e": 2934, "s": 2776, "text": "Create a while loop with condition (i < size && count != K && str[i] == c) and inside the loop increment i and count. Outside the while loop decrease i by 1." }, { "code": null, "e": 3092, "s": 2934, "text": "Create a while loop with condition (i < size && count != K && str[i] == c) and inside the loop increment i and count. Outside the while loop decrease i by 1." }, { "code": null, "e": 3145, "s": 3092, "text": "Check if (count == K). If so, then increment CurrCh." }, { "code": null, "e": 3198, "s": 3145, "text": "Check if (count == K). If so, then increment CurrCh." }, { "code": null, "e": 3287, "s": 3198, "text": "Close the second For loop and update the value of ans by putting ans = max(ans, CurrCh)." }, { "code": null, "e": 3376, "s": 3287, "text": "Close the second For loop and update the value of ans by putting ans = max(ans, CurrCh)." }, { "code": null, "e": 3425, "s": 3376, "text": "Finally close the first For loop and return ans." }, { "code": null, "e": 3474, "s": 3425, "text": "Finally close the first For loop and return ans." }, { "code": null, "e": 3485, "s": 3474, "text": " Live Demo" }, { "code": null, "e": 4319, "s": 3485, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint Max(string str, int K){\n int ans = 0, size = str.size();\n char c;\n //Checking for all characters\n for (int j = 0; j < 26; j++){\n c = 'a' + j;\n //checking for current character\n int CurrCh = 0;\n for (int i = 0; i <= size - K; i++){\n if (str[i] != c)\n continue;\n //Counting the size of sub-string\n int count = 0;\n while (i < size && count != K && str[i] == c){\n i++;\n count++;\n }\n i--;\n //Increment CurrCh if sub-string has length K\n if (count == K)\n CurrCh++;\n }\n //Update ans\n ans = max(ans, CurrCh);\n }\n return ans;\n}\n//main function\nint main(){\n string str = \"tuuuxyuuu\";\n int K = 3;\n cout << Max(str, K);\n return 0;\n}" }, { "code": null, "e": 4321, "s": 4319, "text": "2" } ]
Maximize the Sum of the given array using given operations - GeeksforGeeks
18 Apr, 2022 Given two arrays A[] and B[] consisting of N integers and an integer K, the task is to maximize the sum calculated from the array A[] by the following operations: For every index in B[] containing 0, the corresponding index in A[] is added to the sum. For every index in B[] containing 1, add the value at the corresponding index in A[] to the sum for atmost K such indices. For the remaining indices, subtract from the sum. Examples: Input: A[] = {5, 4, 6, 2, 8}, B[] = {1, 0, 1, 1, 0}, K = 2 Output: 21 Explanation: Add A[1] and A[4] to the sum as B[1] = B[4] = 0 Therefore, sum = 4 + 8 = 12. Now, add A[0] and A[3] to the sum as K elements can be added. Finally, subtract 2 from the sum. Therefore, the maximum possible sum = 12 + 5 + 6 – 2 = 21Input: A[] = {5, 2, 1, 8, 10, 5}, B[] = {1, 1, 1, 1, 0, 0}, K = 3 Output: 29 Approach: Follow the steps below to solve the problem: Sort the array A[] in decreasing order. To maximize the sum, add first K elements from the sorted array corresponding to which the index in B[] contains 1. Subtract the remaining such elements. Add to the sum all the values in A[] corresponding to an index in B[] containing 0. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ Program to maximize the// sum of the given array#include <bits/stdc++.h>using namespace std; // Comparator to sort the array// in ascending orderbool compare(pairs<int, int> p1, pairs<int, int> p2){ return p1.first > p2.first;} // Function to maximize the sum of// the given arrayint maximizeScore(int A[], int B[], int K, int N){ // Stores {A[i], B[i]} pairs vector<pairs<int, int> > pairs(N); for (int i = 0; i < N; i++) { pairs[i] = make_pairs(A[i], B[i]); } // Sort in descending order of the // values in the array A[] sort(pairs.begin(), pairs.end(), compare); // Stores the maximum sum int sum = 0; for (int i = 0; i < N; i++) { // If B[i] is equal to 0 if (pairs[i].second == 0) { // Simply add A[i] to the sum sum += pairs[i].first; } else if (pairs[i].second == 1) { // Add the highest K numbers if (K > 0) { sum += pairs[i].first; K--; } // Subtract from the sum else { sum -= pairs[i].first; } } } // Return the sum return sum;} // Driver Codeint main(){ int A[] = { 5, 4, 6, 2, 8 }; int B[] = { 1, 0, 1, 1, 0 }; int K = 2; int N = sizeof(A) / sizeof(int); cout << maximizeScore(A, B, K, N); return 0;} // Java program to maximise the// sum of the given arrayimport java.util.*; class Pairs implements Comparable<Pairs>{ int first, second; Pairs(int x, int y) { first = x; second = y; } public int compareTo(Pairs p) { return p.first - first; }} class GFG{ // Function to maximise the sum of// the given arraystatic int maximiseScore(int A[], int B[], int K, int N){ // Stores {A[i], B[i]} pairs ArrayList<Pairs> pairs = new ArrayList<>(); for(int i = 0; i < N; i++) { pairs.add(new Pairs(A[i], B[i])); } // Sort in descending order of the // values in the array A[] Collections.sort(pairs); // Stores the maximum sum int sum = 0; for(int i = 0; i < N; i++) { // If B[i] is equal to 0 if (pairs.get(i).second == 0) { // Simply add A[i] to the sum sum += pairs.get(i).first; } else if (pairs.get(i).second == 1) { // Add the highest K numbers if (K > 0) { sum += pairs.get(i).first; K--; } // Subtract from the sum else { sum -= pairs.get(i).first; } } } // Return the sum return sum;} // Driver Codepublic static void main(String[] args){ int A[] = { 5, 4, 6, 2, 8 }; int B[] = { 1, 0, 1, 1, 0 }; int K = 2; int N = A.length; System.out.print(maximiseScore(A, B, K, N));}} // This code is contributed by jrishabh99 # Python Program to maximise the# sum of the given array # Comparator to sort the array# in ascending orderdef compare(p1, p2): return p1[0] > p2[0] # Function to maximise the sum of# the given arraydef maximiseScore(A, B, K, N): # Stores {A[i], B[i]} pairs pairs = [] for i in range(N): pairs.append([A[i], B[i]]) # Sort in descending order of the # values in the array A[] pairs.sort(key = lambda x:x[0], reverse = True) # Stores the maximum sum Sum = 0 for i in range(N): # If B[i] is equal to 0 if(pairs[i][1] == 0): # Simply add A[i] to the sum Sum += pairs[i][0] elif(pairs[i][1] == 1): # Add the highest K numbers if(K > 0): Sum += pairs[i][0] K -= 1 # Subtract from the sum else: Sum -= pairs[i][0] # Return the sum return Sum # Driver CodeA = [5, 4, 6, 2, 8]B = [1, 0, 1, 1, 0]K = 2N = len(A)print(maximiseScore(A, B, K, N)) # This code is contributed by avanitrachhadiya2155 <script> // JavaScript Program to maximize the// sum of the given array // Comparator to sort the array// in ascending orderfunction compare(p1,p2){ return p2[0] - p1[0];} // Function to maximize the sum of// the given arrayfunction maximizeScore(A, B, K, N){ // Stores {A[i], B[i]} pairs let pairs = new Array(N); for (let i = 0; i < N; i++) { pairs[i] = [A[i], B[i]]; } // Sort in descending order of the // values in the array A[] pairs.sort(compare); // Stores the maximum sum let sum = 0; for (let i = 0; i < N; i++) { // If B[i] is equal to 0 if (pairs[i][1] == 0) { // Simply add A[i] to the sum sum += pairs[i][0]; } else if (pairs[i][1] == 1) { // Add the highest K numbers if (K > 0) { sum += pairs[i][0]; K--; } // Subtract from the sum else { sum -= pairs[i][0]; } } } // Return the sum return sum;} // Driver Codelet A = [ 5, 4, 6, 2, 8 ];let B = [ 1, 0, 1, 1, 0 ];let K = 2;let N = A.length;document.write(maximizeScore(A, B, K, N),"</br>"); // This code is contributed by shinjanpatra.</script> 21 Time complexity: O(N*log(N))Auxiliary Space: O(N) jrishabh99 avanitrachhadiya2155 chhabradhanvi shinjanpatra Arrays Greedy Mathematical Sorting Arrays Greedy Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search 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": 25023, "s": 24995, "text": "\n18 Apr, 2022" }, { "code": null, "e": 25188, "s": 25023, "text": "Given two arrays A[] and B[] consisting of N integers and an integer K, the task is to maximize the sum calculated from the array A[] by the following operations: " }, { "code": null, "e": 25277, "s": 25188, "text": "For every index in B[] containing 0, the corresponding index in A[] is added to the sum." }, { "code": null, "e": 25450, "s": 25277, "text": "For every index in B[] containing 1, add the value at the corresponding index in A[] to the sum for atmost K such indices. For the remaining indices, subtract from the sum." }, { "code": null, "e": 25460, "s": 25450, "text": "Examples:" }, { "code": null, "e": 25852, "s": 25460, "text": "Input: A[] = {5, 4, 6, 2, 8}, B[] = {1, 0, 1, 1, 0}, K = 2 Output: 21 Explanation: Add A[1] and A[4] to the sum as B[1] = B[4] = 0 Therefore, sum = 4 + 8 = 12. Now, add A[0] and A[3] to the sum as K elements can be added. Finally, subtract 2 from the sum. Therefore, the maximum possible sum = 12 + 5 + 6 – 2 = 21Input: A[] = {5, 2, 1, 8, 10, 5}, B[] = {1, 1, 1, 1, 0, 0}, K = 3 Output: 29 " }, { "code": null, "e": 25862, "s": 25852, "text": "Approach:" }, { "code": null, "e": 25909, "s": 25862, "text": "Follow the steps below to solve the problem: " }, { "code": null, "e": 25949, "s": 25909, "text": "Sort the array A[] in decreasing order." }, { "code": null, "e": 26103, "s": 25949, "text": "To maximize the sum, add first K elements from the sorted array corresponding to which the index in B[] contains 1. Subtract the remaining such elements." }, { "code": null, "e": 26187, "s": 26103, "text": "Add to the sum all the values in A[] corresponding to an index in B[] containing 0." }, { "code": null, "e": 26238, "s": 26187, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26242, "s": 26238, "text": "C++" }, { "code": null, "e": 26247, "s": 26242, "text": "Java" }, { "code": null, "e": 26255, "s": 26247, "text": "Python3" }, { "code": null, "e": 26266, "s": 26255, "text": "Javascript" }, { "code": "// C++ Program to maximize the// sum of the given array#include <bits/stdc++.h>using namespace std; // Comparator to sort the array// in ascending orderbool compare(pairs<int, int> p1, pairs<int, int> p2){ return p1.first > p2.first;} // Function to maximize the sum of// the given arrayint maximizeScore(int A[], int B[], int K, int N){ // Stores {A[i], B[i]} pairs vector<pairs<int, int> > pairs(N); for (int i = 0; i < N; i++) { pairs[i] = make_pairs(A[i], B[i]); } // Sort in descending order of the // values in the array A[] sort(pairs.begin(), pairs.end(), compare); // Stores the maximum sum int sum = 0; for (int i = 0; i < N; i++) { // If B[i] is equal to 0 if (pairs[i].second == 0) { // Simply add A[i] to the sum sum += pairs[i].first; } else if (pairs[i].second == 1) { // Add the highest K numbers if (K > 0) { sum += pairs[i].first; K--; } // Subtract from the sum else { sum -= pairs[i].first; } } } // Return the sum return sum;} // Driver Codeint main(){ int A[] = { 5, 4, 6, 2, 8 }; int B[] = { 1, 0, 1, 1, 0 }; int K = 2; int N = sizeof(A) / sizeof(int); cout << maximizeScore(A, B, K, N); return 0;}", "e": 27662, "s": 26266, "text": null }, { "code": "// Java program to maximise the// sum of the given arrayimport java.util.*; class Pairs implements Comparable<Pairs>{ int first, second; Pairs(int x, int y) { first = x; second = y; } public int compareTo(Pairs p) { return p.first - first; }} class GFG{ // Function to maximise the sum of// the given arraystatic int maximiseScore(int A[], int B[], int K, int N){ // Stores {A[i], B[i]} pairs ArrayList<Pairs> pairs = new ArrayList<>(); for(int i = 0; i < N; i++) { pairs.add(new Pairs(A[i], B[i])); } // Sort in descending order of the // values in the array A[] Collections.sort(pairs); // Stores the maximum sum int sum = 0; for(int i = 0; i < N; i++) { // If B[i] is equal to 0 if (pairs.get(i).second == 0) { // Simply add A[i] to the sum sum += pairs.get(i).first; } else if (pairs.get(i).second == 1) { // Add the highest K numbers if (K > 0) { sum += pairs.get(i).first; K--; } // Subtract from the sum else { sum -= pairs.get(i).first; } } } // Return the sum return sum;} // Driver Codepublic static void main(String[] args){ int A[] = { 5, 4, 6, 2, 8 }; int B[] = { 1, 0, 1, 1, 0 }; int K = 2; int N = A.length; System.out.print(maximiseScore(A, B, K, N));}} // This code is contributed by jrishabh99", "e": 29262, "s": 27662, "text": null }, { "code": "# Python Program to maximise the# sum of the given array # Comparator to sort the array# in ascending orderdef compare(p1, p2): return p1[0] > p2[0] # Function to maximise the sum of# the given arraydef maximiseScore(A, B, K, N): # Stores {A[i], B[i]} pairs pairs = [] for i in range(N): pairs.append([A[i], B[i]]) # Sort in descending order of the # values in the array A[] pairs.sort(key = lambda x:x[0], reverse = True) # Stores the maximum sum Sum = 0 for i in range(N): # If B[i] is equal to 0 if(pairs[i][1] == 0): # Simply add A[i] to the sum Sum += pairs[i][0] elif(pairs[i][1] == 1): # Add the highest K numbers if(K > 0): Sum += pairs[i][0] K -= 1 # Subtract from the sum else: Sum -= pairs[i][0] # Return the sum return Sum # Driver CodeA = [5, 4, 6, 2, 8]B = [1, 0, 1, 1, 0]K = 2N = len(A)print(maximiseScore(A, B, K, N)) # This code is contributed by avanitrachhadiya2155", "e": 30387, "s": 29262, "text": null }, { "code": "<script> // JavaScript Program to maximize the// sum of the given array // Comparator to sort the array// in ascending orderfunction compare(p1,p2){ return p2[0] - p1[0];} // Function to maximize the sum of// the given arrayfunction maximizeScore(A, B, K, N){ // Stores {A[i], B[i]} pairs let pairs = new Array(N); for (let i = 0; i < N; i++) { pairs[i] = [A[i], B[i]]; } // Sort in descending order of the // values in the array A[] pairs.sort(compare); // Stores the maximum sum let sum = 0; for (let i = 0; i < N; i++) { // If B[i] is equal to 0 if (pairs[i][1] == 0) { // Simply add A[i] to the sum sum += pairs[i][0]; } else if (pairs[i][1] == 1) { // Add the highest K numbers if (K > 0) { sum += pairs[i][0]; K--; } // Subtract from the sum else { sum -= pairs[i][0]; } } } // Return the sum return sum;} // Driver Codelet A = [ 5, 4, 6, 2, 8 ];let B = [ 1, 0, 1, 1, 0 ];let K = 2;let N = A.length;document.write(maximizeScore(A, B, K, N),\"</br>\"); // This code is contributed by shinjanpatra.</script>", "e": 31623, "s": 30387, "text": null }, { "code": null, "e": 31626, "s": 31623, "text": "21" }, { "code": null, "e": 31679, "s": 31628, "text": "Time complexity: O(N*log(N))Auxiliary Space: O(N) " }, { "code": null, "e": 31690, "s": 31679, "text": "jrishabh99" }, { "code": null, "e": 31711, "s": 31690, "text": "avanitrachhadiya2155" }, { "code": null, "e": 31725, "s": 31711, "text": "chhabradhanvi" }, { "code": null, "e": 31738, "s": 31725, "text": "shinjanpatra" }, { "code": null, "e": 31745, "s": 31738, "text": "Arrays" }, { "code": null, "e": 31752, "s": 31745, "text": "Greedy" }, { "code": null, "e": 31765, "s": 31752, "text": "Mathematical" }, { "code": null, "e": 31773, "s": 31765, "text": "Sorting" }, { "code": null, "e": 31780, "s": 31773, "text": "Arrays" }, { "code": null, "e": 31787, "s": 31780, "text": "Greedy" }, { "code": null, "e": 31800, "s": 31787, "text": "Mathematical" }, { "code": null, "e": 31808, "s": 31800, "text": "Sorting" }, { "code": null, "e": 31906, "s": 31808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31915, "s": 31906, "text": "Comments" }, { "code": null, "e": 31928, "s": 31915, "text": "Old Comments" }, { "code": null, "e": 31976, "s": 31928, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32020, "s": 31976, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32043, "s": 32020, "text": "Introduction to Arrays" }, { "code": null, "e": 32075, "s": 32043, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32089, "s": 32075, "text": "Linear Search" }, { "code": null, "e": 32140, "s": 32089, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 32191, "s": 32140, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 32249, "s": 32191, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 32280, "s": 32249, "text": "Huffman Coding | Greedy Algo-3" } ]
ATM using file handling in C++ - GeeksforGeeks
04 Feb, 2021 In this article, the task is to implement an ATM with functions like add, delete, search, and update users using file handling in C++. File handling: File handling is used to store the output of a program in a file. In C++, files use three classes fstream, ifstream, ofstream available in fstream header file for file handling. Some Important Instructions: The password for Admin login is 1234.Initially, the file is empty make sure to first log in as admin and add a user, and then login as a user. The password for Admin login is 1234. Initially, the file is empty make sure to first log in as admin and add a user, and then login as a user. Approach: Select user type and input password. In the given menu, select the basic operation and enter the details in the operations like add, delete, search and update users. After performing all the functions and operations, exit from the ATM system. All the file operations are done in a file named aaa.txt, where the data is written using ofstream mode and can be read using ifstream mode. After this, the file must be closed using <filename>.close(). Below is the implementation of the above approach: C++ // C++ code to implement an ATM and// its basic functions#include <fstream>#include <iostream>#include <limits>#include <string.h>#include <unistd.h>using namespace std; // Class ATM to get user detailsclass atm {private: char username[30]; int password; int balance; public: char* usernames(void) { // Return username return the username; } int passwords(void) { // Return the password return password; } // Function to get the data void getData(void) { cin.ignore( numeric_limits<streamsize>::max(), '\n'); cout << "\nEnter username:"; cin.getline(username, 30); cout << "\nEnter 4-digit " << "password:"; cin >> password; cin.ignore( numeric_limits<streamsize>::max(), '\n'); cout << "\nEnter initial" << " balance:"; cin >> balance; cin.ignore( numeric_limits<streamsize>::max(), '\n'); } // Function displaying the data void showData(void) { cout << "Username:" << username << ", Password:" << password << ", Balance:" << balance << endl; } // Member Functions int adduser(); int viewallusers(); int deleteuser(char*); void updateuserasdeposit(char*); void updateuseraswithdraw(char*); int searchspecificuser(char*, int); int searchallusertodisplay(char*);}; // Function to implement functionality// of ATM Uservoid atmUser(){ atm a; char uname[30]; int pass, ch, ch1, ch2, found = 0; mainmenu: // System("cls"); cout << "\nWelcome to GeeksforGeeks ATM"; cout << "\nLogin as :\n1. Admin\n2." << " User\n3. " "Exit\nChoose one : "; cin >> ch; switch (ch) { case 1: rerun: // System("cls"); cout << "\nEnter details to" << " login as Admin\n"; cout << "\nEnter password:"; cin >> pass; if (pass == 1234) { admin: // System("cls"); cout << "\nWelcome to" << " Admin Menu"; cout << "\n1. Add User\n2." << " Delete User\n3. " "View All User\n4. " << "Exit"; cout << "\nSelect one : "; cin >> ch1; switch (ch1) { case 1: a.adduser(); goto admin; case 2: cout << "\nEnter the " << "Username to be " "deleted : "; cin.ignore( numeric_limits<streamsize>::max(), '\n'); cin.getline(uname, 30); a.deleteuser(uname); goto admin; case 3: a.viewallusers(); // sleep(4); goto admin; case 4: break; } } else { cout << "\nDetails are " << "incorrect ! Please" " try again"; cin.get(); goto rerun; } goto mainmenu; case 2: // System("cls"); cout << "\n Enter details to" << " login as User\n"; cin.ignore( numeric_limits<streamsize>::max(), '\n'); cout << "Enter username:"; cin.getline(uname, 30); cout << "\nEnter password:"; cin >> pass; found = a.searchspecificuser( uname, pass); if (found) { user: // System("cls"); cout << "\nWelcome " << uname; cout << "\nWelcome to" << " User Menu"; cout << "\n1. Deposit\n2." << " Withdraw\n3. View " "Account\n4. " << "Exit\nEnter your choice:"; cin >> ch2; switch (ch2) { case 1: a.updateuserasdeposit(uname); goto user; case 2: a.updateuseraswithdraw(uname); goto user; case 3: a.searchallusertodisplay(uname); // sleep(4); goto user; case 4: cout << "Thank you"; break; } } else { cout << "\nNo account found" << " with username " ":(\n\nHit ENTER to continue " << uname; cin.get(); } goto mainmenu; case 3: cout << "\nThankyou for " << "banking with " << "GeeksforGeeks"; cin.get(); break; }} // Function to add userint atm::adduser(){ atm a; ofstream file; // Open file in write mode file.open("aaa.txt", ios::out | ios::app); if (!file) { cout << "Error in creating " << "file.." << endl; return 0; } // Read from user a.getData(); // Write into file file.write((char*)&a, sizeof(a)); // Close the file file.close(); return 0;} // View Usersint atm::viewallusers(){ atm a; ifstream file1; // Open file in read mode file1.open("aaa.txt", ios::in); if (!file1) { cout << "Error in opening file.."; return 0; } // Read data from file file1.read((char*)&a, sizeof(a)); while (!file1.eof()) { // Display data on monitor a.showData(); file1.read((char*)&a, sizeof(a)); } // Close the file file1.close(); return 0;} // Function to delete the userint atm::deleteuser(char* uname){ atm a; fstream original, temp; original.open("aaa.txt", ios::in); if (!original) { cout << "\nfile not found"; return 0; } else { temp.open("temp.txt", ios::out | ios::app); original.read((char*)&a, sizeof(a)); // Till end of file is reached while (!original.eof()) { if (!strcmp(a.usernames(), uname)) { cout << "data found " << "and deleted\n" << a.username << "\n"; } else { temp.write((char*)&a, sizeof(a)); } original.read((char*)&a, sizeof(a)); } original.close(); temp.close(); remove("aaa.txt"); rename("temp.txt", "aaa.txt"); a.viewallusers(); } return 0;} // Function to update user by// depositing moneyvoid atm::updateuserasdeposit(char* uname){ atm a; fstream file, temp; file.open("aaa.txt", ios::in | ios::out | ios::ate); temp.open("temp.txt", ios::out | ios::app); file.seekg(0); file.read((char*)&a, sizeof(a)); // Till end of the file while (!file.eof()) { if (!strcmp(a.usernames(), uname)) { int b; cout << "\nEnter amount " << "to deposit:"; cin >> b; a.balance = a.balance + b; cout << "\nBalance is:" << a.balance; temp.write((char*)&a, sizeof(a)); } else { temp.write((char*)&a, sizeof(a)); } file.read((char*)&a, sizeof(a)); } file.close(); temp.close(); remove("aaa.txt"); rename("temp.txt", "aaa.txt");} // Function to update user by// depositing withdrawing moneyvoid atm::updateuseraswithdraw(char* uname){ atm a; fstream file, temp; file.open("aaa.txt", ios::in | ios::out | ios::ate); temp.open("temp.txt", ios::out | ios::app); file.seekg(0); file.read((char*)&a, sizeof(a)); // Till end of file is reached while (!file.eof()) { if (!strcmp(a.usernames(), uname)) { int b; cout << "\nEnter amount " << "to withdraw:"; cin >> b; if (a.balance < b) { cout << "\nInsufficient " << "balance to withdraw"; } else { a.balance = a.balance - b; temp.write((char*)&a, sizeof(a)); cout << "\nBalance is:" << a.balance; } } else { temp.write((char*)&a, sizeof(a)); } file.read((char*)&a, sizeof(a)); } // Close the file file.close(); temp.close(); remove("aaa.txt"); rename("temp.txt", "aaa.txt");} // Search userint atm::searchspecificuser( char* uname, int pass){ atm a; fstream f; // Open the file f.open("aaa.txt", ios::in); if (!f) { cout << "Error in opening file.."; return 0; } // Read data from file f.read((char*)&a, sizeof(a)); while (!f.eof()) { if (!strcmp(a.usernames(), uname)) { if (a.passwords() == pass) { return 1; } } f.read((char*)&a, sizeof(a)); } // Close the file f.close(); return 0;} // Search specific userint atm::searchallusertodisplay( char* uname){ atm a; fstream file1; // Open the file file1.open("aaa.txt", ios::in); if (!file1) { cout << "Error in opening file.."; return 0; } // Read data from file file1.read((char*)&a, sizeof(a)); while (!file1.eof()) { if (!strcmp(a.usernames(), uname)) { a.showData(); return 0; } file1.read((char*)&a, sizeof(a)); } // Close the file file1.close(); return 0;} // Driver Codeint main(){ // Function Call atmUser(); return 0;} Output: C-File Handling cpp-file-handling Technical Scripter 2020 C++ Project Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Operator Overloading in C++ Constructors in C++ Virtual Function in C++ Socket Programming in C/C++ SDE SHEET - A Complete Guide for SDE Preparation XML parsing in Python Python | Simple GUI calculator using Tkinter Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python
[ { "code": null, "e": 24408, "s": 24380, "text": "\n04 Feb, 2021" }, { "code": null, "e": 24545, "s": 24408, "text": "In this article, the task is to implement an ATM with functions like add, delete, search, and update users using file handling in C++. " }, { "code": null, "e": 24560, "s": 24545, "text": "File handling:" }, { "code": null, "e": 24626, "s": 24560, "text": "File handling is used to store the output of a program in a file." }, { "code": null, "e": 24738, "s": 24626, "text": "In C++, files use three classes fstream, ifstream, ofstream available in fstream header file for file handling." }, { "code": null, "e": 24767, "s": 24738, "text": "Some Important Instructions:" }, { "code": null, "e": 24910, "s": 24767, "text": "The password for Admin login is 1234.Initially, the file is empty make sure to first log in as admin and add a user, and then login as a user." }, { "code": null, "e": 24948, "s": 24910, "text": "The password for Admin login is 1234." }, { "code": null, "e": 25054, "s": 24948, "text": "Initially, the file is empty make sure to first log in as admin and add a user, and then login as a user." }, { "code": null, "e": 25064, "s": 25054, "text": "Approach:" }, { "code": null, "e": 25102, "s": 25064, "text": "Select user type and input password. " }, { "code": null, "e": 25231, "s": 25102, "text": "In the given menu, select the basic operation and enter the details in the operations like add, delete, search and update users." }, { "code": null, "e": 25308, "s": 25231, "text": "After performing all the functions and operations, exit from the ATM system." }, { "code": null, "e": 25449, "s": 25308, "text": "All the file operations are done in a file named aaa.txt, where the data is written using ofstream mode and can be read using ifstream mode." }, { "code": null, "e": 25511, "s": 25449, "text": "After this, the file must be closed using <filename>.close()." }, { "code": null, "e": 25562, "s": 25511, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25566, "s": 25562, "text": "C++" }, { "code": "// C++ code to implement an ATM and// its basic functions#include <fstream>#include <iostream>#include <limits>#include <string.h>#include <unistd.h>using namespace std; // Class ATM to get user detailsclass atm {private: char username[30]; int password; int balance; public: char* usernames(void) { // Return username return the username; } int passwords(void) { // Return the password return password; } // Function to get the data void getData(void) { cin.ignore( numeric_limits<streamsize>::max(), '\\n'); cout << \"\\nEnter username:\"; cin.getline(username, 30); cout << \"\\nEnter 4-digit \" << \"password:\"; cin >> password; cin.ignore( numeric_limits<streamsize>::max(), '\\n'); cout << \"\\nEnter initial\" << \" balance:\"; cin >> balance; cin.ignore( numeric_limits<streamsize>::max(), '\\n'); } // Function displaying the data void showData(void) { cout << \"Username:\" << username << \", Password:\" << password << \", Balance:\" << balance << endl; } // Member Functions int adduser(); int viewallusers(); int deleteuser(char*); void updateuserasdeposit(char*); void updateuseraswithdraw(char*); int searchspecificuser(char*, int); int searchallusertodisplay(char*);}; // Function to implement functionality// of ATM Uservoid atmUser(){ atm a; char uname[30]; int pass, ch, ch1, ch2, found = 0; mainmenu: // System(\"cls\"); cout << \"\\nWelcome to GeeksforGeeks ATM\"; cout << \"\\nLogin as :\\n1. Admin\\n2.\" << \" User\\n3. \" \"Exit\\nChoose one : \"; cin >> ch; switch (ch) { case 1: rerun: // System(\"cls\"); cout << \"\\nEnter details to\" << \" login as Admin\\n\"; cout << \"\\nEnter password:\"; cin >> pass; if (pass == 1234) { admin: // System(\"cls\"); cout << \"\\nWelcome to\" << \" Admin Menu\"; cout << \"\\n1. Add User\\n2.\" << \" Delete User\\n3. \" \"View All User\\n4. \" << \"Exit\"; cout << \"\\nSelect one : \"; cin >> ch1; switch (ch1) { case 1: a.adduser(); goto admin; case 2: cout << \"\\nEnter the \" << \"Username to be \" \"deleted : \"; cin.ignore( numeric_limits<streamsize>::max(), '\\n'); cin.getline(uname, 30); a.deleteuser(uname); goto admin; case 3: a.viewallusers(); // sleep(4); goto admin; case 4: break; } } else { cout << \"\\nDetails are \" << \"incorrect ! Please\" \" try again\"; cin.get(); goto rerun; } goto mainmenu; case 2: // System(\"cls\"); cout << \"\\n Enter details to\" << \" login as User\\n\"; cin.ignore( numeric_limits<streamsize>::max(), '\\n'); cout << \"Enter username:\"; cin.getline(uname, 30); cout << \"\\nEnter password:\"; cin >> pass; found = a.searchspecificuser( uname, pass); if (found) { user: // System(\"cls\"); cout << \"\\nWelcome \" << uname; cout << \"\\nWelcome to\" << \" User Menu\"; cout << \"\\n1. Deposit\\n2.\" << \" Withdraw\\n3. View \" \"Account\\n4. \" << \"Exit\\nEnter your choice:\"; cin >> ch2; switch (ch2) { case 1: a.updateuserasdeposit(uname); goto user; case 2: a.updateuseraswithdraw(uname); goto user; case 3: a.searchallusertodisplay(uname); // sleep(4); goto user; case 4: cout << \"Thank you\"; break; } } else { cout << \"\\nNo account found\" << \" with username \" \":(\\n\\nHit ENTER to continue \" << uname; cin.get(); } goto mainmenu; case 3: cout << \"\\nThankyou for \" << \"banking with \" << \"GeeksforGeeks\"; cin.get(); break; }} // Function to add userint atm::adduser(){ atm a; ofstream file; // Open file in write mode file.open(\"aaa.txt\", ios::out | ios::app); if (!file) { cout << \"Error in creating \" << \"file..\" << endl; return 0; } // Read from user a.getData(); // Write into file file.write((char*)&a, sizeof(a)); // Close the file file.close(); return 0;} // View Usersint atm::viewallusers(){ atm a; ifstream file1; // Open file in read mode file1.open(\"aaa.txt\", ios::in); if (!file1) { cout << \"Error in opening file..\"; return 0; } // Read data from file file1.read((char*)&a, sizeof(a)); while (!file1.eof()) { // Display data on monitor a.showData(); file1.read((char*)&a, sizeof(a)); } // Close the file file1.close(); return 0;} // Function to delete the userint atm::deleteuser(char* uname){ atm a; fstream original, temp; original.open(\"aaa.txt\", ios::in); if (!original) { cout << \"\\nfile not found\"; return 0; } else { temp.open(\"temp.txt\", ios::out | ios::app); original.read((char*)&a, sizeof(a)); // Till end of file is reached while (!original.eof()) { if (!strcmp(a.usernames(), uname)) { cout << \"data found \" << \"and deleted\\n\" << a.username << \"\\n\"; } else { temp.write((char*)&a, sizeof(a)); } original.read((char*)&a, sizeof(a)); } original.close(); temp.close(); remove(\"aaa.txt\"); rename(\"temp.txt\", \"aaa.txt\"); a.viewallusers(); } return 0;} // Function to update user by// depositing moneyvoid atm::updateuserasdeposit(char* uname){ atm a; fstream file, temp; file.open(\"aaa.txt\", ios::in | ios::out | ios::ate); temp.open(\"temp.txt\", ios::out | ios::app); file.seekg(0); file.read((char*)&a, sizeof(a)); // Till end of the file while (!file.eof()) { if (!strcmp(a.usernames(), uname)) { int b; cout << \"\\nEnter amount \" << \"to deposit:\"; cin >> b; a.balance = a.balance + b; cout << \"\\nBalance is:\" << a.balance; temp.write((char*)&a, sizeof(a)); } else { temp.write((char*)&a, sizeof(a)); } file.read((char*)&a, sizeof(a)); } file.close(); temp.close(); remove(\"aaa.txt\"); rename(\"temp.txt\", \"aaa.txt\");} // Function to update user by// depositing withdrawing moneyvoid atm::updateuseraswithdraw(char* uname){ atm a; fstream file, temp; file.open(\"aaa.txt\", ios::in | ios::out | ios::ate); temp.open(\"temp.txt\", ios::out | ios::app); file.seekg(0); file.read((char*)&a, sizeof(a)); // Till end of file is reached while (!file.eof()) { if (!strcmp(a.usernames(), uname)) { int b; cout << \"\\nEnter amount \" << \"to withdraw:\"; cin >> b; if (a.balance < b) { cout << \"\\nInsufficient \" << \"balance to withdraw\"; } else { a.balance = a.balance - b; temp.write((char*)&a, sizeof(a)); cout << \"\\nBalance is:\" << a.balance; } } else { temp.write((char*)&a, sizeof(a)); } file.read((char*)&a, sizeof(a)); } // Close the file file.close(); temp.close(); remove(\"aaa.txt\"); rename(\"temp.txt\", \"aaa.txt\");} // Search userint atm::searchspecificuser( char* uname, int pass){ atm a; fstream f; // Open the file f.open(\"aaa.txt\", ios::in); if (!f) { cout << \"Error in opening file..\"; return 0; } // Read data from file f.read((char*)&a, sizeof(a)); while (!f.eof()) { if (!strcmp(a.usernames(), uname)) { if (a.passwords() == pass) { return 1; } } f.read((char*)&a, sizeof(a)); } // Close the file f.close(); return 0;} // Search specific userint atm::searchallusertodisplay( char* uname){ atm a; fstream file1; // Open the file file1.open(\"aaa.txt\", ios::in); if (!file1) { cout << \"Error in opening file..\"; return 0; } // Read data from file file1.read((char*)&a, sizeof(a)); while (!file1.eof()) { if (!strcmp(a.usernames(), uname)) { a.showData(); return 0; } file1.read((char*)&a, sizeof(a)); } // Close the file file1.close(); return 0;} // Driver Codeint main(){ // Function Call atmUser(); return 0;}", "e": 35354, "s": 25566, "text": null }, { "code": null, "e": 35362, "s": 35354, "text": "Output:" }, { "code": null, "e": 35378, "s": 35362, "text": "C-File Handling" }, { "code": null, "e": 35396, "s": 35378, "text": "cpp-file-handling" }, { "code": null, "e": 35420, "s": 35396, "text": "Technical Scripter 2020" }, { "code": null, "e": 35424, "s": 35420, "text": "C++" }, { "code": null, "e": 35432, "s": 35424, "text": "Project" }, { "code": null, "e": 35451, "s": 35432, "text": "Technical Scripter" }, { "code": null, "e": 35455, "s": 35451, "text": "CPP" }, { "code": null, "e": 35553, "s": 35455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35577, "s": 35553, "text": "C++ Classes and Objects" }, { "code": null, "e": 35605, "s": 35577, "text": "Operator Overloading in C++" }, { "code": null, "e": 35625, "s": 35605, "text": "Constructors in C++" }, { "code": null, "e": 35649, "s": 35625, "text": "Virtual Function in C++" }, { "code": null, "e": 35677, "s": 35649, "text": "Socket Programming in C/C++" }, { "code": null, "e": 35726, "s": 35677, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 35748, "s": 35726, "text": "XML parsing in Python" }, { "code": null, "e": 35793, "s": 35748, "text": "Python | Simple GUI calculator using Tkinter" }, { "code": null, "e": 35848, "s": 35793, "text": "Implementing Web Scraping in Python with BeautifulSoup" } ]
Concept of Margin in Android - GeeksforGeeks
23 Feb, 2021 In order to style and positioned user interface elements, we use standard attributes in android known as Margin and Padding. In this article, all the confusion about Margin is explained with examples. Margin specifies an extra space outside that View on which we applied Margin. In simple words, Margin means to push outside. Diagrammatically, the margin is shown below: Syntax: android:layout_margin=”size in dp” The above syntax will specify an extra space in all directions i.e. left, right, top, bottom. Its code working is shown below: XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#1aff1a"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="100dp" android:background="#009933" android:text="GeeksforGeeks" android:textColor="@color/white" android:textSize="30sp" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> Output: This Margin is equal in all directions. Let’s have a look at the following output. Layout_Margin But this attribute has one disadvantage i.e. When we want to specify space gap in only one direction suppose left or right then it is not possible with android:layout_margin. For that Margin provide other attributes as: 1. android:layout_marginLeft: It specifies extra space on the left side of the view. Its value must be positive. Example: XML <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#1aff1a"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:background="#009933" android:text="GeeksforGeeks" android:textColor="@color/white" android:textSize="30sp" /> </LinearLayout> Output: 2. android:layout_marginRight: It specifies extra space on the right side of the view. Example: XML <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#1aff1a"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="190dp" android:background="#009933" android:text="GeeksforGeeks" android:textColor="@color/white" android:textSize="30sp" /> </LinearLayout> Output: 3. android:layout_marginTop: It specifies the extra space on the top side of the view. Example: XML <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#1aff1a"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="150dp" android:background="#009933" android:text="GeeksforGeeks" android:textColor="@color/white" android:textSize="30sp" /> </LinearLayout> Output: 4. android:layout_marginBottom: It specifies the extra space on the bottom side of the view. Example: XML <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#1aff1a"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="150dp" android:background="#009933" android:text="GeeksforGeeks" android:textColor="@color/white" android:textSize="30sp" /> </LinearLayout> Output: Android-Misc Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? How to Get Current Location in Android? Flexbox-Layout in Android Android Listview in Java with Example Fragment Lifecycle in Android How to Save Data to the Firebase Realtime Database in Android?
[ { "code": null, "e": 26381, "s": 26353, "text": "\n23 Feb, 2021" }, { "code": null, "e": 26752, "s": 26381, "text": "In order to style and positioned user interface elements, we use standard attributes in android known as Margin and Padding. In this article, all the confusion about Margin is explained with examples. Margin specifies an extra space outside that View on which we applied Margin. In simple words, Margin means to push outside. Diagrammatically, the margin is shown below:" }, { "code": null, "e": 26760, "s": 26752, "text": "Syntax:" }, { "code": null, "e": 26795, "s": 26760, "text": "android:layout_margin=”size in dp”" }, { "code": null, "e": 26864, "s": 26795, "text": "The above syntax will specify an extra space in all directions i.e. " }, { "code": null, "e": 26870, "s": 26864, "text": "left," }, { "code": null, "e": 26877, "s": 26870, "text": "right," }, { "code": null, "e": 26882, "s": 26877, "text": "top," }, { "code": null, "e": 26891, "s": 26882, "text": "bottom. " }, { "code": null, "e": 26924, "s": 26891, "text": "Its code working is shown below:" }, { "code": null, "e": 26928, "s": 26924, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout 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\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"#1aff1a\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"100dp\" android:background=\"#009933\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/white\" android:textSize=\"30sp\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 27790, "s": 26928, "text": null }, { "code": null, "e": 27798, "s": 27790, "text": "Output:" }, { "code": null, "e": 27881, "s": 27798, "text": "This Margin is equal in all directions. Let’s have a look at the following output." }, { "code": null, "e": 27895, "s": 27881, "text": "Layout_Margin" }, { "code": null, "e": 28115, "s": 27895, "text": "But this attribute has one disadvantage i.e. When we want to specify space gap in only one direction suppose left or right then it is not possible with android:layout_margin. For that Margin provide other attributes as:" }, { "code": null, "e": 28239, "s": 28115, "text": "1. android:layout_marginLeft: It specifies extra space on the left side of the view. Its value must be positive. " }, { "code": null, "e": 28270, "s": 28239, "text": "Example: " }, { "code": null, "e": 28274, "s": 28270, "text": "XML" }, { "code": "<LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#1aff1a\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"100dp\" android:background=\"#009933\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/white\" android:textSize=\"30sp\" /> </LinearLayout>", "e": 28750, "s": 28274, "text": null }, { "code": null, "e": 28758, "s": 28750, "text": "Output:" }, { "code": null, "e": 28845, "s": 28758, "text": "2. android:layout_marginRight: It specifies extra space on the right side of the view." }, { "code": null, "e": 28854, "s": 28845, "text": "Example:" }, { "code": null, "e": 28858, "s": 28854, "text": "XML" }, { "code": "<LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#1aff1a\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"190dp\" android:background=\"#009933\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/white\" android:textSize=\"30sp\" /> </LinearLayout>", "e": 29335, "s": 28858, "text": null }, { "code": null, "e": 29343, "s": 29335, "text": "Output:" }, { "code": null, "e": 29430, "s": 29343, "text": "3. android:layout_marginTop: It specifies the extra space on the top side of the view." }, { "code": null, "e": 29439, "s": 29430, "text": "Example:" }, { "code": null, "e": 29443, "s": 29439, "text": "XML" }, { "code": "<LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#1aff1a\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"150dp\" android:background=\"#009933\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/white\" android:textSize=\"30sp\" /> </LinearLayout>", "e": 29918, "s": 29443, "text": null }, { "code": null, "e": 29926, "s": 29918, "text": "Output:" }, { "code": null, "e": 30019, "s": 29926, "text": "4. android:layout_marginBottom: It specifies the extra space on the bottom side of the view." }, { "code": null, "e": 30028, "s": 30019, "text": "Example:" }, { "code": null, "e": 30032, "s": 30028, "text": "XML" }, { "code": "<LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#1aff1a\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"150dp\" android:background=\"#009933\" android:text=\"GeeksforGeeks\" android:textColor=\"@color/white\" android:textSize=\"30sp\" /> </LinearLayout>", "e": 30510, "s": 30032, "text": null }, { "code": null, "e": 30518, "s": 30510, "text": "Output:" }, { "code": null, "e": 30531, "s": 30518, "text": "Android-Misc" }, { "code": null, "e": 30555, "s": 30531, "text": "Technical Scripter 2020" }, { "code": null, "e": 30563, "s": 30555, "text": "Android" }, { "code": null, "e": 30582, "s": 30563, "text": "Technical Scripter" }, { "code": null, "e": 30590, "s": 30582, "text": "Android" }, { "code": null, "e": 30688, "s": 30590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30726, "s": 30688, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30765, "s": 30726, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30815, "s": 30765, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30857, "s": 30815, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30908, "s": 30857, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30948, "s": 30908, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 30974, "s": 30948, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 31012, "s": 30974, "text": "Android Listview in Java with Example" }, { "code": null, "e": 31042, "s": 31012, "text": "Fragment Lifecycle in Android" } ]
jQuery | extend() method - GeeksforGeeks
10 May, 2020 This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object. Syntax: jQuery.extend( [deep ], target, object1 [, objectN ] ) Parameters: The extend() method accepts four parameter that is mentioned above and described below: deep: This parameter is the merge becomes recursive . target: This parameter is the object to extend. It will receive the new properties. object1: This parameter is the object containing additional properties to merge in. object1: This parameter is an additional objects containing properties to merge in. Return Value: It returns the object after merging. Below examples illustrate the use of extend() method in jQuery: Example 1: In this example, the extend() method merge two objects in one. <!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | extend() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | extend() method</h3> <p>Merge two objects in One object.</p> <p id = "geeks"> </p> <script> var value1 = { geeks1: 0, geeks2: { topic1: 52, topic2: 100 }, geeks3: 97 }; var value2 = { geeks2: { topic1: 200 }, geeks4: 100 }; // Merge value2 into value1 $.extend( value1, value2 ); // Assuming JSON.stringify - not available in IE<8 $( "#geeks" ).append( JSON.stringify( value1 ) ); </script></body></html> Output: Example 2: In this example, the extend() method merge two objects, without modifying any object. <!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | extend() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | extend() method</h3> <p>Merge two objects, without modifying any object.</p> <p id = "geeks"> </p> <script> var Object_1 = { bool_Val: false, num: 5, name: "shubham" }; var Object_2 = { bool_Val: true, name: "SHUBHAM" }; // Merge Object_1 and Object_2, without modifying Object_1 var Object_3 = $.extend( {}, Object_1, Object_2 ); // Assuming JSON.stringify - not available in IE<8 $( "#geeks" ).append( "<b>Object_1 : </b>" + JSON.stringify( Object_1 ) + "<br>" ); $( "#geeks" ).append( "<b>Object_2 : </b>" + JSON.stringify( Object_2 ) + "<br>" ); $( "#geeks" ).append( "<b>Object_3 : </b>" + JSON.stringify( Object_3 ) + "<br>" ); </script></body></html> Output: jQuery-Methods JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to Show and Hide div elements using radio buttons? Scroll to the top of the page using JavaScript/jQuery jQuery | children() with Examples 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": 26186, "s": 26158, "text": "\n10 May, 2020" }, { "code": null, "e": 26302, "s": 26186, "text": "This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object." }, { "code": null, "e": 26310, "s": 26302, "text": "Syntax:" }, { "code": null, "e": 26366, "s": 26310, "text": "jQuery.extend( [deep ], target, object1 [, objectN ] )\n" }, { "code": null, "e": 26466, "s": 26366, "text": "Parameters: The extend() method accepts four parameter that is mentioned above and described below:" }, { "code": null, "e": 26520, "s": 26466, "text": "deep: This parameter is the merge becomes recursive ." }, { "code": null, "e": 26604, "s": 26520, "text": "target: This parameter is the object to extend. It will receive the new properties." }, { "code": null, "e": 26688, "s": 26604, "text": "object1: This parameter is the object containing additional properties to merge in." }, { "code": null, "e": 26772, "s": 26688, "text": "object1: This parameter is an additional objects containing properties to merge in." }, { "code": null, "e": 26823, "s": 26772, "text": "Return Value: It returns the object after merging." }, { "code": null, "e": 26887, "s": 26823, "text": "Below examples illustrate the use of extend() method in jQuery:" }, { "code": null, "e": 26961, "s": 26887, "text": "Example 1: In this example, the extend() method merge two objects in one." }, { "code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | extend() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | extend() method</h3> <p>Merge two objects in One object.</p> <p id = \"geeks\"> </p> <script> var value1 = { geeks1: 0, geeks2: { topic1: 52, topic2: 100 }, geeks3: 97 }; var value2 = { geeks2: { topic1: 200 }, geeks4: 100 }; // Merge value2 into value1 $.extend( value1, value2 ); // Assuming JSON.stringify - not available in IE<8 $( \"#geeks\" ).append( JSON.stringify( value1 ) ); </script></body></html> ", "e": 27847, "s": 26961, "text": null }, { "code": null, "e": 27855, "s": 27847, "text": "Output:" }, { "code": null, "e": 27952, "s": 27855, "text": "Example 2: In this example, the extend() method merge two objects, without modifying any object." }, { "code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | extend() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | extend() method</h3> <p>Merge two objects, without modifying any object.</p> <p id = \"geeks\"> </p> <script> var Object_1 = { bool_Val: false, num: 5, name: \"shubham\" }; var Object_2 = { bool_Val: true, name: \"SHUBHAM\" }; // Merge Object_1 and Object_2, without modifying Object_1 var Object_3 = $.extend( {}, Object_1, Object_2 ); // Assuming JSON.stringify - not available in IE<8 $( \"#geeks\" ).append( \"<b>Object_1 : </b>\" + JSON.stringify( Object_1 ) + \"<br>\" ); $( \"#geeks\" ).append( \"<b>Object_2 : </b>\" + JSON.stringify( Object_2 ) + \"<br>\" ); $( \"#geeks\" ).append( \"<b>Object_3 : </b>\" + JSON.stringify( Object_3 ) + \"<br>\" ); </script></body></html>", "e": 28986, "s": 27952, "text": null }, { "code": null, "e": 28994, "s": 28986, "text": "Output:" }, { "code": null, "e": 29009, "s": 28994, "text": "jQuery-Methods" }, { "code": null, "e": 29016, "s": 29009, "text": "JQuery" }, { "code": null, "e": 29033, "s": 29016, "text": "Web Technologies" }, { "code": null, "e": 29060, "s": 29033, "text": "Web technologies Questions" }, { "code": null, "e": 29158, "s": 29060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29187, "s": 29158, "text": "Form validation using jQuery" }, { "code": null, "e": 29243, "s": 29187, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 29298, "s": 29243, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 29352, "s": 29298, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 29386, "s": 29352, "text": "jQuery | children() with Examples" }, { "code": null, "e": 29426, "s": 29386, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29459, "s": 29426, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29504, "s": 29459, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29547, "s": 29504, "text": "How to fetch data from an API in ReactJS ?" } ]
SQL Query to convert NUMERIC to NVARCHAR - GeeksforGeeks
15 May, 2021 Here we will see, how to convert NUMERIC data to NVARCHAR data in a MS SQL Server’s database table using the CAST(), CONVERT() and FORMAT() functions. We will be creating a person table in a database called “geeks”. CREATE DATABASE geeks; USE geeks; We have the following Employee table in our geeks database : CREATE TABLE person( id INT IDENTITY(1,1) PRIMARY KEY, name VARCHAR(30) NOT NULL, weight NUMERIC(10,5) NOT NULL); --Here NUMERIC(10,5) says there should be total 10 digits given that 5 digits would be --to the right of the decimal point. You can use the below statement to query the description of the created table: EXEC SP_COLUMNS person; Use the below statement to add data to the person table: INSERT INTO person VALUES ('Yogesh Vaishnav', 62.5), ('Vishal Vishwakarma', 70), ('Ashish Yadav', 69), ('Ajit Yadav', 71.9); To verify the contents of the table use the below statement: SELECT * FROM person; Now let’s convert NUMBERIC values to NVARCHAR using three different methods. Using the CONVERT() function: Syntax: SELECT CONVERT(<DATA_TYPE>, <VALUE>); --DATA_TYPE is the type we want to convert to. --VALUE is the value we want to convert into DATA_TYPE. Example: SELECT 'Weight of Yogesh Vaishnav is ' + CONVERT(NVARCHAR(20), weight) AS person_weight FROM person WHERE name = 'Yogesh Vaishnav'; As you can see that there are total 5 digits to the right side of the decimal point as discussed above. Using the CAST() function: Syntax: SELECT CAST(<VALUE> AS <DATA_TYPE>); --DATA_TYPE is the type we want to convert to. --VALUE is the value we want to convert into DATA_TYPE Example: SELECT 'Weight of Ajit Yadav is ' + CAST(weight as NVARCHAR(20)) AS person_weight FROM person WHERE name = 'Ajit Yadav'; Using the FORMAT() function: Although FORMAT() function is useful for formatting datetime and not converting one type into another, but still can be used to convert(or here format) float value into an STR value. Syntax: SELECT FORMAT(<VALUE> , 'actual_format'; --actual_format is the format we want to achieve in a string form. --VALUE is the value we want to format according to the actual_format. Example: SELECT 'Weight of Ashish Yadav is ' + FORMAT(weight, '') --'' denotes no formating --i.e simply convert it to a string of characters. AS person_weight FROM person WHERE name = 'Ashish Yadav'; Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL | Subquery SQL Query to Convert VARCHAR to INT SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python How to Select Data Between Two Dates and Times in SQL Server? How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Compare Two Dates
[ { "code": null, "e": 25623, "s": 25595, "text": "\n15 May, 2021" }, { "code": null, "e": 25774, "s": 25623, "text": "Here we will see, how to convert NUMERIC data to NVARCHAR data in a MS SQL Server’s database table using the CAST(), CONVERT() and FORMAT() functions." }, { "code": null, "e": 25839, "s": 25774, "text": "We will be creating a person table in a database called “geeks”." }, { "code": null, "e": 25862, "s": 25839, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 25873, "s": 25862, "text": "USE geeks;" }, { "code": null, "e": 25934, "s": 25873, "text": "We have the following Employee table in our geeks database :" }, { "code": null, "e": 26173, "s": 25934, "text": "CREATE TABLE person(\nid INT IDENTITY(1,1) PRIMARY KEY,\nname VARCHAR(30) NOT NULL,\nweight NUMERIC(10,5) NOT NULL);\n--Here NUMERIC(10,5) says there should be total 10 digits given that 5 digits would be \n--to the right of the decimal point." }, { "code": null, "e": 26252, "s": 26173, "text": "You can use the below statement to query the description of the created table:" }, { "code": null, "e": 26276, "s": 26252, "text": "EXEC SP_COLUMNS person;" }, { "code": null, "e": 26333, "s": 26276, "text": "Use the below statement to add data to the person table:" }, { "code": null, "e": 26458, "s": 26333, "text": "INSERT INTO person\nVALUES\n('Yogesh Vaishnav', 62.5),\n('Vishal Vishwakarma', 70),\n('Ashish Yadav', 69),\n('Ajit Yadav', 71.9);" }, { "code": null, "e": 26519, "s": 26458, "text": "To verify the contents of the table use the below statement:" }, { "code": null, "e": 26541, "s": 26519, "text": "SELECT * FROM person;" }, { "code": null, "e": 26618, "s": 26541, "text": "Now let’s convert NUMBERIC values to NVARCHAR using three different methods." }, { "code": null, "e": 26648, "s": 26618, "text": "Using the CONVERT() function:" }, { "code": null, "e": 26797, "s": 26648, "text": "Syntax: SELECT CONVERT(<DATA_TYPE>, <VALUE>);\n--DATA_TYPE is the type we want to convert to.\n--VALUE is the value we want to convert into DATA_TYPE." }, { "code": null, "e": 26806, "s": 26797, "text": "Example:" }, { "code": null, "e": 26938, "s": 26806, "text": "SELECT 'Weight of Yogesh Vaishnav is ' + CONVERT(NVARCHAR(20), weight)\nAS person_weight\nFROM person\nWHERE name = 'Yogesh Vaishnav';" }, { "code": null, "e": 27042, "s": 26938, "text": "As you can see that there are total 5 digits to the right side of the decimal point as discussed above." }, { "code": null, "e": 27069, "s": 27042, "text": "Using the CAST() function:" }, { "code": null, "e": 27216, "s": 27069, "text": "Syntax: SELECT CAST(<VALUE> AS <DATA_TYPE>);\n--DATA_TYPE is the type we want to convert to.\n--VALUE is the value we want to convert into DATA_TYPE" }, { "code": null, "e": 27225, "s": 27216, "text": "Example:" }, { "code": null, "e": 27346, "s": 27225, "text": "SELECT 'Weight of Ajit Yadav is ' + CAST(weight as NVARCHAR(20))\nAS person_weight\nFROM person\nWHERE name = 'Ajit Yadav';" }, { "code": null, "e": 27375, "s": 27346, "text": "Using the FORMAT() function:" }, { "code": null, "e": 27558, "s": 27375, "text": "Although FORMAT() function is useful for formatting datetime and not converting one type into another, but still can be used to convert(or here format) float value into an STR value." }, { "code": null, "e": 27745, "s": 27558, "text": "Syntax: SELECT FORMAT(<VALUE> , 'actual_format';\n--actual_format is the format we want to achieve in a string form.\n--VALUE is the value we want to format according to the actual_format." }, { "code": null, "e": 27754, "s": 27745, "text": "Example:" }, { "code": null, "e": 27946, "s": 27754, "text": "SELECT 'Weight of Ashish Yadav is ' + FORMAT(weight, '') --'' denotes no formating\n--i.e simply convert it to a string of characters.\nAS person_weight\nFROM person\nWHERE name = 'Ashish Yadav';" }, { "code": null, "e": 27953, "s": 27946, "text": "Picked" }, { "code": null, "e": 27963, "s": 27953, "text": "SQL-Query" }, { "code": null, "e": 27967, "s": 27963, "text": "SQL" }, { "code": null, "e": 27971, "s": 27967, "text": "SQL" }, { "code": null, "e": 28069, "s": 27971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28135, "s": 28069, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28192, "s": 28135, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28224, "s": 28192, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28239, "s": 28224, "text": "SQL | Subquery" }, { "code": null, "e": 28275, "s": 28239, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28353, "s": 28275, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28370, "s": 28353, "text": "SQL using Python" }, { "code": null, "e": 28432, "s": 28370, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 28498, "s": 28432, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" } ]
Decimal.Negate() Method in C# - GeeksforGeeks
30 Jan, 2019 This method is used to get the result of multiplying the specified Decimal value by negative one. Syntax: public static decimal Negate (decimal a); Parameter:a: This parameter specifies the decimal which will be converted. Return Value: A decimal number with the value of a, but the opposite sign. But zero, if a is zero. Below programs illustrate the use of Decimal.Negate(Decimal) Method: Example 1: When a is positive // C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variable Decimal a = 127.97m; // using Negate() method; Decimal value = Decimal.Negate(a); // Display the negative value Console.WriteLine("The negative value "+ "is : {0}", value); }} The negative value is : -127.97 Example 2: When a is negative // C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variable Decimal a = -12.39m; // using Negate() method; Decimal value = Decimal.Negate(a); // Display the value after // using negate method Console.WriteLine("The value is : {0}", value); }} The value is : 12.39 Example 3: If a is zero. // C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variable Decimal a = 0.00m; // using Negate() method; Decimal value = Decimal.Negate(a); // Display the Negate value Console.WriteLine("The Negate value "+ "is : {0}", value); }} The Negate value is : 0.00 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.decimal.negate?view=netframework-4.7.2 CSharp-Decimal-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Delegates Introduction to .NET Framework C# Dictionary with examples Difference between Ref and Out keywords in C# Partial Classes in C# Extension Method in C# Top 50 C# Interview Questions & Answers Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework Different ways to sort an array in descending order in C# Lambda Expressions in C#
[ { "code": null, "e": 23537, "s": 23509, "text": "\n30 Jan, 2019" }, { "code": null, "e": 23635, "s": 23537, "text": "This method is used to get the result of multiplying the specified Decimal value by negative one." }, { "code": null, "e": 23685, "s": 23635, "text": "Syntax: public static decimal Negate (decimal a);" }, { "code": null, "e": 23760, "s": 23685, "text": "Parameter:a: This parameter specifies the decimal which will be converted." }, { "code": null, "e": 23859, "s": 23760, "text": "Return Value: A decimal number with the value of a, but the opposite sign. But zero, if a is zero." }, { "code": null, "e": 23928, "s": 23859, "text": "Below programs illustrate the use of Decimal.Negate(Decimal) Method:" }, { "code": null, "e": 23958, "s": 23928, "text": "Example 1: When a is positive" }, { "code": "// C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variable Decimal a = 127.97m; // using Negate() method; Decimal value = Decimal.Negate(a); // Display the negative value Console.WriteLine(\"The negative value \"+ \"is : {0}\", value); }}", "e": 24420, "s": 23958, "text": null }, { "code": null, "e": 24453, "s": 24420, "text": "The negative value is : -127.97\n" }, { "code": null, "e": 24483, "s": 24453, "text": "Example 2: When a is negative" }, { "code": "// C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variable Decimal a = -12.39m; // using Negate() method; Decimal value = Decimal.Negate(a); // Display the value after // using negate method Console.WriteLine(\"The value is : {0}\", value); }}", "e": 24970, "s": 24483, "text": null }, { "code": null, "e": 24992, "s": 24970, "text": "The value is : 12.39\n" }, { "code": null, "e": 25017, "s": 24992, "text": "Example 3: If a is zero." }, { "code": "// C# program to demonstrate the// Decimal.Negate(Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variable Decimal a = 0.00m; // using Negate() method; Decimal value = Decimal.Negate(a); // Display the Negate value Console.WriteLine(\"The Negate value \"+ \"is : {0}\", value); }}", "e": 25471, "s": 25017, "text": null }, { "code": null, "e": 25499, "s": 25471, "text": "The Negate value is : 0.00\n" }, { "code": null, "e": 25510, "s": 25499, "text": "Reference:" }, { "code": null, "e": 25600, "s": 25510, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.decimal.negate?view=netframework-4.7.2" }, { "code": null, "e": 25622, "s": 25600, "text": "CSharp-Decimal-Struct" }, { "code": null, "e": 25636, "s": 25622, "text": "CSharp-method" }, { "code": null, "e": 25639, "s": 25636, "text": "C#" }, { "code": null, "e": 25737, "s": 25639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25746, "s": 25737, "text": "Comments" }, { "code": null, "e": 25759, "s": 25746, "text": "Old Comments" }, { "code": null, "e": 25774, "s": 25759, "text": "C# | Delegates" }, { "code": null, "e": 25805, "s": 25774, "text": "Introduction to .NET Framework" }, { "code": null, "e": 25833, "s": 25805, "text": "C# Dictionary with examples" }, { "code": null, "e": 25879, "s": 25833, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 25901, "s": 25879, "text": "Partial Classes in C#" }, { "code": null, "e": 25924, "s": 25901, "text": "Extension Method in C#" }, { "code": null, "e": 25964, "s": 25924, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26051, "s": 25964, "text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework" }, { "code": null, "e": 26109, "s": 26051, "text": "Different ways to sort an array in descending order in C#" } ]
7 Awesome Rust-powered Command-line Utilities | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction🦀 Starship🦀 ripgrep🦀 bat🦀 tokei🦀 exa🦀 fd🦀 procs🦀 How I found themConclusion The Rust programming language has been Stack Overflow’s most loved language for four years in a row. Rust is largely viewed as an alternative to other systems programming languages, like C or C++. That’s why many talented developers including Benjamin Sago and Andrew Gallant created excellent Rust-powered command-line utilities. In this article, you will find the top seven command-line utilities you can start using today. Starship is the minimal, blazing-fast, and infinitely customizable prompt for any shell. To install with homebrew run: brew install starship For more details on how to install the Starship, please read about the Starship in this article. And add the init script to your shell’s config file: # ~/.zshrceval "$(starship init zsh)" You can find other installations from here. A super-fast search tool that recursively searches directories for a regex pattern. ripgrep supports Windows, macOS, and Linux and it is a modern replacement for grep. You can install ripgrep: # macOS Homebrew/Linuxbrew$ brew install ripgrep# MacPorts$ sudo port install ripgrep# Windows Chocolatey$ choco install ripgrep# Windows Scoop$ scoop install ripgrep You can find other installations here. MS's VS code uses a ripgre-powered search. It also ignores hidden and binary files by default. bat is a cat clone with syntax highlighting and Git integration. bat is written in Rust and woks on Windows/macOS/Linux. # for macOSbrew install bat bat supports syntax highlighting for a large number of programming and markup languages: bat has git integration and shows modifications with respect to the index (see the left sidebar in the above image). tokei is a program that displays statistics about your code. It is a super-fast replacement for cloc. tokei shows the number of files, total lines within those files and code, comments, and blanks grouped by language. tokei is available on Mac, Linux, and Windows. See installation instructions. exa is a modern replacement for the command-line program ls that ships with Unix and Linux operating systems. To install with homebrew run: brew install exa You can find other installations in this link. fd is a simple, fast, and user-friendly alternative to find. fd works on Windows/macOS/Linux. To install with homebrew run: brew install fd For other installations please see this link. procs is a replacement for ps written in Rust. It creates the tree view and its output is a human-readable format. You can keyword-search over multi-column. procs works on Windows(experimental)/macOS/Linux. Please find other installations for your system here. You can cycle through the headings by pressing n and order in ascending order by pressing a and order in descending order by pressing d. # for macOSbrew install procs The website doesn’t allow you to order by # of downloads so you can run this code to stay up to date. I used BeautifulSoup to scrape the website and used Pandas to create a dataframe on Jupyter Notebook. Even though lib.rs has its own ranking algorithm, I ordered them by download numbers. import requestsfrom bs4 import BeautifulSoupimport pandas as pdURL = 'https://lib.rs/command-line-utilities'page = requests.get(URL)soup = BeautifulSoup(page.content, 'html.parser')# find all package namesdivs = soup.select('.h > h4')names=[]for div in divs: names.append(div.text.strip())# find all package downloadsmetas = soup.select('.meta')downloads=[]for meta in metas: if(mytitle:=meta.find(class_='downloads')): parts = str(mytitle).split()[2].split('="')[1] downloads.append(int(parts)) else: # some libraries do not have downloads class downloads.append(0)# create a dataframe using pandasdata_tuples = list(zip(names,downloads))df=pd.DataFrame(data_tuples, columns=['Name','Downloads'])# sort by number of downloadsdf = df.sort_values(by='Downloads', ascending=False)df.head(20) Result (as of May 5, 2020) Some packages are for the Rust environment, so I selected packages that everyone can use for a terminal. There are more Rust-powered command-line utilities that are not on this list. I hope you find these utilities useful. What are your favorites? Or you are so inspired that you want to start building your own command-line application in Rust. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 276, "s": 171, "text": "Table of ContentsIntroduction🦀 Starship🦀 ripgrep🦀 bat🦀 tokei🦀 exa🦀 fd🦀 procs🦀 How I found themConclusion" }, { "code": null, "e": 377, "s": 276, "text": "The Rust programming language has been Stack Overflow’s most loved language for four years in a row." }, { "code": null, "e": 473, "s": 377, "text": "Rust is largely viewed as an alternative to other systems programming languages, like C or C++." }, { "code": null, "e": 607, "s": 473, "text": "That’s why many talented developers including Benjamin Sago and Andrew Gallant created excellent Rust-powered command-line utilities." }, { "code": null, "e": 702, "s": 607, "text": "In this article, you will find the top seven command-line utilities you can start using today." }, { "code": null, "e": 791, "s": 702, "text": "Starship is the minimal, blazing-fast, and infinitely customizable prompt for any shell." }, { "code": null, "e": 821, "s": 791, "text": "To install with homebrew run:" }, { "code": null, "e": 843, "s": 821, "text": "brew install starship" }, { "code": null, "e": 940, "s": 843, "text": "For more details on how to install the Starship, please read about the Starship in this article." }, { "code": null, "e": 993, "s": 940, "text": "And add the init script to your shell’s config file:" }, { "code": null, "e": 1031, "s": 993, "text": "# ~/.zshrceval \"$(starship init zsh)\"" }, { "code": null, "e": 1075, "s": 1031, "text": "You can find other installations from here." }, { "code": null, "e": 1243, "s": 1075, "text": "A super-fast search tool that recursively searches directories for a regex pattern. ripgrep supports Windows, macOS, and Linux and it is a modern replacement for grep." }, { "code": null, "e": 1268, "s": 1243, "text": "You can install ripgrep:" }, { "code": null, "e": 1435, "s": 1268, "text": "# macOS Homebrew/Linuxbrew$ brew install ripgrep# MacPorts$ sudo port install ripgrep# Windows Chocolatey$ choco install ripgrep# Windows Scoop$ scoop install ripgrep" }, { "code": null, "e": 1474, "s": 1435, "text": "You can find other installations here." }, { "code": null, "e": 1569, "s": 1474, "text": "MS's VS code uses a ripgre-powered search. It also ignores hidden and binary files by default." }, { "code": null, "e": 1690, "s": 1569, "text": "bat is a cat clone with syntax highlighting and Git integration. bat is written in Rust and woks on Windows/macOS/Linux." }, { "code": null, "e": 1718, "s": 1690, "text": "# for macOSbrew install bat" }, { "code": null, "e": 1807, "s": 1718, "text": "bat supports syntax highlighting for a large number of programming and markup languages:" }, { "code": null, "e": 1924, "s": 1807, "text": "bat has git integration and shows modifications with respect to the index (see the left sidebar in the above image)." }, { "code": null, "e": 2026, "s": 1924, "text": "tokei is a program that displays statistics about your code. It is a super-fast replacement for cloc." }, { "code": null, "e": 2142, "s": 2026, "text": "tokei shows the number of files, total lines within those files and code, comments, and blanks grouped by language." }, { "code": null, "e": 2220, "s": 2142, "text": "tokei is available on Mac, Linux, and Windows. See installation instructions." }, { "code": null, "e": 2330, "s": 2220, "text": "exa is a modern replacement for the command-line program ls that ships with Unix and Linux operating systems." }, { "code": null, "e": 2360, "s": 2330, "text": "To install with homebrew run:" }, { "code": null, "e": 2377, "s": 2360, "text": "brew install exa" }, { "code": null, "e": 2424, "s": 2377, "text": "You can find other installations in this link." }, { "code": null, "e": 2518, "s": 2424, "text": "fd is a simple, fast, and user-friendly alternative to find. fd works on Windows/macOS/Linux." }, { "code": null, "e": 2548, "s": 2518, "text": "To install with homebrew run:" }, { "code": null, "e": 2565, "s": 2548, "text": "brew install fd " }, { "code": null, "e": 2611, "s": 2565, "text": "For other installations please see this link." }, { "code": null, "e": 2726, "s": 2611, "text": "procs is a replacement for ps written in Rust. It creates the tree view and its output is a human-readable format." }, { "code": null, "e": 2818, "s": 2726, "text": "You can keyword-search over multi-column. procs works on Windows(experimental)/macOS/Linux." }, { "code": null, "e": 2872, "s": 2818, "text": "Please find other installations for your system here." }, { "code": null, "e": 3009, "s": 2872, "text": "You can cycle through the headings by pressing n and order in ascending order by pressing a and order in descending order by pressing d." }, { "code": null, "e": 3039, "s": 3009, "text": "# for macOSbrew install procs" }, { "code": null, "e": 3141, "s": 3039, "text": "The website doesn’t allow you to order by # of downloads so you can run this code to stay up to date." }, { "code": null, "e": 3243, "s": 3141, "text": "I used BeautifulSoup to scrape the website and used Pandas to create a dataframe on Jupyter Notebook." }, { "code": null, "e": 3329, "s": 3243, "text": "Even though lib.rs has its own ranking algorithm, I ordered them by download numbers." }, { "code": null, "e": 4156, "s": 3329, "text": "import requestsfrom bs4 import BeautifulSoupimport pandas as pdURL = 'https://lib.rs/command-line-utilities'page = requests.get(URL)soup = BeautifulSoup(page.content, 'html.parser')# find all package namesdivs = soup.select('.h > h4')names=[]for div in divs: names.append(div.text.strip())# find all package downloadsmetas = soup.select('.meta')downloads=[]for meta in metas: if(mytitle:=meta.find(class_='downloads')): parts = str(mytitle).split()[2].split('=\"')[1] downloads.append(int(parts)) else: # some libraries do not have downloads class downloads.append(0)# create a dataframe using pandasdata_tuples = list(zip(names,downloads))df=pd.DataFrame(data_tuples, columns=['Name','Downloads'])# sort by number of downloadsdf = df.sort_values(by='Downloads', ascending=False)df.head(20)" }, { "code": null, "e": 4183, "s": 4156, "text": "Result (as of May 5, 2020)" }, { "code": null, "e": 4288, "s": 4183, "text": "Some packages are for the Rust environment, so I selected packages that everyone can use for a terminal." }, { "code": null, "e": 4406, "s": 4288, "text": "There are more Rust-powered command-line utilities that are not on this list. I hope you find these utilities useful." }, { "code": null, "e": 4529, "s": 4406, "text": "What are your favorites? Or you are so inspired that you want to start building your own command-line application in Rust." } ]
Binary Tree Inorder Traversal in Python
Suppose we have a binary tree. We have to traverse this tree using the inorder traversal scheme without using recursion. So if the tree is like Then the traversal will be [2,5,7,10,15,20] To solve this, we will follow these steps − Create two array res and stack, set curr := root Run one infinite loopwhile current is not nullpush curr into a stack, and set curr := left of currwhen the length of stack = 0, then return resnode := popped element from the stackinsert a value of node into rescurr := right of curr while current is not nullpush curr into a stack, and set curr := left of curr push curr into a stack, and set curr := left of curr when the length of stack = 0, then return res node := popped element from the stack insert a value of node into res curr := right of curr Let us see the following implementation to get a better understanding − Live Demo class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): temp.left = TreeNode(data) break else: que.append(temp.left) if (not temp.right): temp.right = TreeNode(data) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def inorderTraversal(self, root): res, stack = [], [] current = root while True: while current: stack.append(current) current = current.left if len(stack) == 0: return res node = stack[-1] stack.pop(len(stack)-1) if node.data != None: res.append(node.data) current = node.right return res ob1 = Solution() root = make_tree([10,5,15,2,7,None,20]) print(ob1.inorderTraversal(root)) [10,5,15,2,7,null,20] [2,5,7,10,15,20]
[ { "code": null, "e": 1206, "s": 1062, "text": "Suppose we have a binary tree. We have to traverse this tree using the inorder traversal scheme without using recursion. So if the tree is like" }, { "code": null, "e": 1250, "s": 1206, "text": "Then the traversal will be [2,5,7,10,15,20]" }, { "code": null, "e": 1294, "s": 1250, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1343, "s": 1294, "text": "Create two array res and stack, set curr := root" }, { "code": null, "e": 1576, "s": 1343, "text": "Run one infinite loopwhile current is not nullpush curr into a stack, and set curr := left of currwhen the length of stack = 0, then return resnode := popped element from the stackinsert a value of node into rescurr := right of curr" }, { "code": null, "e": 1654, "s": 1576, "text": "while current is not nullpush curr into a stack, and set curr := left of curr" }, { "code": null, "e": 1707, "s": 1654, "text": "push curr into a stack, and set curr := left of curr" }, { "code": null, "e": 1753, "s": 1707, "text": "when the length of stack = 0, then return res" }, { "code": null, "e": 1791, "s": 1753, "text": "node := popped element from the stack" }, { "code": null, "e": 1823, "s": 1791, "text": "insert a value of node into res" }, { "code": null, "e": 1845, "s": 1823, "text": "curr := right of curr" }, { "code": null, "e": 1917, "s": 1845, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1928, "s": 1917, "text": " Live Demo" }, { "code": null, "e": 3092, "s": 1928, "text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef insert(temp,data):\n que = []\n que.append(temp)\n while (len(que)):\n temp = que[0]\n que.pop(0)\n if (not temp.left):\n temp.left = TreeNode(data)\n break\n else:\n que.append(temp.left)\n if (not temp.right):\n temp.right = TreeNode(data)\n break\n else:\n que.append(temp.right)\ndef make_tree(elements):\n Tree = TreeNode(elements[0])\n for element in elements[1:]:\n insert(Tree, element)\n return Tree\nclass Solution(object):\n def inorderTraversal(self, root):\n res, stack = [], []\n current = root\n while True:\n while current:\n stack.append(current)\n current = current.left\n if len(stack) == 0:\n return res\n node = stack[-1]\n stack.pop(len(stack)-1)\n if node.data != None:\n res.append(node.data)\n current = node.right\n return res\nob1 = Solution()\nroot = make_tree([10,5,15,2,7,None,20])\nprint(ob1.inorderTraversal(root))" }, { "code": null, "e": 3114, "s": 3092, "text": "[10,5,15,2,7,null,20]" }, { "code": null, "e": 3131, "s": 3114, "text": "[2,5,7,10,15,20]" } ]
How to run a JAR file through command prompt in java?
For packaging of class files Java provides a file format known as JAR (Java Archive). Typically, a JAR file contains .class files, images, text files, libraries that are required to execute the application or, library. This file format is used to distribute application software and libraries in Java. All the predefined libraries are available in this format. If you have any library in this format to use it In your application either you need to place it in the current (or, lib) folder of the project or, you need to set the class path for that particular JAR file. Java provides jar command to work with jar files if you execute it in the command prompt you will get the execution syntax and options of this command as shown below − C:\>jar Usage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ... Options: -c create new archive -t list table of contents for archive -x extract named (or all) files from archive -u update existing archive -v generate verbose output on standard output -f specify archive file name -m include manifest information from specified manifest file -n perform Pack200 normalization after creating a new archive -e specify application entry point for stand-alone application bundled into an executable jar file -0 store only; use no ZIP compression -P preserve leading '/' (absolute path) and ".." (parent directory) components from file names -M do not create a manifest file for the entries -i generate index information for the specified jar files -C change to the specified directory and include the following file You can create a JAR file using by executing this command with the options c, v, f Following is the syntax to create a JAR file using command prompt − jar cvf jar_file_name output_path Create a java file with name Sample.java in the path D:/example, copy and paste the following program in it − public class Sample { public static void main(String args[]){ System.out.println("Hi welcome to Tutorialspoint"); } } Compile the above program using the javac command as − javac Example.java If your program gets executed without errors .class file will be generated in the current folder. Now, create a jar file for the generated class as − C:\Sample>jar cvf sample.jar *.class added manifest adding: Sample.class(in = 434) (out= 302) (deflated 30%) Once you execute a JAR file is generated with the specified name. You can also create JAR files using IDE’s. To create a JAR file using eclipse follow the procedure given below − Open eclipse, create a project in it as − Open eclipse, create a project in it as − Right Click on the project folder and select the Export option as − Right Click on the project folder and select the Export option as − Under the Java category select JAR file. Under the Java category select JAR file. Click on Next. Click on Next. Enter the JAR file name and folder. Enter the JAR file name and folder. Click on Finish. Click on Finish.
[ { "code": null, "e": 1281, "s": 1062, "text": "For packaging of class files Java provides a file format known as JAR (Java Archive). Typically, a JAR file contains .class files, images, text files, libraries that are required to execute the application or, library." }, { "code": null, "e": 1423, "s": 1281, "text": "This file format is used to distribute application software and libraries in Java. All the predefined libraries are available in this format." }, { "code": null, "e": 1632, "s": 1423, "text": "If you have any library in this format to use it In your application either you need to place it in the current (or, lib) folder of the project or, you need to set the class path for that particular JAR file." }, { "code": null, "e": 1800, "s": 1632, "text": "Java provides jar command to work with jar files if you execute it in the command prompt you will get the execution syntax and options of this command as shown below −" }, { "code": null, "e": 2685, "s": 1800, "text": "C:\\>jar\nUsage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\nOptions:\n -c create new archive\n -t list table of contents for archive\n -x extract named (or all) files from archive\n -u update existing archive\n -v generate verbose output on standard output\n -f specify archive file name\n -m include manifest information from specified manifest file\n -n perform Pack200 normalization after creating a new archive\n -e specify application entry point for stand-alone application bundled into an executable jar file\n -0 store only; use no ZIP compression\n -P preserve leading '/' (absolute path) and \"..\" (parent directory) components from file names\n -M do not create a manifest file for the entries\n -i generate index information for the specified jar files\n -C change to the specified directory and include the following file" }, { "code": null, "e": 2836, "s": 2685, "text": "You can create a JAR file using by executing this command with the options c, v, f Following is the syntax to create a JAR file using command prompt −" }, { "code": null, "e": 2870, "s": 2836, "text": "jar cvf jar_file_name output_path" }, { "code": null, "e": 2980, "s": 2870, "text": "Create a java file with name Sample.java in the path D:/example, copy and paste the following program in it −" }, { "code": null, "e": 3110, "s": 2980, "text": "public class Sample {\n public static void main(String args[]){\n System.out.println(\"Hi welcome to Tutorialspoint\");\n }\n}" }, { "code": null, "e": 3165, "s": 3110, "text": "Compile the above program using the javac command as −" }, { "code": null, "e": 3184, "s": 3165, "text": "javac Example.java" }, { "code": null, "e": 3334, "s": 3184, "text": "If your program gets executed without errors .class file will be generated in the current folder. Now, create a jar file for the generated class as −" }, { "code": null, "e": 3509, "s": 3334, "text": "C:\\Sample>jar cvf sample.jar *.class\nadded manifest\nadding: Sample.class(in = 434) (out= 302) (deflated 30%)\nOnce you execute a JAR file is generated with the specified name." }, { "code": null, "e": 3622, "s": 3509, "text": "You can also create JAR files using IDE’s. To create a JAR file using eclipse follow the procedure given below −" }, { "code": null, "e": 3664, "s": 3622, "text": "Open eclipse, create a project in it as −" }, { "code": null, "e": 3706, "s": 3664, "text": "Open eclipse, create a project in it as −" }, { "code": null, "e": 3774, "s": 3706, "text": "Right Click on the project folder and select the Export option as −" }, { "code": null, "e": 3842, "s": 3774, "text": "Right Click on the project folder and select the Export option as −" }, { "code": null, "e": 3883, "s": 3842, "text": "Under the Java category select JAR file." }, { "code": null, "e": 3924, "s": 3883, "text": "Under the Java category select JAR file." }, { "code": null, "e": 3939, "s": 3924, "text": "Click on Next." }, { "code": null, "e": 3954, "s": 3939, "text": "Click on Next." }, { "code": null, "e": 3990, "s": 3954, "text": "Enter the JAR file name and folder." }, { "code": null, "e": 4026, "s": 3990, "text": "Enter the JAR file name and folder." }, { "code": null, "e": 4043, "s": 4026, "text": "Click on Finish." }, { "code": null, "e": 4060, "s": 4043, "text": "Click on Finish." } ]
Boy or Girl? A Machine Learning Web App to Detect Gender from Name | by Marie Stephen Leo | Towards Data Science
Choosing a name for your child is one of the most stressful decisions you’ll have to make as a new parent. Especially for a data-driven guy like me, having to decide on a name without any prior data about my child’s character and preferences is a nightmare come true! Since my first name starts with “Marie,” I’ve gone through countless experiences of people addressing me as “Miss” over emails and text only to be disappointed to realize that I’m actually a guy when we finally meet or talk 😜. So, when my wife and I were researching names for our baby girl, an important question we asked ourselves was: Will people be able to identify that the name refers to a girl and not a boy? It turns out we can use Machine Learning to help us check if potential names would be associate more with boys or girls! To check out the app I’ve built to do exactly this, please head over to https://www.boyorgirl.xyz. The rest of this post talks about the technical details, including Obtaining a name to the gender training datasetPreprocessing the names to make them compatible with Machine Learning (ML) modelsDeveloping a Natural Language Processing (NLP) ML model to read in a name and output if it’s a boy’s name or a girl’s nameBuilding a simple web app for people to interact with the modelPublishing the app on the internet Obtaining a name to the gender training dataset Preprocessing the names to make them compatible with Machine Learning (ML) models Developing a Natural Language Processing (NLP) ML model to read in a name and output if it’s a boy’s name or a girl’s name Building a simple web app for people to interact with the model Publishing the app on the internet To train any Machine Learning model, we need a large quantity of labeled data. In this case, we need a large number of names and the associated gender of that name. Luckily, Google Cloud’s Bigquery has a free open dataset called USA_NAMES [Link] that “contains all names from Social Security card applications for births that occurred in the United States.” The dataset contains roughly 35000 names and the associated gender, which works very well for our model. Human names are textual data, while ML models can only work with numeric data. To convert our text into a numeric representation, we’ll do the following steps. Lowercase the name since each character’s case doesn’t convey any information about a person’s gender.Split each character: The basic idea of the ML model we’re building is to read characters in a name to identify patterns that could indicate masculinity or femininity. Thus we split the name into each character.Pad names with empty spaces until a max of 50 characters ensures the ML model sees the same length for all the names.Encode each character to a unique number since ML models can only work with numbers. In this case, we encode ‘ ’ (space) to 0, ‘a’ to 1, ‘b’ to 2, and so on.Encode each gender to a unique number since ML models can only work with numbers. In this case, we encode ‘F’ to 0 and ‘M’ to 1. Lowercase the name since each character’s case doesn’t convey any information about a person’s gender. Split each character: The basic idea of the ML model we’re building is to read characters in a name to identify patterns that could indicate masculinity or femininity. Thus we split the name into each character. Pad names with empty spaces until a max of 50 characters ensures the ML model sees the same length for all the names. Encode each character to a unique number since ML models can only work with numbers. In this case, we encode ‘ ’ (space) to 0, ‘a’ to 1, ‘b’ to 2, and so on. Encode each gender to a unique number since ML models can only work with numbers. In this case, we encode ‘F’ to 0 and ‘M’ to 1. When we read a name, we identify the probable gender of that name by the sequence in which characters appear in that name. For example, “Stephen” is most likely a boy’s name but “Stephanie” is likely a girl’s name. To mimic the way we humans identify the gender of a name, we construct a simple Bidirectional LSTM model using the tensorflow.keras API. Embedding layer: to “embed” each input character’s encoded number into a dense 256 dimension vector. The choice of embedding_dim is a hyperparameter that can be tuned to get the desired accuracy.Bidirectional LSTM layer: read the sequence of character embeddings from the previous step and output a single vector representing that sequence. The values for units and dropouts are hyperparameters as well.Final Dense layer: to output a single value close to 0 for ‘F’ or close to 1 for ‘M’ since this is the encoding we used in the preprocessing step. Embedding layer: to “embed” each input character’s encoded number into a dense 256 dimension vector. The choice of embedding_dim is a hyperparameter that can be tuned to get the desired accuracy. Bidirectional LSTM layer: read the sequence of character embeddings from the previous step and output a single vector representing that sequence. The values for units and dropouts are hyperparameters as well. Final Dense layer: to output a single value close to 0 for ‘F’ or close to 1 for ‘M’ since this is the encoding we used in the preprocessing step. We’ll use the standard tensorflow.keras training pipeline as below Instantiate the model using the function we wrote in the model architecture step.Split the data into 80% training and 20% validation.Call model.fit with EarlyStopping callback to stop training once the model starts to overfit.Save the trained model to reuse while serving the web app.Plot the training and validation accuracies to visually check the model performance. Instantiate the model using the function we wrote in the model architecture step. Split the data into 80% training and 20% validation. Call model.fit with EarlyStopping callback to stop training once the model starts to overfit. Save the trained model to reuse while serving the web app. Plot the training and validation accuracies to visually check the model performance. Now that we have the trained model with good accuracy, we can create a Plotly Dash [Link] web app [https://www.boyorgirl.xyz] to get input names from a user, load the model (only once during app startup), use the model to predict the gender on the input names, and visualize the results back on the web app. The below code snippet only shows the model inference part of the web app. The full Plotly Dash web app code, including the model load, text box input, table output, and interactive bar plot output, is available on my GitHub repository. The final step is to publish our new app on the internet for everyone worldwide to interact with. After a little bit of research, I decided to use Heroku to deploy the app for the following reasons. Free!!!A straightforward deployment processMax 500MB memory is sufficient for my small custom model. Free!!! A straightforward deployment process Max 500MB memory is sufficient for my small custom model. The steps to deploy an app to Heroku are well documented on the Heroku website [Link]. I made custom changes to support my mono-repo format, which I’ve documented in my Github repo [Link]. The main changes to support mono-repos are Add the following buildpack heroku buildpacks:add -a <app> https://github.com/lstoll/heroku-buildpack-monorepo -i 1 Add the following configs heroku config:set -a <app> PROCFILE=relative/path/to/app/Procfileheroku config:set -a <app> APP_BASE=relative/path/to/app Important! One major gotcha that took me some time to figure out is that Heroku starts two workers by default. So if your app’s size is more than 250MB, the two workers combined would exceed the 500MB limit that Heroku sets for free apps. Since I don't expect the traffic to my app to be large enough to need two workers, I easily solved this issue by specifying only one worker by using the -w 1 flag in the Procfile. web: gunicorn -w 1 serve:server Free tier Heroku apps go to sleep after 30 mins of inactivity. Thus I used a free ping service called Kaffeine [Link] to ping my app once every 10mins. This will ensure zero downtime for the app. Subsequently, I upgraded from Free tier to Hobby tier (mainly for Free SSL on my custom domain), ensuring the app never sleeps, so the ping service is no longer relevant for my app. Finally, I purchased a cheap domain from Namecheap [Link] and pointed the domain to my Heroku app following instructions from here [Link]. On a serious note, we need to keep a few limitations and biases in mind while using this approach. The model has ZERO understanding of the concept of gender in the real world! It is only making an informed guess at which gender a specific name probably belongs to based on historical data of names belonging to different genders. For example, my name begins with “Marie,” which the model detects as a female name (with the confidence of ~90%!) though I’m actually a male. Thus this approach perpetuates the inherent bias in our names, and it’s beyond the scope of this work to address these biases.The training data only consisted of binary genders (M and F). Thus, non-binary genders are not represented. The model has ZERO understanding of the concept of gender in the real world! It is only making an informed guess at which gender a specific name probably belongs to based on historical data of names belonging to different genders. For example, my name begins with “Marie,” which the model detects as a female name (with the confidence of ~90%!) though I’m actually a male. Thus this approach perpetuates the inherent bias in our names, and it’s beyond the scope of this work to address these biases. The training data only consisted of binary genders (M and F). Thus, non-binary genders are not represented. In conclusion, please DO NOT use this app to make assumptions about anyone’s gender identity! And that’s it! Our cool ML app to predict gender from names is now available for anyone on the internet to interact with! From my testing, the app seems to perform very well for English names and reasonably well for Indian names because of the names present in the training dataset. Non-English names like Chinese names performed poorly. Would you please take a look and let me know if it got your names correct? Thanks for reading! All the code is available on my Github repo: [Link] You can access “Boy Or Girl?” at: https://www.boyorgirl.xyz
[ { "code": null, "e": 439, "s": 171, "text": "Choosing a name for your child is one of the most stressful decisions you’ll have to make as a new parent. Especially for a data-driven guy like me, having to decide on a name without any prior data about my child’s character and preferences is a nightmare come true!" }, { "code": null, "e": 777, "s": 439, "text": "Since my first name starts with “Marie,” I’ve gone through countless experiences of people addressing me as “Miss” over emails and text only to be disappointed to realize that I’m actually a guy when we finally meet or talk 😜. So, when my wife and I were researching names for our baby girl, an important question we asked ourselves was:" }, { "code": null, "e": 855, "s": 777, "text": "Will people be able to identify that the name refers to a girl and not a boy?" }, { "code": null, "e": 1075, "s": 855, "text": "It turns out we can use Machine Learning to help us check if potential names would be associate more with boys or girls! To check out the app I’ve built to do exactly this, please head over to https://www.boyorgirl.xyz." }, { "code": null, "e": 1142, "s": 1075, "text": "The rest of this post talks about the technical details, including" }, { "code": null, "e": 1490, "s": 1142, "text": "Obtaining a name to the gender training datasetPreprocessing the names to make them compatible with Machine Learning (ML) modelsDeveloping a Natural Language Processing (NLP) ML model to read in a name and output if it’s a boy’s name or a girl’s nameBuilding a simple web app for people to interact with the modelPublishing the app on the internet" }, { "code": null, "e": 1538, "s": 1490, "text": "Obtaining a name to the gender training dataset" }, { "code": null, "e": 1620, "s": 1538, "text": "Preprocessing the names to make them compatible with Machine Learning (ML) models" }, { "code": null, "e": 1743, "s": 1620, "text": "Developing a Natural Language Processing (NLP) ML model to read in a name and output if it’s a boy’s name or a girl’s name" }, { "code": null, "e": 1807, "s": 1743, "text": "Building a simple web app for people to interact with the model" }, { "code": null, "e": 1842, "s": 1807, "text": "Publishing the app on the internet" }, { "code": null, "e": 2305, "s": 1842, "text": "To train any Machine Learning model, we need a large quantity of labeled data. In this case, we need a large number of names and the associated gender of that name. Luckily, Google Cloud’s Bigquery has a free open dataset called USA_NAMES [Link] that “contains all names from Social Security card applications for births that occurred in the United States.” The dataset contains roughly 35000 names and the associated gender, which works very well for our model." }, { "code": null, "e": 2465, "s": 2305, "text": "Human names are textual data, while ML models can only work with numeric data. To convert our text into a numeric representation, we’ll do the following steps." }, { "code": null, "e": 3181, "s": 2465, "text": "Lowercase the name since each character’s case doesn’t convey any information about a person’s gender.Split each character: The basic idea of the ML model we’re building is to read characters in a name to identify patterns that could indicate masculinity or femininity. Thus we split the name into each character.Pad names with empty spaces until a max of 50 characters ensures the ML model sees the same length for all the names.Encode each character to a unique number since ML models can only work with numbers. In this case, we encode ‘ ’ (space) to 0, ‘a’ to 1, ‘b’ to 2, and so on.Encode each gender to a unique number since ML models can only work with numbers. In this case, we encode ‘F’ to 0 and ‘M’ to 1." }, { "code": null, "e": 3284, "s": 3181, "text": "Lowercase the name since each character’s case doesn’t convey any information about a person’s gender." }, { "code": null, "e": 3496, "s": 3284, "text": "Split each character: The basic idea of the ML model we’re building is to read characters in a name to identify patterns that could indicate masculinity or femininity. Thus we split the name into each character." }, { "code": null, "e": 3614, "s": 3496, "text": "Pad names with empty spaces until a max of 50 characters ensures the ML model sees the same length for all the names." }, { "code": null, "e": 3772, "s": 3614, "text": "Encode each character to a unique number since ML models can only work with numbers. In this case, we encode ‘ ’ (space) to 0, ‘a’ to 1, ‘b’ to 2, and so on." }, { "code": null, "e": 3901, "s": 3772, "text": "Encode each gender to a unique number since ML models can only work with numbers. In this case, we encode ‘F’ to 0 and ‘M’ to 1." }, { "code": null, "e": 4253, "s": 3901, "text": "When we read a name, we identify the probable gender of that name by the sequence in which characters appear in that name. For example, “Stephen” is most likely a boy’s name but “Stephanie” is likely a girl’s name. To mimic the way we humans identify the gender of a name, we construct a simple Bidirectional LSTM model using the tensorflow.keras API." }, { "code": null, "e": 4803, "s": 4253, "text": "Embedding layer: to “embed” each input character’s encoded number into a dense 256 dimension vector. The choice of embedding_dim is a hyperparameter that can be tuned to get the desired accuracy.Bidirectional LSTM layer: read the sequence of character embeddings from the previous step and output a single vector representing that sequence. The values for units and dropouts are hyperparameters as well.Final Dense layer: to output a single value close to 0 for ‘F’ or close to 1 for ‘M’ since this is the encoding we used in the preprocessing step." }, { "code": null, "e": 4999, "s": 4803, "text": "Embedding layer: to “embed” each input character’s encoded number into a dense 256 dimension vector. The choice of embedding_dim is a hyperparameter that can be tuned to get the desired accuracy." }, { "code": null, "e": 5208, "s": 4999, "text": "Bidirectional LSTM layer: read the sequence of character embeddings from the previous step and output a single vector representing that sequence. The values for units and dropouts are hyperparameters as well." }, { "code": null, "e": 5355, "s": 5208, "text": "Final Dense layer: to output a single value close to 0 for ‘F’ or close to 1 for ‘M’ since this is the encoding we used in the preprocessing step." }, { "code": null, "e": 5422, "s": 5355, "text": "We’ll use the standard tensorflow.keras training pipeline as below" }, { "code": null, "e": 5791, "s": 5422, "text": "Instantiate the model using the function we wrote in the model architecture step.Split the data into 80% training and 20% validation.Call model.fit with EarlyStopping callback to stop training once the model starts to overfit.Save the trained model to reuse while serving the web app.Plot the training and validation accuracies to visually check the model performance." }, { "code": null, "e": 5873, "s": 5791, "text": "Instantiate the model using the function we wrote in the model architecture step." }, { "code": null, "e": 5926, "s": 5873, "text": "Split the data into 80% training and 20% validation." }, { "code": null, "e": 6020, "s": 5926, "text": "Call model.fit with EarlyStopping callback to stop training once the model starts to overfit." }, { "code": null, "e": 6079, "s": 6020, "text": "Save the trained model to reuse while serving the web app." }, { "code": null, "e": 6164, "s": 6079, "text": "Plot the training and validation accuracies to visually check the model performance." }, { "code": null, "e": 6709, "s": 6164, "text": "Now that we have the trained model with good accuracy, we can create a Plotly Dash [Link] web app [https://www.boyorgirl.xyz] to get input names from a user, load the model (only once during app startup), use the model to predict the gender on the input names, and visualize the results back on the web app. The below code snippet only shows the model inference part of the web app. The full Plotly Dash web app code, including the model load, text box input, table output, and interactive bar plot output, is available on my GitHub repository." }, { "code": null, "e": 6908, "s": 6709, "text": "The final step is to publish our new app on the internet for everyone worldwide to interact with. After a little bit of research, I decided to use Heroku to deploy the app for the following reasons." }, { "code": null, "e": 7009, "s": 6908, "text": "Free!!!A straightforward deployment processMax 500MB memory is sufficient for my small custom model." }, { "code": null, "e": 7017, "s": 7009, "text": "Free!!!" }, { "code": null, "e": 7054, "s": 7017, "text": "A straightforward deployment process" }, { "code": null, "e": 7112, "s": 7054, "text": "Max 500MB memory is sufficient for my small custom model." }, { "code": null, "e": 7344, "s": 7112, "text": "The steps to deploy an app to Heroku are well documented on the Heroku website [Link]. I made custom changes to support my mono-repo format, which I’ve documented in my Github repo [Link]. The main changes to support mono-repos are" }, { "code": null, "e": 7372, "s": 7344, "text": "Add the following buildpack" }, { "code": null, "e": 7460, "s": 7372, "text": "heroku buildpacks:add -a <app> https://github.com/lstoll/heroku-buildpack-monorepo -i 1" }, { "code": null, "e": 7486, "s": 7460, "text": "Add the following configs" }, { "code": null, "e": 7608, "s": 7486, "text": "heroku config:set -a <app> PROCFILE=relative/path/to/app/Procfileheroku config:set -a <app> APP_BASE=relative/path/to/app" }, { "code": null, "e": 8027, "s": 7608, "text": "Important! One major gotcha that took me some time to figure out is that Heroku starts two workers by default. So if your app’s size is more than 250MB, the two workers combined would exceed the 500MB limit that Heroku sets for free apps. Since I don't expect the traffic to my app to be large enough to need two workers, I easily solved this issue by specifying only one worker by using the -w 1 flag in the Procfile." }, { "code": null, "e": 8059, "s": 8027, "text": "web: gunicorn -w 1 serve:server" }, { "code": null, "e": 8255, "s": 8059, "text": "Free tier Heroku apps go to sleep after 30 mins of inactivity. Thus I used a free ping service called Kaffeine [Link] to ping my app once every 10mins. This will ensure zero downtime for the app." }, { "code": null, "e": 8437, "s": 8255, "text": "Subsequently, I upgraded from Free tier to Hobby tier (mainly for Free SSL on my custom domain), ensuring the app never sleeps, so the ping service is no longer relevant for my app." }, { "code": null, "e": 8576, "s": 8437, "text": "Finally, I purchased a cheap domain from Namecheap [Link] and pointed the domain to my Heroku app following instructions from here [Link]." }, { "code": null, "e": 8675, "s": 8576, "text": "On a serious note, we need to keep a few limitations and biases in mind while using this approach." }, { "code": null, "e": 9282, "s": 8675, "text": "The model has ZERO understanding of the concept of gender in the real world! It is only making an informed guess at which gender a specific name probably belongs to based on historical data of names belonging to different genders. For example, my name begins with “Marie,” which the model detects as a female name (with the confidence of ~90%!) though I’m actually a male. Thus this approach perpetuates the inherent bias in our names, and it’s beyond the scope of this work to address these biases.The training data only consisted of binary genders (M and F). Thus, non-binary genders are not represented." }, { "code": null, "e": 9782, "s": 9282, "text": "The model has ZERO understanding of the concept of gender in the real world! It is only making an informed guess at which gender a specific name probably belongs to based on historical data of names belonging to different genders. For example, my name begins with “Marie,” which the model detects as a female name (with the confidence of ~90%!) though I’m actually a male. Thus this approach perpetuates the inherent bias in our names, and it’s beyond the scope of this work to address these biases." }, { "code": null, "e": 9890, "s": 9782, "text": "The training data only consisted of binary genders (M and F). Thus, non-binary genders are not represented." }, { "code": null, "e": 9984, "s": 9890, "text": "In conclusion, please DO NOT use this app to make assumptions about anyone’s gender identity!" }, { "code": null, "e": 10417, "s": 9984, "text": "And that’s it! Our cool ML app to predict gender from names is now available for anyone on the internet to interact with! From my testing, the app seems to perform very well for English names and reasonably well for Indian names because of the names present in the training dataset. Non-English names like Chinese names performed poorly. Would you please take a look and let me know if it got your names correct? Thanks for reading!" }, { "code": null, "e": 10469, "s": 10417, "text": "All the code is available on my Github repo: [Link]" } ]
Python selenium browser driver.back().
We can navigate back in the browser with Selenium webdriver. There are multiple ways to achieve this. The back() method is used to move back to the prior browser page. This method only is applicable if we jump from webpage to another. We can also move back in the browser with the help of a Javascript Executor in Selenium. It has the execute_script() method which allows Selenium to run Javascript commands. We have to execute the Javascript command window.history.go(-1) to go back to the previous page. from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) #launch a webpage driver.get("https://www.tutorialspoint.com/about/about_careers.htm") print("Current Page title: " + driver.title) #launch another webpage driver.get("https://www.tutorialspoint.com/questions/index.php") print("Current Page title: " + driver.title) #back to previous page with back() driver.back() print("Current Page title after back: " + driver.title) Code Implementation with Javascript Executor. from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) #launch a webpage driver.get("https://www.tutorialspoint.com/about/about_careers.htm") print("Current Page title: " + driver.title) #launch another webpage driver.get("https://www.tutorialspoint.com/questions/index.php") print("Current Page title: " + driver.title) #back to previous page with execute_script() driver.execute_script("window.history.go(-1)") print("Current Page title after back: " + driver.title)
[ { "code": null, "e": 1422, "s": 1187, "text": "We can navigate back in the browser with Selenium webdriver. There are multiple ways to achieve this. The back() method is used to move back to the prior browser page. This method only is applicable if we jump from webpage to another." }, { "code": null, "e": 1693, "s": 1422, "text": "We can also move back in the browser with the help of a Javascript Executor in Selenium. It has the execute_script() method which allows Selenium to run Javascript commands. We have to execute the Javascript command window.history.go(-1) to go back to the previous page." }, { "code": null, "e": 2190, "s": 1693, "text": "from selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch a webpage\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\nprint(\"Current Page title: \" + driver.title)\n#launch another webpage\ndriver.get(\"https://www.tutorialspoint.com/questions/index.php\")\nprint(\"Current Page title: \" + driver.title)\n#back to previous page with back()\ndriver.back()\nprint(\"Current Page title after back: \" + driver.title)" }, { "code": null, "e": 2236, "s": 2190, "text": "Code Implementation with Javascript Executor." }, { "code": null, "e": 2776, "s": 2236, "text": "from selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch a webpage\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\nprint(\"Current Page title: \" + driver.title)\n#launch another webpage\ndriver.get(\"https://www.tutorialspoint.com/questions/index.php\")\nprint(\"Current Page title: \" + driver.title)\n#back to previous page with execute_script()\ndriver.execute_script(\"window.history.go(-1)\")\nprint(\"Current Page title after back: \" + driver.title)" } ]
YACC program to recognize strings of { anb | n≥5 }
07 May, 2019 Problem: Write YACC program to recognize strings of { anb | n≥5 } Explanation:Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc. Examples: Input: ab Output: invalid string Input: aaaaab Output: valid string Input: aabb Output: invalid string Input: aaaaaaab Output: valid string Input: aaaaaabb Output: invalid string Lexical Analyzer Source Code: %{ /* Definition section */ #include "y.tab.h" %} /* Rule Section */ %%[aA] {return A;}[bB] {return B;}\n {return NL;}. {return yytext[0];} %% int yywrap() { return 1; } Parser Source Code: %{ /* Definition section */ #include<stdio.h> #include<stdlib.h> %} %token A B NL /* Rule Section */%%stmt: A A A A A S B NL {printf("valid string\n"); exit(0);};S: S A|;%% int yyerror(char *msg) { printf("invalid string\n"); exit(0); } //driver code main() { printf("enter the string\n"); yyparse(); } Output: Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Issues in the design of a code generator Peephole Optimization in Compiler Design Code Optimization in Compiler Design Type Checking in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Difference between Compiler and Interpreter Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Introduction of Compiler Design Runtime Environments in Compiler Design
[ { "code": null, "e": 53, "s": 25, "text": "\n07 May, 2019" }, { "code": null, "e": 119, "s": 53, "text": "Problem: Write YACC program to recognize strings of { anb | n≥5 }" }, { "code": null, "e": 416, "s": 119, "text": "Explanation:Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc." }, { "code": null, "e": 426, "s": 416, "text": "Examples:" }, { "code": null, "e": 610, "s": 426, "text": "Input: ab\nOutput: invalid string\n\nInput: aaaaab\nOutput: valid string\n\nInput: aabb\nOutput: invalid string\n\nInput: aaaaaaab\nOutput: valid string\n\nInput: aaaaaabb\nOutput: invalid string " }, { "code": null, "e": 640, "s": 610, "text": "Lexical Analyzer Source Code:" }, { "code": "%{ /* Definition section */ #include \"y.tab.h\" %} /* Rule Section */ %%[aA] {return A;}[bB] {return B;}\\n {return NL;}. {return yytext[0];} %% int yywrap() { return 1; } ", "e": 823, "s": 640, "text": null }, { "code": null, "e": 843, "s": 823, "text": "Parser Source Code:" }, { "code": "%{ /* Definition section */ #include<stdio.h> #include<stdlib.h> %} %token A B NL /* Rule Section */%%stmt: A A A A A S B NL {printf(\"valid string\\n\"); exit(0);};S: S A|;%% int yyerror(char *msg) { printf(\"invalid string\\n\"); exit(0); } //driver code main() { printf(\"enter the string\\n\"); yyparse(); }", "e": 1172, "s": 843, "text": null }, { "code": null, "e": 1180, "s": 1172, "text": "Output:" }, { "code": null, "e": 1192, "s": 1180, "text": "Lex program" }, { "code": null, "e": 1208, "s": 1192, "text": "Compiler Design" }, { "code": null, "e": 1306, "s": 1208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1347, "s": 1306, "text": "Issues in the design of a code generator" }, { "code": null, "e": 1388, "s": 1347, "text": "Peephole Optimization in Compiler Design" }, { "code": null, "e": 1425, "s": 1388, "text": "Code Optimization in Compiler Design" }, { "code": null, "e": 1458, "s": 1425, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 1516, "s": 1458, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 1560, "s": 1516, "text": "Difference between Compiler and Interpreter" }, { "code": null, "e": 1591, "s": 1560, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 1661, "s": 1591, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 1693, "s": 1661, "text": "Introduction of Compiler Design" } ]
VideoView in Kotlin
08 Jun, 2022 VideoView class of Kotlin is used to display video files in the android application. This class supports the 3gp and MP4 video formats. VideoView class is capable of playing a video file either from local storage, specific URL or from a resource file. The drawback of this class is that it does not retain the full state of the video file if the application goes into the background it means that the current play position, play state, or any kind of subtitle track can not be restored. This example demonstrates steps involved in adding a video file in an android activity from local storage. A media controller is also added to the activity to control the play and pause the position of the video. Note: Following steps are performed on Android Studio version 4.0 Click on File, then New => New Project.Select language as Kotlin.Select the minimum SDK as per your need. Click on File, then New => New Project. Select language as Kotlin. Select the minimum SDK as per your need. Add VideoView in activity_main.xml file Below is the code for activity_main.xml file to add a TextView and a VideoView in an activity. xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:isScrollContainer="false" android:text="@string/heading_of_activity" android:textAlignment="center" android:textColor="#1FBC26" android:textSize="30sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.01999998" /> <VideoView android:id="@+id/simpleVideoView" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> </androidx.constraintlayout.widget.ConstraintLayout> Below is the code for MainActivity.kt file to access VideoView widget in Kotlin file and to add a media controller for it. Note: Make sure to create a directory named raw in the resource file of your project and add the video file in that directory using file explorer. Java package com.example.videoviewinkotlin import android.net.Uriimport android.os.Bundleimport android.view.Viewimport android.widget.MediaControllerimport android.widget.Toastimport android.widget.VideoViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // declaring a null variable for VideoView var simpleVideoView: VideoView? = null // declaring a null variable for MediaController var mediaControls: MediaController? = null override fun onCreate(savedInstanceState: Bundle?){ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning id of VideoView from // activity_main.xml layout file simpleVideoView = findViewById<View>(R.id.simpleVideoView) as VideoView if (mediaControls == null) { // creating an object of media controller class mediaControls = MediaController(this) // set the anchor view for the video view mediaControls!!.setAnchorView(this.simpleVideoView) } // set the media controller for video view simpleVideoView!!.setMediaController(mediaControls) // set the absolute path of the video file which is going to be played simpleVideoView!!.setVideoURI(Uri.parse("android.resource://" + packageName + "/" + R.raw.gfgvideo)) simpleVideoView!!.requestFocus() // starting the video simpleVideoView!!.start() // display a toast message // after the video is completed simpleVideoView!!.setOnCompletionListener { Toast.makeText(applicationContext, "Video completed", Toast.LENGTH_LONG).show() } // display a toast message if any // error occurs while playing the video simpleVideoView!!.setOnErrorListener { mp, what, extra -> Toast.makeText(applicationContext, "An Error Occurred " + "While Playing Video !!!", Toast.LENGTH_LONG).show() false } }} All the strings which are used in the activity are listed in this file. Java <resources> <string name="app_name">VideoView in Kotlin</string> <string name="heading_of_activity">Running a video file in an activity</string></resources> Below is the code for AndroidManifest.xml file Java <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http:// schemas.android.com/apk/res/android" package="com.example.videoviewinkotlin"> <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> <meta-data android:name="preloaded_fonts" android:resource="@array/preloaded_fonts" /> </application> </manifest> surindertarika1234 nikhatkhan11 android Android-View Kotlin Android Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Android RecyclerView in Kotlin Broadcast Receiver in Android With Example How to Communicate Between Fragments in Android?
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 542, "s": 54, "text": "VideoView class of Kotlin is used to display video files in the android application. This class supports the 3gp and MP4 video formats. VideoView class is capable of playing a video file either from local storage, specific URL or from a resource file. The drawback of this class is that it does not retain the full state of the video file if the application goes into the background it means that the current play position, play state, or any kind of subtitle track can not be restored. " }, { "code": null, "e": 764, "s": 550, "text": "This example demonstrates steps involved in adding a video file in an android activity from local storage. A media controller is also added to the activity to control the play and pause the position of the video. " }, { "code": null, "e": 830, "s": 764, "text": "Note: Following steps are performed on Android Studio version 4.0" }, { "code": null, "e": 938, "s": 832, "text": "Click on File, then New => New Project.Select language as Kotlin.Select the minimum SDK as per your need." }, { "code": null, "e": 978, "s": 938, "text": "Click on File, then New => New Project." }, { "code": null, "e": 1005, "s": 978, "text": "Select language as Kotlin." }, { "code": null, "e": 1046, "s": 1005, "text": "Select the minimum SDK as per your need." }, { "code": null, "e": 1086, "s": 1046, "text": "Add VideoView in activity_main.xml file" }, { "code": null, "e": 1183, "s": 1086, "text": "Below is the code for activity_main.xml file to add a TextView and a VideoView in an activity. " }, { "code": null, "e": 1187, "s": 1183, "text": "xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:isScrollContainer=\"false\" android:text=\"@string/heading_of_activity\" android:textAlignment=\"center\" android:textColor=\"#1FBC26\" android:textSize=\"30sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.01999998\" /> <VideoView android:id=\"@+id/simpleVideoView\" android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"10dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2815, "s": 1187, "text": null }, { "code": null, "e": 2939, "s": 2815, "text": "Below is the code for MainActivity.kt file to access VideoView widget in Kotlin file and to add a media controller for it. " }, { "code": null, "e": 3086, "s": 2939, "text": "Note: Make sure to create a directory named raw in the resource file of your project and add the video file in that directory using file explorer." }, { "code": null, "e": 3093, "s": 3088, "text": "Java" }, { "code": "package com.example.videoviewinkotlin import android.net.Uriimport android.os.Bundleimport android.view.Viewimport android.widget.MediaControllerimport android.widget.Toastimport android.widget.VideoViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // declaring a null variable for VideoView var simpleVideoView: VideoView? = null // declaring a null variable for MediaController var mediaControls: MediaController? = null override fun onCreate(savedInstanceState: Bundle?){ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning id of VideoView from // activity_main.xml layout file simpleVideoView = findViewById<View>(R.id.simpleVideoView) as VideoView if (mediaControls == null) { // creating an object of media controller class mediaControls = MediaController(this) // set the anchor view for the video view mediaControls!!.setAnchorView(this.simpleVideoView) } // set the media controller for video view simpleVideoView!!.setMediaController(mediaControls) // set the absolute path of the video file which is going to be played simpleVideoView!!.setVideoURI(Uri.parse(\"android.resource://\" + packageName + \"/\" + R.raw.gfgvideo)) simpleVideoView!!.requestFocus() // starting the video simpleVideoView!!.start() // display a toast message // after the video is completed simpleVideoView!!.setOnCompletionListener { Toast.makeText(applicationContext, \"Video completed\", Toast.LENGTH_LONG).show() } // display a toast message if any // error occurs while playing the video simpleVideoView!!.setOnErrorListener { mp, what, extra -> Toast.makeText(applicationContext, \"An Error Occurred \" + \"While Playing Video !!!\", Toast.LENGTH_LONG).show() false } }}", "e": 5159, "s": 3093, "text": null }, { "code": null, "e": 5232, "s": 5159, "text": "All the strings which are used in the activity are listed in this file. " }, { "code": null, "e": 5237, "s": 5232, "text": "Java" }, { "code": "<resources> <string name=\"app_name\">VideoView in Kotlin</string> <string name=\"heading_of_activity\">Running a video file in an activity</string></resources>", "e": 5400, "s": 5237, "text": null }, { "code": null, "e": 5448, "s": 5400, "text": "Below is the code for AndroidManifest.xml file " }, { "code": null, "e": 5453, "s": 5448, "text": "Java" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http:// schemas.android.com/apk/res/android\" package=\"com.example.videoviewinkotlin\"> <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> <meta-data android:name=\"preloaded_fonts\" android:resource=\"@array/preloaded_fonts\" /> </application> </manifest>", "e": 6277, "s": 5453, "text": null }, { "code": null, "e": 6296, "s": 6277, "text": "surindertarika1234" }, { "code": null, "e": 6309, "s": 6296, "text": "nikhatkhan11" }, { "code": null, "e": 6317, "s": 6309, "text": "android" }, { "code": null, "e": 6330, "s": 6317, "text": "Android-View" }, { "code": null, "e": 6345, "s": 6330, "text": "Kotlin Android" }, { "code": null, "e": 6352, "s": 6345, "text": "Picked" }, { "code": null, "e": 6360, "s": 6352, "text": "Android" }, { "code": null, "e": 6367, "s": 6360, "text": "Kotlin" }, { "code": null, "e": 6375, "s": 6367, "text": "Android" }, { "code": null, "e": 6473, "s": 6375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6542, "s": 6473, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6573, "s": 6542, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 6616, "s": 6573, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 6648, "s": 6616, "text": "Android SDK and it's Components" }, { "code": null, "e": 6687, "s": 6648, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6756, "s": 6687, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6775, "s": 6756, "text": "Android UI Layouts" }, { "code": null, "e": 6806, "s": 6775, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 6849, "s": 6806, "text": "Broadcast Receiver in Android With Example" } ]
Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
01 Sep, 2021 Given a binary tree, the task is to print nodes of extreme corners of each level but in alternate order.Examples: Input : 1 / \ 2 3 / / \ 4 5 6 / / \ 7 8 9 Output : 1 2 6 7 Print the rightmost node at 1st level: 1 Print the leftmost node at 2nd level: 2 Print the rightmost node at 3rd level: 6 Print the leftmost node at 4th level: 7 Other possible output will be -> 1 3 4 9 Input : 3 / \ 8 1 / \ / \ 9 5 6 4 Output : 3 8 4 We have already discussed the iterative approach to solve this problem. In this post the recursive approach is discussed.Approach: The idea is to perform level order traversal in the spiral form and at each level print the first node during the traversal, these will be the nodes at extreme corner present in the alternate form.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print nodes of extreme corners// of each level in alternate order #include <bits/stdc++.h>using namespace std; // A binary tree nodestruct Node { int data; Node *left, *right;}; // Utility function to allocate memory for a new nodeNode* newNode(int data){ Node* node = new (Node); node->data = data; node->left = node->right = NULL; return (node);} // Function that returns the height of the binary treeint height(Node* root){ if (root == NULL) return 0; int lheight = height(root->left); int rheight = height(root->right); return max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalvoid rightToLeft(Node* root, int level, int& f){ if (root == NULL) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f == 0) { printf("%d ", root->data); f = 1; } else if (level > 1) { rightToLeft(root->right, level - 1, f); rightToLeft(root->left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalvoid leftToRight(Node* root, int level, int& f){ if (root == NULL) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f == 1) { printf("%d ", root->data); f = 0; } else if (level > 1) { leftToRight(root->left, level - 1, f); leftToRight(root->right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treevoid printExtremeNodes(Node* root){ // Stores height of binary tree int h = height(root); // Flag to mark the change in level int flag = 0; // To check if the extreme node of a // particular level has been visited int f = 0; for (int i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->right->left = newNode(14); root->right->right->right = newNode(15); root->left->left->left->left = newNode(16); root->left->left->left->right = newNode(17); root->right->right->right->right = newNode(31); printExtremeNodes(root); return 0;} // Java program to print nodes of extreme corners// of each level in alternate orderimport java.util.*; class GFG{ //INT classstatic class INT{ int a;} // A binary tree nodestatic class Node{ int data; Node left, right;}; // Utility function to allocate memory for a new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function that returns the height of the binary treestatic int height(Node root){ if (root == null) return 0; int lheight = height(root.left); int rheight = height(root.right); return Math.max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalstatic void rightToLeft(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 0) { System.out.printf("%d ", root.data); f.a = 1; } else if (level > 1) { rightToLeft(root.right, level - 1, f); rightToLeft(root.left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalstatic void leftToRight(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 1) { System.out.printf("%d ", root.data); f.a = 0; } else if (level > 1) { leftToRight(root.left, level - 1, f); leftToRight(root.right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treestatic void printExtremeNodes(Node root){ // Stores height of binary tree int h = height(root); // Flag to mark the change in level int flag = 0; // To check if the extreme node of a // particular level has been visited INT f=new INT(); f.a = 0; for (int i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(8); root.left.left.right = newNode(9); root.left.right.left = newNode(10); root.left.right.right = newNode(11); root.right.right.left = newNode(14); root.right.right.right = newNode(15); root.left.left.left.left = newNode(16); root.left.left.left.right = newNode(17); root.right.right.right.right = newNode(31); printExtremeNodes(root); }} // This code is contributed by Arnab Kundu # Python3 program to print nodes of# extreme corners of each level in# alternate orderfrom collections import deque # A binary tree node has key, pointer to left# child and a pointer to right childclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function that returns the height of# the binary treedef height(root: Node) -> int: if (root is None): return 0 lheight = height(root.left) rheight = height(root.right) return max(lheight, rheight) + 1 # Function performs level order traversal# from right to left and prints the first# node during the traversaldef rightToLeft(root: Node, level: int) -> int: global f if (root is None): return # Checks for the value of f so that # only first node is printed during # the traversal and no other node is printed if (level == 1 and f == 0): print("%d " % root.data, end = "") f = 1 elif (level > 1): rightToLeft(root.right, level - 1) rightToLeft(root.left, level - 1) # Function performs level order traversal# from left to right and prints the first# node during the traversaldef leftToRight(root: Node, level: int): global f if (root is None): return # Checks for the value of f so that # only first node is printed during # the traversal and no other node is printed if (level == 1 and f == 1): print("%d " % root.data, end = "") f = 0 elif (level > 1): leftToRight(root.left, level - 1) leftToRight(root.right, level - 1) # Function to print the extreme nodes of# a given binary treedef printExtremeNodes(root: Node): global f # Stores height of binary tree h = height(root) # Flag to mark the change in level flag = 0 # To check if the extreme node of a # particular level has been visited f = 0 for i in range(1, h + 1): # If flag is zero then traverse from # right to left at the given level and # print the first node during the traversal if (flag == 0): rightToLeft(root, i) flag = 1 # If flag is one then traverse from # left to right at the given level and # print the first node during the traversal elif (flag == 1): leftToRight(root, i) flag = 0 return # Driver Codeif __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(7) root.left.left.left = Node(8) root.left.left.right = Node(9) root.left.right.left = Node(10) root.left.right.right = Node(11) root.right.right.left = Node(14) root.right.right.right = Node(15) root.left.left.left.left = Node(16) root.left.left.left.right = Node(17) root.right.right.right.right = Node(31) printExtremeNodes(root) # This code is contributed by sanjeev2552 // C# program to print nodes of extreme corners// of each level in alternate orderusing System; class GFG{ //INT classpublic class INT{ public int a;} // A binary tree nodepublic class Node{ public int data; public Node left, right;}; // Utility function to allocate memory for a new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function that returns the height of the binary treestatic int height(Node root){ if (root == null) return 0; int lheight = height(root.left); int rheight = height(root.right); return Math.Max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalstatic void rightToLeft(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 0) { Console.Write("{0} ", root.data); f.a = 1; } else if (level > 1) { rightToLeft(root.right, level - 1, f); rightToLeft(root.left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalstatic void leftToRight(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 1) { Console.Write("{0} ", root.data); f.a = 0; } else if (level > 1) { leftToRight(root.left, level - 1, f); leftToRight(root.right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treestatic void printExtremeNodes(Node root){ // Stores height of binary tree int h = height(root); // Flag to mark the change in level int flag = 0; // To check if the extreme node of a // particular level has been visited INT f=new INT(); f.a = 0; for (int i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codepublic static void Main(){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(8); root.left.left.right = newNode(9); root.left.right.left = newNode(10); root.left.right.right = newNode(11); root.right.right.left = newNode(14); root.right.right.right = newNode(15); root.left.left.left.left = newNode(16); root.left.left.left.right = newNode(17); root.right.right.right.right = newNode(31); printExtremeNodes(root); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program to print nodes of extreme corners// of each level in alternate order //INT classclass INT{ constructor() { this.a = 0; }} // A binary tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Utility function to allocate memory for a new nodefunction newNode(data){ var node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function that returns the height of the binary treefunction height(root){ if (root == null) return 0; var lheight = height(root.left); var rheight = height(root.right); return Math.max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalfunction rightToLeft(root, level, f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 0) { document.write(root.data + " "); f.a = 1; } else if (level > 1) { rightToLeft(root.right, level - 1, f); rightToLeft(root.left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalfunction leftToRight(root, level, f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 1) { document.write(root.data+ " "); f.a = 0; } else if (level > 1) { leftToRight(root.left, level - 1, f); leftToRight(root.right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treefunction printExtremeNodes(root){ // Stores height of binary tree var h = height(root); // Flag to mark the change in level var flag = 0; // To check if the extreme node of a // particular level has been visited var f=new INT(); f.a = 0; for (var i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.right = newNode(7);root.left.left.left = newNode(8);root.left.left.right = newNode(9);root.left.right.left = newNode(10);root.left.right.right = newNode(11);root.right.right.left = newNode(14);root.right.right.right = newNode(15);root.left.left.left.left = newNode(16);root.left.left.left.right = newNode(17);root.right.right.right.right = newNode(31);printExtremeNodes(root); </script> 1 2 7 8 31 Time Complexity: O(N^2), where N is the total number of nodes in the binary tree. Auxiliary Space: O(N) andrew1234 princiraj1992 sanjeev2552 itsok pankajsharmagfg Binary Tree spiral Data Structures Tree Data Structures Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 144, "s": 28, "text": "Given a binary tree, the task is to print nodes of extreme corners of each level but in alternate order.Examples: " }, { "code": null, "e": 560, "s": 144, "text": "Input : \n 1\n / \\\n 2 3\n / / \\\n 4 5 6\n / / \\\n 7 8 9\nOutput : 1 2 6 7\nPrint the rightmost node at 1st level: 1\nPrint the leftmost node at 2nd level: 2\nPrint the rightmost node at 3rd level: 6\nPrint the leftmost node at 4th level: 7\nOther possible output will be -> 1 3 4 9\n\nInput :\n 3 \n / \\\n 8 1\n / \\ / \\\n 9 5 6 4\nOutput : 3 8 4" }, { "code": null, "e": 943, "s": 562, "text": "We have already discussed the iterative approach to solve this problem. In this post the recursive approach is discussed.Approach: The idea is to perform level order traversal in the spiral form and at each level print the first node during the traversal, these will be the nodes at extreme corner present in the alternate form.Below is the implementation of the above approach: " }, { "code": null, "e": 947, "s": 943, "text": "C++" }, { "code": null, "e": 952, "s": 947, "text": "Java" }, { "code": null, "e": 960, "s": 952, "text": "Python3" }, { "code": null, "e": 963, "s": 960, "text": "C#" }, { "code": null, "e": 974, "s": 963, "text": "Javascript" }, { "code": "// C++ program to print nodes of extreme corners// of each level in alternate order #include <bits/stdc++.h>using namespace std; // A binary tree nodestruct Node { int data; Node *left, *right;}; // Utility function to allocate memory for a new nodeNode* newNode(int data){ Node* node = new (Node); node->data = data; node->left = node->right = NULL; return (node);} // Function that returns the height of the binary treeint height(Node* root){ if (root == NULL) return 0; int lheight = height(root->left); int rheight = height(root->right); return max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalvoid rightToLeft(Node* root, int level, int& f){ if (root == NULL) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f == 0) { printf(\"%d \", root->data); f = 1; } else if (level > 1) { rightToLeft(root->right, level - 1, f); rightToLeft(root->left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalvoid leftToRight(Node* root, int level, int& f){ if (root == NULL) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f == 1) { printf(\"%d \", root->data); f = 0; } else if (level > 1) { leftToRight(root->left, level - 1, f); leftToRight(root->right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treevoid printExtremeNodes(Node* root){ // Stores height of binary tree int h = height(root); // Flag to mark the change in level int flag = 0; // To check if the extreme node of a // particular level has been visited int f = 0; for (int i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->right->left = newNode(14); root->right->right->right = newNode(15); root->left->left->left->left = newNode(16); root->left->left->left->right = newNode(17); root->right->right->right->right = newNode(31); printExtremeNodes(root); return 0;}", "e": 4158, "s": 974, "text": null }, { "code": "// Java program to print nodes of extreme corners// of each level in alternate orderimport java.util.*; class GFG{ //INT classstatic class INT{ int a;} // A binary tree nodestatic class Node{ int data; Node left, right;}; // Utility function to allocate memory for a new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function that returns the height of the binary treestatic int height(Node root){ if (root == null) return 0; int lheight = height(root.left); int rheight = height(root.right); return Math.max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalstatic void rightToLeft(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 0) { System.out.printf(\"%d \", root.data); f.a = 1; } else if (level > 1) { rightToLeft(root.right, level - 1, f); rightToLeft(root.left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalstatic void leftToRight(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 1) { System.out.printf(\"%d \", root.data); f.a = 0; } else if (level > 1) { leftToRight(root.left, level - 1, f); leftToRight(root.right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treestatic void printExtremeNodes(Node root){ // Stores height of binary tree int h = height(root); // Flag to mark the change in level int flag = 0; // To check if the extreme node of a // particular level has been visited INT f=new INT(); f.a = 0; for (int i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(8); root.left.left.right = newNode(9); root.left.right.left = newNode(10); root.left.right.right = newNode(11); root.right.right.left = newNode(14); root.right.right.right = newNode(15); root.left.left.left.left = newNode(16); root.left.left.left.right = newNode(17); root.right.right.right.right = newNode(31); printExtremeNodes(root); }} // This code is contributed by Arnab Kundu", "e": 7493, "s": 4158, "text": null }, { "code": "# Python3 program to print nodes of# extreme corners of each level in# alternate orderfrom collections import deque # A binary tree node has key, pointer to left# child and a pointer to right childclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function that returns the height of# the binary treedef height(root: Node) -> int: if (root is None): return 0 lheight = height(root.left) rheight = height(root.right) return max(lheight, rheight) + 1 # Function performs level order traversal# from right to left and prints the first# node during the traversaldef rightToLeft(root: Node, level: int) -> int: global f if (root is None): return # Checks for the value of f so that # only first node is printed during # the traversal and no other node is printed if (level == 1 and f == 0): print(\"%d \" % root.data, end = \"\") f = 1 elif (level > 1): rightToLeft(root.right, level - 1) rightToLeft(root.left, level - 1) # Function performs level order traversal# from left to right and prints the first# node during the traversaldef leftToRight(root: Node, level: int): global f if (root is None): return # Checks for the value of f so that # only first node is printed during # the traversal and no other node is printed if (level == 1 and f == 1): print(\"%d \" % root.data, end = \"\") f = 0 elif (level > 1): leftToRight(root.left, level - 1) leftToRight(root.right, level - 1) # Function to print the extreme nodes of# a given binary treedef printExtremeNodes(root: Node): global f # Stores height of binary tree h = height(root) # Flag to mark the change in level flag = 0 # To check if the extreme node of a # particular level has been visited f = 0 for i in range(1, h + 1): # If flag is zero then traverse from # right to left at the given level and # print the first node during the traversal if (flag == 0): rightToLeft(root, i) flag = 1 # If flag is one then traverse from # left to right at the given level and # print the first node during the traversal elif (flag == 1): leftToRight(root, i) flag = 0 return # Driver Codeif __name__ == \"__main__\": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(7) root.left.left.left = Node(8) root.left.left.right = Node(9) root.left.right.left = Node(10) root.left.right.right = Node(11) root.right.right.left = Node(14) root.right.right.right = Node(15) root.left.left.left.left = Node(16) root.left.left.left.right = Node(17) root.right.right.right.right = Node(31) printExtremeNodes(root) # This code is contributed by sanjeev2552", "e": 10482, "s": 7493, "text": null }, { "code": "// C# program to print nodes of extreme corners// of each level in alternate orderusing System; class GFG{ //INT classpublic class INT{ public int a;} // A binary tree nodepublic class Node{ public int data; public Node left, right;}; // Utility function to allocate memory for a new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function that returns the height of the binary treestatic int height(Node root){ if (root == null) return 0; int lheight = height(root.left); int rheight = height(root.right); return Math.Max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalstatic void rightToLeft(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 0) { Console.Write(\"{0} \", root.data); f.a = 1; } else if (level > 1) { rightToLeft(root.right, level - 1, f); rightToLeft(root.left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalstatic void leftToRight(Node root, int level, INT f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 1) { Console.Write(\"{0} \", root.data); f.a = 0; } else if (level > 1) { leftToRight(root.left, level - 1, f); leftToRight(root.right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treestatic void printExtremeNodes(Node root){ // Stores height of binary tree int h = height(root); // Flag to mark the change in level int flag = 0; // To check if the extreme node of a // particular level has been visited INT f=new INT(); f.a = 0; for (int i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codepublic static void Main(){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(8); root.left.left.right = newNode(9); root.left.right.left = newNode(10); root.left.right.right = newNode(11); root.right.right.left = newNode(14); root.right.right.right = newNode(15); root.left.left.left.left = newNode(16); root.left.left.left.right = newNode(17); root.right.right.right.right = newNode(31); printExtremeNodes(root); }} /* This code contributed by PrinciRaj1992 */", "e": 13813, "s": 10482, "text": null }, { "code": "<script> // JavaScript program to print nodes of extreme corners// of each level in alternate order //INT classclass INT{ constructor() { this.a = 0; }} // A binary tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Utility function to allocate memory for a new nodefunction newNode(data){ var node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function that returns the height of the binary treefunction height(root){ if (root == null) return 0; var lheight = height(root.left); var rheight = height(root.right); return Math.max(lheight, rheight) + 1;} // Function performs level order traversal from right to// left and prints the first node during the traversalfunction rightToLeft(root, level, f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 0) { document.write(root.data + \" \"); f.a = 1; } else if (level > 1) { rightToLeft(root.right, level - 1, f); rightToLeft(root.left, level - 1, f); }} // Function performs level order traversal from left to// right and prints the first node during the traversalfunction leftToRight(root, level, f){ if (root == null) return; // Checks for the value of f so that // only first node is printed during // the traversal and no other node is printed if (level == 1 && f.a == 1) { document.write(root.data+ \" \"); f.a = 0; } else if (level > 1) { leftToRight(root.left, level - 1, f); leftToRight(root.right, level - 1, f); }} // Function to print the extreme nodes of// a given binary treefunction printExtremeNodes(root){ // Stores height of binary tree var h = height(root); // Flag to mark the change in level var flag = 0; // To check if the extreme node of a // particular level has been visited var f=new INT(); f.a = 0; for (var i = 1; i <= h; i++) { // If flag is zero then traverse from // right to left at the given level and // print the first node during the traversal if (flag == 0) { rightToLeft(root, i, f); flag = 1; } // If flag is one then traverse from // left to right at the given level and // print the first node during the traversal else if (flag == 1) { leftToRight(root, i, f); flag = 0; } } return;} // Driver codevar root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.right = newNode(7);root.left.left.left = newNode(8);root.left.left.right = newNode(9);root.left.right.left = newNode(10);root.left.right.right = newNode(11);root.right.right.left = newNode(14);root.right.right.right = newNode(15);root.left.left.left.left = newNode(16);root.left.left.left.right = newNode(17);root.right.right.right.right = newNode(31);printExtremeNodes(root); </script>", "e": 17013, "s": 13813, "text": null }, { "code": null, "e": 17028, "s": 17013, "text": "1 2 7 8 31 " }, { "code": null, "e": 17134, "s": 17030, "text": "Time Complexity: O(N^2), where N is the total number of nodes in the binary tree. Auxiliary Space: O(N)" }, { "code": null, "e": 17145, "s": 17134, "text": "andrew1234" }, { "code": null, "e": 17159, "s": 17145, "text": "princiraj1992" }, { "code": null, "e": 17171, "s": 17159, "text": "sanjeev2552" }, { "code": null, "e": 17177, "s": 17171, "text": "itsok" }, { "code": null, "e": 17193, "s": 17177, "text": "pankajsharmagfg" }, { "code": null, "e": 17205, "s": 17193, "text": "Binary Tree" }, { "code": null, "e": 17212, "s": 17205, "text": "spiral" }, { "code": null, "e": 17228, "s": 17212, "text": "Data Structures" }, { "code": null, "e": 17233, "s": 17228, "text": "Tree" }, { "code": null, "e": 17249, "s": 17233, "text": "Data Structures" }, { "code": null, "e": 17254, "s": 17249, "text": "Tree" } ]
Print numbers in matrix diagonal pattern in C Program.
The task is to print the matrix of n x n of the diagonal pattern. If n is 3 then to print a matrix in Diagonal pattern is − So the output will be like − Input: 3 Output: 1 2 4 3 5 7 6 8 9 Input: 4 Output: 1 2 4 7 3 5 8 11 6 9 12 14 10 13 15 16 The problem suggests we have to give a number n and generate a matrix of n x n and then we have to traverse the matrix in a diagonal pattern and store the values in a separate matrix. But this will increase the complexity of our code, so we will − Create a matrix of size N X N which will store the pattern before printing. Create a matrix of size N X N which will store the pattern before printing. Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and the column index decreases by 1 as you move down the diagonal. Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and the column index decreases by 1 as you move down the diagonal. Once the upper triangle is completed then store the elements of the lower triangle in a similar way as the upper triangle i.e. row index increases by 1 and column index decreases by 1 as you move down the diagonal. Once the upper triangle is completed then store the elements of the lower triangle in a similar way as the upper triangle i.e. row index increases by 1 and column index decreases by 1 as you move down the diagonal. int printdiagonal(int n) START STEP 1: DECLARE int mat[n][n], i, j, k, d=1, m STEP 2: LOOP FOR i = 0 AND i < n AND i++ ASSIGN j AS i AND k AS 0 LOOP FOR j = I AND j >= 0 AND j-- ASSIGN mat[k][j] AS d INCREMENT d AND k BY 1 END LOOP END LOOP STEP 3: LOOP FOR k = 1 AND k < n AND k++ ASSIGN i AND m EQUALS TO k LOOP FOR j = n-1 AND j >= m AND j-- ASSIGN mat[i][j] AS d; INCREMENT d AND i WITH 1 END FOR END FOR STEP 4: LOOP FOR i = 0 AND i < n AND i++ LOOP FOR j = 0 AND j < n AND j++ PRINT mat[i][j] END FOR PRINT NEWLINE END FOR STOP #include <stdio.h> int printdiagonal(int n){ int mat[n][n], i, j, k, d=1, m; for ( i = 0; i < n; i++){ j = i; k = 0; for ( j = i; j >= 0; j--){ mat[k][j] = d; d++; k++; } } for ( k = 1; k < n; k++){ i = m = k; for ( j = n-1; j >= m; j--){ mat[i][j] = d; d++; i++; } } for ( i = 0; i < n; i++){ for(j = 0; j < n; j++){ printf("%d ", mat[i][j] ); } printf("\n"); } } int main(int argc, char const *argv[]){ int n = 3; printdiagonal(n); return 0; } If we run the above program then it will generate the following output − 1 2 4 3 5 7 6 8 9
[ { "code": null, "e": 1253, "s": 1187, "text": "The task is to print the matrix of n x n of the diagonal pattern." }, { "code": null, "e": 1311, "s": 1253, "text": "If n is 3 then to print a matrix in Diagonal pattern is −" }, { "code": null, "e": 1340, "s": 1311, "text": "So the output will be like −" }, { "code": null, "e": 1453, "s": 1340, "text": "Input: 3\nOutput:\n 1 2 4\n 3 5 7\n 6 8 9\nInput: 4\nOutput:\n 1 2 4 7\n 3 5 8 11\n 6 9 12 14\n 10 13 15 16" }, { "code": null, "e": 1637, "s": 1453, "text": "The problem suggests we have to give a number n and generate a matrix of n x n and then we have to traverse the matrix in a diagonal pattern and store the values in a separate matrix." }, { "code": null, "e": 1701, "s": 1637, "text": "But this will increase the complexity of our code, so we will −" }, { "code": null, "e": 1777, "s": 1701, "text": "Create a matrix of size N X N which will store the pattern before printing." }, { "code": null, "e": 1853, "s": 1777, "text": "Create a matrix of size N X N which will store the pattern before printing." }, { "code": null, "e": 2018, "s": 1853, "text": "Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and the column index decreases by 1 as you move down the diagonal." }, { "code": null, "e": 2183, "s": 2018, "text": "Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and the column index decreases by 1 as you move down the diagonal." }, { "code": null, "e": 2398, "s": 2183, "text": "Once the upper triangle is completed then store the elements of the lower triangle in a similar way as the upper triangle i.e. row index increases by 1 and column index decreases by 1 as you move down the diagonal." }, { "code": null, "e": 2613, "s": 2398, "text": "Once the upper triangle is completed then store the elements of the lower triangle in a similar way as the upper triangle i.e. row index increases by 1 and column index decreases by 1 as you move down the diagonal." }, { "code": null, "e": 3204, "s": 2613, "text": "int printdiagonal(int n)\nSTART\nSTEP 1: DECLARE int mat[n][n], i, j, k, d=1, m\nSTEP 2: LOOP FOR i = 0 AND i < n AND i++\n ASSIGN j AS i AND k AS 0\n LOOP FOR j = I AND j >= 0 AND j--\n ASSIGN mat[k][j] AS d\n INCREMENT d AND k BY 1\n END LOOP\nEND LOOP\nSTEP 3: LOOP FOR k = 1 AND k < n AND k++\n ASSIGN i AND m EQUALS TO k\n LOOP FOR j = n-1 AND j >= m AND j--\n ASSIGN mat[i][j] AS d;\n INCREMENT d AND i WITH 1\n END FOR\nEND FOR\nSTEP 4: LOOP FOR i = 0 AND i < n AND i++\n LOOP FOR j = 0 AND j < n AND j++\n PRINT mat[i][j]\n END FOR\n PRINT NEWLINE\nEND FOR\nSTOP" }, { "code": null, "e": 3803, "s": 3204, "text": "#include <stdio.h>\nint printdiagonal(int n){\n int mat[n][n], i, j, k, d=1, m;\n for ( i = 0; i < n; i++){\n j = i;\n k = 0;\n for ( j = i; j >= 0; j--){\n mat[k][j] = d;\n d++;\n k++;\n }\n }\n for ( k = 1; k < n; k++){\n i = m = k;\n for ( j = n-1; j >= m; j--){\n mat[i][j] = d;\n d++;\n i++;\n }\n }\n for ( i = 0; i < n; i++){\n for(j = 0; j < n; j++){\n printf(\"%d \", mat[i][j] );\n }\n printf(\"\\n\");\n }\n}\nint main(int argc, char const *argv[]){\n int n = 3;\n printdiagonal(n);\n return 0;\n}" }, { "code": null, "e": 3876, "s": 3803, "text": "If we run the above program then it will generate the following output −" }, { "code": null, "e": 3894, "s": 3876, "text": "1 2 4\n3 5 7\n6 8 9" } ]
strings.ToValidUTF8() Function in Golang With Examples
17 May, 2020 strings.ToValidUTF8() Function in Golang is used to returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty. Syntax: func ToValidUTF8(str, rep string) string Here, str is string which may contain invalid UTF-8 and rep is the replacement string. Return Value: It returns the replaced string. Example 1: // Golang program to show the usage// of strings.ToValidUTF8() Functionpackage main // importing fmt and stringsimport ( "fmt" "strings") // calling main methodfunc main() { // There is no invalid UTF-8 character // present, so the same string returned fmt.Print(strings.ToValidUTF8("This is GeeksForGeeks", " "))} Output: This is GeeksForGeeks Example 2: // Golang program to show the usage// of strings.ToValidUTF8() Functionpackage main // importing fmt and stringsimport ( "fmt" "strings") // calling main methodfunc main() { // Invalid UTF-8 '\xc5' replaced by 'For' fmt.Print(strings.ToValidUTF8("Geeks\xc5Geeks", "For"))} Output: GeeksForGeeks Golang-String Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? Constants- Go Language Time Durations in Golang Loops in Go Language How to iterate over an Array using for loop in Golang? Structures in Golang Strings in Golang Go Variables time.Parse() Function in Golang With Examples Class and Object in Golang
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2020" }, { "code": null, "e": 213, "s": 28, "text": "strings.ToValidUTF8() Function in Golang is used to returns a copy of the string s with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty." }, { "code": null, "e": 221, "s": 213, "text": "Syntax:" }, { "code": null, "e": 263, "s": 221, "text": "func ToValidUTF8(str, rep string) string\n" }, { "code": null, "e": 350, "s": 263, "text": "Here, str is string which may contain invalid UTF-8 and rep is the replacement string." }, { "code": null, "e": 396, "s": 350, "text": "Return Value: It returns the replaced string." }, { "code": null, "e": 407, "s": 396, "text": "Example 1:" }, { "code": "// Golang program to show the usage// of strings.ToValidUTF8() Functionpackage main // importing fmt and stringsimport ( \"fmt\" \"strings\") // calling main methodfunc main() { // There is no invalid UTF-8 character // present, so the same string returned fmt.Print(strings.ToValidUTF8(\"This is GeeksForGeeks\", \" \"))}", "e": 741, "s": 407, "text": null }, { "code": null, "e": 749, "s": 741, "text": "Output:" }, { "code": null, "e": 772, "s": 749, "text": "This is GeeksForGeeks\n" }, { "code": null, "e": 783, "s": 772, "text": "Example 2:" }, { "code": "// Golang program to show the usage// of strings.ToValidUTF8() Functionpackage main // importing fmt and stringsimport ( \"fmt\" \"strings\") // calling main methodfunc main() { // Invalid UTF-8 '\\xc5' replaced by 'For' fmt.Print(strings.ToValidUTF8(\"Geeks\\xc5Geeks\", \"For\"))}", "e": 1072, "s": 783, "text": null }, { "code": null, "e": 1080, "s": 1072, "text": "Output:" }, { "code": null, "e": 1095, "s": 1080, "text": "GeeksForGeeks\n" }, { "code": null, "e": 1109, "s": 1095, "text": "Golang-String" }, { "code": null, "e": 1116, "s": 1109, "text": "Picked" }, { "code": null, "e": 1128, "s": 1116, "text": "Go Language" }, { "code": null, "e": 1226, "s": 1128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1255, "s": 1226, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 1278, "s": 1255, "text": "Constants- Go Language" }, { "code": null, "e": 1303, "s": 1278, "text": "Time Durations in Golang" }, { "code": null, "e": 1324, "s": 1303, "text": "Loops in Go Language" }, { "code": null, "e": 1379, "s": 1324, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 1400, "s": 1379, "text": "Structures in Golang" }, { "code": null, "e": 1418, "s": 1400, "text": "Strings in Golang" }, { "code": null, "e": 1431, "s": 1418, "text": "Go Variables" }, { "code": null, "e": 1477, "s": 1431, "text": "time.Parse() Function in Golang With Examples" } ]
Reject Vs Throw Promises in JavaScript
17 Jan, 2022 This article covers the use of reject and throw premises in Javascript and explains it’s differences.reject(): It is an inbuilt function in Javascript that returns a Promise object which has been rejected for a particular given reason. Syntax: Promise.reject(reason) Examples: The reason can be a simple string message or you can even pass an Error object. Program 1: Passing a string message as the reason. javascript <script>const p = new Promise( ( resolve, reject ) => { reject( 'promise failed!' ); });p.catch(err => { console.log( err ); });</script> Output: promise failed! Program 2: Passing an instanceOf Error as reason. javascript <script>const p = new Promise( ( resolve, reject ) => { reject( new Error( 'promise failed!' ) ); });p.catch( err => { console.log( err ); });</script> Output: As you can see when we are passing an Error object we get the entire Error tree. So it is upto the user which one the user prefers. Error: promise failed! at :4:9 at new Promise () at :2:11 at render (tryit.php:202) at tryit.php:170 at dispatch (jquery.js:4435) at r.handle (jquery.js:4121) throw: It is used in JavaScript to create and throw user defined exceptions. Using JavaScript throw statement, you can completely control program flow and generate the user define error messages. If we use throw instead of reject() in the above two examples the results will be exactly same (you can try it yourself just by replacing reject with throw).Examples: However throw can be used in any Javascript try-catch block and not only with promises. Program 1: Using throw in a promise. javascript <script>const p = new Promise( ( resolve, reject ) => { throw( 'promise failed!' ); });p.catch(err => { console.log( err ); });</script> Output: promise failed! Program 2: Using throw without a promise. javascript <script>var a = 20;try{ if( a < 25 ) throw ( 'Less than 25' ); console.log( 'Okay!' );}catch(err){ console.log( err );}</script> Output: Now as we have understood the basic working of both reject and throw, let us talk about the differences between them: Less than 25 Comparison between Promise- reject and throw:1. If there is an asynchronous callback function inside the Promise then we cannot use throw from inside the callback function as it will not be recognised by catch() and we will be getting an error in the output. Program 1: javascript <script>const p = new Promise( ( resolve, reject ) => { // Asynchronous function called within the Promise. setTimeout( () => { throw( 'promise failed!' ); }, 1000); }); // The catch block will not be able to recognize the // error thrown. It will become an uncaught exception. p.catch( ( err )=> { console.log( err ); });</script> Output: As you can see the error message (“promise failed!”) has been printed in the output but it wasn’t printed by the catch() function of our promise. It becomes an uncaught exception. /home/akarshan/Desktop/Projects/Personal/gfg/app.js:3 throw( 'promise failed!' ); ^ promise failed! (Use `node --trace-uncaught ...` to show where the exception was thrown) Program 2: To resolve the above situation we can make use of reject() method. javascript <script>const p = new Promise( ( resolve, reject ) => { // Asynchronous function called within the Promise. setTimeout( () => { reject( 'promise failed!' ); }, 1000); }); // The catch block will be able to recognize // the rejected statement. p.catch( (err) => { console.log( err ); });</script> Output: Here the catch block is able to recognise reject() and print the corresponding message. promise failed! 2. This is a very basic difference. If throw is encountered anywhere inside a function the exception is thrown immediately and the control flow is terminated.In other words after throwing the exception control comes out of the function inside which the exception was thrown. Program 1: javascript <script>const p = new Promise( ( resolve, reject ) => { throw( 'promise failed!' ); console.log("Here"); }); p.catch( err => { console.log( err )});</script> Output: From this example it is clear that the statement console.log(“Here”) is not getting executed. 'promise failed!' Program 2: To resolve above situation we use reject() instead of throw the statements after the reject statement inside the function will get executed before the control goes to the catch block. javascript <script>const p = new Promise( ( resolve, reject ) => { reject( 'promise failed!' ); console.log( "Here" ); }); p.catch( err => { console.log( err )});</script> Output: Here promise failed! 3. The reject can only be used with a Javascript promise but throw unlike reject can be used to create and throw user-defined exceptions in any try-catch block and not only the ones with promises. If you use Promise.reject() in a try-catch block which is not associated with a promise, UnhandledPromiseRejectionWarning error will pop up. Program 1: javascript <script>var a=20; try{ if( a < 25 ) Promise.reject ( 'Less than 25' ); console.log( 'Okay!' );}catch(err){ console.log( "inside catch" ); console.log( err );}</script> Output: Here, UnhandledPromiseRejectionWarning error comes as Promise.reject() cannot find a catch block associated with a Promise object. Okay! Program 2: The catch block in the above code is not associated with any Promise object and so it is not executed. This is clear from the output as the message “inside catch” is not getting printed. But if we use throw this error will not occur. javascript <script>var a=20; try{ if( a < 25 ) throw ( 'Less than 25' ); console.log( 'Okay!' ); }catch(err){ console.log( "inside catch" ); console.log( err );}</script> Output: inside catch Less than 25 kashishsoda saurabh1990aror JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Jan, 2022" }, { "code": null, "e": 290, "s": 53, "text": "This article covers the use of reject and throw premises in Javascript and explains it’s differences.reject(): It is an inbuilt function in Javascript that returns a Promise object which has been rejected for a particular given reason. " }, { "code": null, "e": 300, "s": 290, "text": "Syntax: " }, { "code": null, "e": 323, "s": 300, "text": "Promise.reject(reason)" }, { "code": null, "e": 415, "s": 323, "text": "Examples: The reason can be a simple string message or you can even pass an Error object. " }, { "code": null, "e": 466, "s": 415, "text": "Program 1: Passing a string message as the reason." }, { "code": null, "e": 477, "s": 466, "text": "javascript" }, { "code": "<script>const p = new Promise( ( resolve, reject ) => { reject( 'promise failed!' ); });p.catch(err => { console.log( err ); });</script>", "e": 622, "s": 477, "text": null }, { "code": null, "e": 632, "s": 622, "text": "Output: " }, { "code": null, "e": 648, "s": 632, "text": "promise failed!" }, { "code": null, "e": 698, "s": 648, "text": "Program 2: Passing an instanceOf Error as reason." }, { "code": null, "e": 709, "s": 698, "text": "javascript" }, { "code": "<script>const p = new Promise( ( resolve, reject ) => { reject( new Error( 'promise failed!' ) ); });p.catch( err => { console.log( err ); });</script>", "e": 868, "s": 709, "text": null }, { "code": null, "e": 1008, "s": 868, "text": "Output: As you can see when we are passing an Error object we get the entire Error tree. So it is upto the user which one the user prefers." }, { "code": null, "e": 1195, "s": 1008, "text": "Error: promise failed!\n at :4:9\n at new Promise ()\n at :2:11\n at render (tryit.php:202)\n at tryit.php:170\n at dispatch (jquery.js:4435)\n at r.handle (jquery.js:4121)" }, { "code": null, "e": 1647, "s": 1195, "text": "throw: It is used in JavaScript to create and throw user defined exceptions. Using JavaScript throw statement, you can completely control program flow and generate the user define error messages. If we use throw instead of reject() in the above two examples the results will be exactly same (you can try it yourself just by replacing reject with throw).Examples: However throw can be used in any Javascript try-catch block and not only with promises. " }, { "code": null, "e": 1684, "s": 1647, "text": "Program 1: Using throw in a promise." }, { "code": null, "e": 1695, "s": 1684, "text": "javascript" }, { "code": "<script>const p = new Promise( ( resolve, reject ) => { throw( 'promise failed!' ); });p.catch(err => { console.log( err ); });</script>", "e": 1839, "s": 1695, "text": null }, { "code": null, "e": 1847, "s": 1839, "text": "Output:" }, { "code": null, "e": 1863, "s": 1847, "text": "promise failed!" }, { "code": null, "e": 1905, "s": 1863, "text": "Program 2: Using throw without a promise." }, { "code": null, "e": 1916, "s": 1905, "text": "javascript" }, { "code": "<script>var a = 20;try{ if( a < 25 ) throw ( 'Less than 25' ); console.log( 'Okay!' );}catch(err){ console.log( err );}</script>", "e": 2053, "s": 1916, "text": null }, { "code": null, "e": 2179, "s": 2053, "text": "Output: Now as we have understood the basic working of both reject and throw, let us talk about the differences between them:" }, { "code": null, "e": 2192, "s": 2179, "text": "Less than 25" }, { "code": null, "e": 2453, "s": 2192, "text": "Comparison between Promise- reject and throw:1. If there is an asynchronous callback function inside the Promise then we cannot use throw from inside the callback function as it will not be recognised by catch() and we will be getting an error in the output. " }, { "code": null, "e": 2464, "s": 2453, "text": "Program 1:" }, { "code": null, "e": 2475, "s": 2464, "text": "javascript" }, { "code": "<script>const p = new Promise( ( resolve, reject ) => { // Asynchronous function called within the Promise. setTimeout( () => { throw( 'promise failed!' ); }, 1000); }); // The catch block will not be able to recognize the // error thrown. It will become an uncaught exception. p.catch( ( err )=> { console.log( err ); });</script>", "e": 2844, "s": 2475, "text": null }, { "code": null, "e": 3032, "s": 2844, "text": "Output: As you can see the error message (“promise failed!”) has been printed in the output but it wasn’t printed by the catch() function of our promise. It becomes an uncaught exception." }, { "code": null, "e": 3217, "s": 3032, "text": "/home/akarshan/Desktop/Projects/Personal/gfg/app.js:3\n throw( 'promise failed!' );\n ^\npromise failed!\n(Use `node --trace-uncaught ...` to show where the exception was thrown)" }, { "code": null, "e": 3295, "s": 3217, "text": "Program 2: To resolve the above situation we can make use of reject() method." }, { "code": null, "e": 3306, "s": 3295, "text": "javascript" }, { "code": "<script>const p = new Promise( ( resolve, reject ) => { // Asynchronous function called within the Promise. setTimeout( () => { reject( 'promise failed!' ); }, 1000); }); // The catch block will be able to recognize // the rejected statement. p.catch( (err) => { console.log( err ); });</script>", "e": 3635, "s": 3306, "text": null }, { "code": null, "e": 3731, "s": 3635, "text": "Output: Here the catch block is able to recognise reject() and print the corresponding message." }, { "code": null, "e": 3747, "s": 3731, "text": "promise failed!" }, { "code": null, "e": 4024, "s": 3747, "text": "2. This is a very basic difference. If throw is encountered anywhere inside a function the exception is thrown immediately and the control flow is terminated.In other words after throwing the exception control comes out of the function inside which the exception was thrown. " }, { "code": null, "e": 4035, "s": 4024, "text": "Program 1:" }, { "code": null, "e": 4046, "s": 4035, "text": "javascript" }, { "code": "<script>const p = new Promise( ( resolve, reject ) => { throw( 'promise failed!' ); console.log(\"Here\"); }); p.catch( err => { console.log( err )});</script>", "e": 4226, "s": 4046, "text": null }, { "code": null, "e": 4330, "s": 4226, "text": "Output: From this example it is clear that the statement console.log(“Here”) is not getting executed. " }, { "code": null, "e": 4348, "s": 4330, "text": "'promise failed!'" }, { "code": null, "e": 4545, "s": 4348, "text": "Program 2: To resolve above situation we use reject() instead of throw the statements after the reject statement inside the function will get executed before the control goes to the catch block. " }, { "code": null, "e": 4556, "s": 4545, "text": "javascript" }, { "code": "<script>const p = new Promise( ( resolve, reject ) => { reject( 'promise failed!' ); console.log( \"Here\" ); }); p.catch( err => { console.log( err )});</script>", "e": 4739, "s": 4556, "text": null }, { "code": null, "e": 4747, "s": 4739, "text": "Output:" }, { "code": null, "e": 4768, "s": 4747, "text": "Here\npromise failed!" }, { "code": null, "e": 5108, "s": 4768, "text": "3. The reject can only be used with a Javascript promise but throw unlike reject can be used to create and throw user-defined exceptions in any try-catch block and not only the ones with promises. If you use Promise.reject() in a try-catch block which is not associated with a promise, UnhandledPromiseRejectionWarning error will pop up. " }, { "code": null, "e": 5119, "s": 5108, "text": "Program 1:" }, { "code": null, "e": 5130, "s": 5119, "text": "javascript" }, { "code": "<script>var a=20; try{ if( a < 25 ) Promise.reject ( 'Less than 25' ); console.log( 'Okay!' );}catch(err){ console.log( \"inside catch\" ); console.log( err );}</script>", "e": 5306, "s": 5130, "text": null }, { "code": null, "e": 5445, "s": 5306, "text": "Output: Here, UnhandledPromiseRejectionWarning error comes as Promise.reject() cannot find a catch block associated with a Promise object." }, { "code": null, "e": 5451, "s": 5445, "text": "Okay!" }, { "code": null, "e": 5696, "s": 5451, "text": "Program 2: The catch block in the above code is not associated with any Promise object and so it is not executed. This is clear from the output as the message “inside catch” is not getting printed. But if we use throw this error will not occur." }, { "code": null, "e": 5707, "s": 5696, "text": "javascript" }, { "code": "<script>var a=20; try{ if( a < 25 ) throw ( 'Less than 25' ); console.log( 'Okay!' ); }catch(err){ console.log( \"inside catch\" ); console.log( err );}</script>", "e": 5872, "s": 5707, "text": null }, { "code": null, "e": 5880, "s": 5872, "text": "Output:" }, { "code": null, "e": 5906, "s": 5880, "text": "inside catch\nLess than 25" }, { "code": null, "e": 5918, "s": 5906, "text": "kashishsoda" }, { "code": null, "e": 5934, "s": 5918, "text": "saurabh1990aror" }, { "code": null, "e": 5950, "s": 5934, "text": "JavaScript-Misc" }, { "code": null, "e": 5957, "s": 5950, "text": "Picked" }, { "code": null, "e": 5968, "s": 5957, "text": "JavaScript" }, { "code": null, "e": 5985, "s": 5968, "text": "Web Technologies" }, { "code": null, "e": 6012, "s": 5985, "text": "Web technologies Questions" }, { "code": null, "e": 6110, "s": 6012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6171, "s": 6110, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6243, "s": 6171, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6283, "s": 6243, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6324, "s": 6283, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6376, "s": 6324, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 6409, "s": 6376, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6471, "s": 6409, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6532, "s": 6471, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6582, "s": 6532, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Round Robin Scheduling with different arrival times
27 May, 2022 Prerequisite: Round Robin Scheduling with arrival time as 0 A round-robin scheduling algorithm is used to schedule the process fairly for each job a time slot or quantum and the interrupting the job if it is not completed by then the job come after the other job which is arrived in the quantum time that makes these scheduling fairly. Note: Round-robin is cyclic in nature, so starvation doesn’t occur Round-robin is a variant of first come, first served scheduling No priority, special importance is given to any process or task RR scheduling is also known as Time slicing scheduling Advantages: Each process is served by CPU for a fixed time, so priority is the same for each one Starvation does not occur because of its cyclic nature. Disadvantages: Throughput depends on quantum time. If we want to give some process priority, we cannot. Quantum time is 2 this means each process is only executing for 2 units of time at a time.How to compute these process requests:- Take the process which occurs first and start executing the process(for quantum time only).Check if any other process request has arrived. If a process request arrives during the quantum time in which another process is executing, then add the new process to the Ready queueAfter the quantum time has passed, check for any processes in the Ready queue. If the ready queue is empty then continue the current process. If the queue not empty and the current process is not complete, then add the current process to the end of the ready queue.Take the first process from the Ready queue and start executing it (same rules)Repeat all steps above from 2-4If the process is complete and the ready queue is empty then the task is complete Take the process which occurs first and start executing the process(for quantum time only). Check if any other process request has arrived. If a process request arrives during the quantum time in which another process is executing, then add the new process to the Ready queue After the quantum time has passed, check for any processes in the Ready queue. If the ready queue is empty then continue the current process. If the queue not empty and the current process is not complete, then add the current process to the end of the ready queue. Take the first process from the Ready queue and start executing it (same rules) Repeat all steps above from 2-4 If the process is complete and the ready queue is empty then the task is complete After all these we get the three times which are: Completion Time: the time taken for a process to complete.Turn Around Time: total time the process exists in the system. (completion time – arrival time).Waiting Time: total time waiting for their complete execution. (turn around time – burst time ). Completion Time: the time taken for a process to complete. Turn Around Time: total time the process exists in the system. (completion time – arrival time). Waiting Time: total time waiting for their complete execution. (turn around time – burst time ). How to implement in a programming language 1. Declare arrival[], burst[], wait[], turn[] arrays and initialize them. Also declare a timer variable and initialize it to zero. To sustain the original burst array create another array (temp_burst[]) and copy all the values of burst array in it. 2. To keep a check we create another array of bool type which keeps the record of whether a process is completed or not. we also need to maintain a queue array which contains the process indices (initially the array is filled with 0). 3. Now we increment the timer variable until the first process arrives and when it does, we add the process index to the queue array 4. Now we execute the first process until the time quanta and during that time quanta, we check whether any other process has arrived or not and if it has then we add the index in the queue (by calling the fxn. queueUpdation()). 5. Now, after doing the above steps if a process has finished, we store its exit time and execute the next process in the queue array. Else, we move the currently executed process at the end of the queue (by calling another fxn. queueMaintainence()) when the time slice expires. 6. The above steps are then repeated until all the processes have been completely executed. If a scenario arises where there are some processes left but they have not arrived yet, then we shall wait and the CPU will remain idle during this interval. Below is the implementation of the above approach: (For the sake of simplicity, we assume that the arrival times are entered in a sorted way) C++ C++ C# Java Javascript //C++ Program for implementing//Round Robin Algorithm//code by sparsh_cbs#include <iostream> using namespace std; void queueUpdation(int queue[],int timer,int arrival[],int n, int maxProccessIndex){ int zeroIndex; for(int i = 0; i < n; i++){ if(queue[i] == 0){ zeroIndex = i; break; } } queue[zeroIndex] = maxProccessIndex + 1;} void queueMaintainence(int queue[], int n){ for(int i = 0; (i < n-1) && (queue[i+1] != 0) ; i++){ int temp = queue[i]; queue[i] = queue[i+1]; queue[i+1] = temp; }} void checkNewArrival(int timer, int arrival[], int n, int maxProccessIndex,int queue[]){ if(timer <= arrival[n-1]){ bool newArrival = false; for(int j = (maxProccessIndex+1); j < n; j++){ if(arrival[j] <= timer){ if(maxProccessIndex < j){ maxProccessIndex = j; newArrival = true; } } } //adds the incoming process to the ready queue //(if any arrives) if(newArrival) queueUpdation(queue,timer,arrival,n, maxProccessIndex); }} //Driver Codeint main(){ int n,tq, timer = 0, maxProccessIndex = 0; float avgWait = 0, avgTT = 0; cout << "\nEnter the time quanta : "; cin>>tq; cout << "\nEnter the number of processes : "; cin>>n; int arrival[n], burst[n], wait[n], turn[n], queue[n], temp_burst[n]; bool complete[n]; cout << "\nEnter the arrival time of the processes : "; for(int i = 0; i < n; i++) cin>>arrival[i]; cout << "\nEnter the burst time of the processes : "; for(int i = 0; i < n; i++){ cin>>burst[i]; temp_burst[i] = burst[i]; } for(int i = 0; i < n; i++){ //Initializing the queue and complete array complete[i] = false; queue[i] = 0; } while(timer < arrival[0]) //Incrementing Timer until the first process arrives timer++; queue[0] = 1; while(true){ bool flag = true; for(int i = 0; i < n; i++){ if(temp_burst[i] != 0){ flag = false; break; } } if(flag) break; for(int i = 0; (i < n) && (queue[i] != 0); i++){ int ctr = 0; while((ctr < tq) && (temp_burst[queue[0]-1] > 0)){ temp_burst[queue[0]-1] -= 1; timer += 1; ctr++; //Checking and Updating the ready queue until all the processes arrive checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //If a process is completed then store its exit time //and mark it as completed if((temp_burst[queue[0]-1] == 0) && (complete[queue[0]-1] == false)){ //turn array currently stores the completion time turn[queue[0]-1] = timer; complete[queue[0]-1] = true; } //checks whether or not CPU is idle bool idle = true; if(queue[n-1] == 0){ for(int i = 0; i < n && queue[i] != 0; i++){ if(complete[queue[i]-1] == false){ idle = false; } } } else idle = false; if(idle){ timer++; checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //Maintaining the entries of processes //after each premption in the ready Queue queueMaintainence(queue,n); } } for(int i = 0; i < n; i++){ turn[i] = turn[i] - arrival[i]; wait[i] = turn[i] - burst[i]; } cout << "\nProgram No.\tArrival Time\tBurst Time\tWait Time\tTurnAround Time" << endl; for(int i = 0; i < n; i++){ cout<<i+1<<"\t\t"<<arrival[i]<<"\t\t" <<burst[i]<<"\t\t"<<wait[i]<<"\t\t"<<turn[i]<<endl; } for(int i =0; i< n; i++){ avgWait += wait[i]; avgTT += turn[i]; } cout<<"\nAverage wait time : "<<(avgWait/n) <<"\nAverage Turn Around Time : "<<(avgTT/n); return 0; } // C# program to implement Round Robin// Scheduling with different arrival timeusing System; class GFG { public static void roundRobin(String[] p, int[] a, int[] b, int n) { // result of average times int res = 0; int resc = 0; // for sequence storage String seq = ""; // copy the burst array and arrival array // for not effecting the actual array int[] res_b = new int[b.Length]; int[] res_a = new int[a.Length]; for (int i = 0; i < res_b.Length; i++) { res_b[i] = b[i]; res_a[i] = a[i]; } // critical time of system int t = 0; // for store the waiting time int[] w = new int[p.Length]; // for store the Completion time int[] comp = new int[p.Length]; while (true) { Boolean flag = true; for (int i = 0; i < p.Length; i++) { // these condition for if // arrival is not on zero // check that if there come before qtime if (res_a[i] <= t) { if (res_a[i] <= n) { if (res_b[i] > 0) { flag = false; if (res_b[i] > n) { // make decrease the b time t = t + n; res_b[i] = res_b[i] - n; res_a[i] = res_a[i] + n; seq += "->" + p[i]; } else { // for last time t = t + res_b[i]; // store comp time comp[i] = t - a[i]; // store wait time w[i] = t - b[i] - a[i]; res_b[i] = 0; // add sequence seq += "->" + p[i]; } } } else if (res_a[i] > n) { // is any have less arrival time // the coming process then execute // them for (int j = 0; j < p.Length; j++) { // compare if (res_a[j] < res_a[i]) { if (res_b[j] > 0) { flag = false; if (res_b[j] > n) { t = t + n; res_b[j] = res_b[j] - n; res_a[j] = res_a[j] + n; seq += "->" + p[j]; } else { t = t + res_b[j]; comp[j] = t - a[j]; w[j] = t - b[j] - a[j]; res_b[j] = 0; seq += "->" + p[j]; } } } } // now the previous process // according to ith is process if (res_b[i] > 0) { flag = false; // Check for greaters if (res_b[i] > n) { t = t + n; res_b[i] = res_b[i] - n; res_a[i] = res_a[i] + n; seq += "->" + p[i]; } else { t = t + res_b[i]; comp[i] = t - a[i]; w[i] = t - b[i] - a[i]; res_b[i] = 0; seq += "->" + p[i]; } } } } // if no process is come on the critical else if (res_a[i] > t) { t++; i--; } } // for exit the while loop if (flag) { break; } } Console.WriteLine("name ctime wtime"); for (int i = 0; i < p.Length; i++) { Console.WriteLine(" " + p[i] + "\t" + comp[i] + "\t" + w[i]); res = res + w[i]; resc = resc + comp[i]; } Console.WriteLine("Average waiting time is " + (float)res / p.Length); Console.WriteLine("Average compilation time is " + (float)resc / p.Length); Console.WriteLine("Sequence is like that " + seq); } // Driver Code public static void Main(String[] args) { // name of the process String[] name = { "p1", "p2", "p3", "p4" }; // arrival for every process int[] arrivaltime = { 0, 1, 2, 3 }; // burst time for every process int[] bursttime = { 10, 4, 5, 3 }; // quantum time of each process int q = 3; // cal the function for output roundRobin(name, arrivaltime, bursttime, q); }} // This code is contributed by Rajput-Ji //JAVA Program for implementing//Round Robin Algorithm// code by Sparsh_cbsimport java.util.*; public class RoundRobin{ private static Scanner inp = new Scanner(System.in); //Driver Code public static void main(String[] args){ int n,tq, timer = 0, maxProccessIndex = 0; float avgWait = 0, avgTT = 0; System.out.print("\nEnter the time quanta : "); tq = inp.nextInt(); System.out.print("\nEnter the number of processes : "); n = inp.nextInt(); int arrival[] = new int[n]; int burst[] = new int[n]; int wait[] = new int[n]; int turn[] = new int[n]; int queue[] = new int[n]; int temp_burst[] = new int[n]; boolean complete[] = new boolean[n]; System.out.print("\nEnter the arrival time of the processes : "); for(int i = 0; i < n; i++) arrival[i] = inp.nextInt(); System.out.print("\nEnter the burst time of the processes : "); for(int i = 0; i < n; i++){ burst[i] = inp.nextInt(); temp_burst[i] = burst[i]; } for(int i = 0; i < n; i++){ //Initializing the queue and complete array complete[i] = false; queue[i] = 0; } while(timer < arrival[0]) //Incrementing Timer until the first process arrives timer++; queue[0] = 1; while(true){ boolean flag = true; for(int i = 0; i < n; i++){ if(temp_burst[i] != 0){ flag = false; break; } } if(flag) break; for(int i = 0; (i < n) && (queue[i] != 0); i++){ int ctr = 0; while((ctr < tq) && (temp_burst[queue[0]-1] > 0)){ temp_burst[queue[0]-1] -= 1; timer += 1; ctr++; //Updating the ready queue until all the processes arrive checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } if((temp_burst[queue[0]-1] == 0) && (complete[queue[0]-1] == false)){ turn[queue[0]-1] = timer; //turn currently stores exit times complete[queue[0]-1] = true; } //checks whether or not CPU is idle boolean idle = true; if(queue[n-1] == 0){ for(int k = 0; k < n && queue[k] != 0; k++){ if(complete[queue[k]-1] == false){ idle = false; } } } else idle = false; if(idle){ timer++; checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //Maintaining the entries of processes after each premption in the ready Queue queueMaintainence(queue,n); } } for(int i = 0; i < n; i++){ turn[i] = turn[i] - arrival[i]; wait[i] = turn[i] - burst[i]; } System.out.print("\nProgram No.\tArrival Time\tBurst Time\tWait Time\tTurnAround Time" + "\n"); for(int i = 0; i < n; i++){ System.out.print(i+1+"\t\t"+arrival[i]+"\t\t"+burst[i] +"\t\t"+wait[i]+"\t\t"+turn[i]+ "\n"); } for(int i =0; i< n; i++){ avgWait += wait[i]; avgTT += turn[i]; } System.out.print("\nAverage wait time : "+(avgWait/n) +"\nAverage Turn Around Time : "+(avgTT/n)); } public static void queueUpdation(int queue[],int timer,int arrival[],int n, int maxProccessIndex){ int zeroIndex = -1; for(int i = 0; i < n; i++){ if(queue[i] == 0){ zeroIndex = i; break; } } if(zeroIndex == -1) return; queue[zeroIndex] = maxProccessIndex + 1; } public static void checkNewArrival(int timer, int arrival[], int n, int maxProccessIndex,int queue[]){ if(timer <= arrival[n-1]){ boolean newArrival = false; for(int j = (maxProccessIndex+1); j < n; j++){ if(arrival[j] <= timer){ if(maxProccessIndex < j){ maxProccessIndex = j; newArrival = true; } } } if(newArrival) //adds the index of the arriving process(if any) queueUpdation(queue,timer,arrival,n, maxProccessIndex); } } public static void queueMaintainence(int queue[], int n){ for(int i = 0; (i < n-1) && (queue[i+1] != 0) ; i++){ int temp = queue[i]; queue[i] = queue[i+1]; queue[i+1] = temp; } }} <script> const queueUpdation = (queue, timer, arrival, n, maxProccessIndex) => { let zeroIndex; for (let i = 0; i < n; i++) { if (queue[i] == 0) { zeroIndex = i; break; } } queue[zeroIndex] = maxProccessIndex + 1; } const queueMaintainence = (queue, n) => { for (let i = 0; (i < n - 1) && (queue[i + 1] != 0); i++) { let temp = queue[i]; queue[i] = queue[i + 1]; queue[i + 1] = temp; } } const checkNewArrival = (timer, arrival, n, maxProccessIndex, queue) => { if (timer <= arrival[n - 1]) { let newArrival = false; for (let j = (maxProccessIndex + 1); j < n; j++) { if (arrival[j] <= timer) { if (maxProccessIndex < j) { maxProccessIndex = j; newArrival = true; } } } //adds the incoming process to the ready queue //(if any arrives) if (newArrival) queueUpdation(queue, timer, arrival, n, maxProccessIndex); } } //Driver Code let n = 4; let tq = 2; let timer = 0; let maxProccessIndex = 0; let avgWait = 0; let avgTT = 0; const wait = []; const turn = []; const queue = []; const temp_burst = []; const complete = []; const arrival = [0, 1, 2, 3]; const burst = [5, 4, 2, 1]; for (let i = 0; i < n; i++) { temp_burst[i] = burst[i]; } for (let i = 0; i < n; i++) { //Initializing the queue and complete array complete[i] = false; queue[i] = 0; } while (timer < arrival[0]) //Incrementing Timer until the first process arrives timer++; queue[0] = 1; while (true) { let flag = true; for (let i = 0; i < n; i++) { if (temp_burst[i] != 0) { flag = false; break; } } if (flag) break; for (let i = 0; (i < n) && (queue[i] != 0); i++) { let ctr = 0; while ((ctr < tq) && (temp_burst[queue[0] - 1] > 0)) { temp_burst[queue[0] - 1] -= 1; timer += 1; ctr++; // Checking and Updating the ready queue until all the processes arrive checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } // If a process is completed then store its exit time // and mark it as completed if ((temp_burst[queue[0] - 1] == 0) && (complete[queue[0] - 1] == false)) { //turn array currently stores the completion time turn[queue[0] - 1] = timer; complete[queue[0] - 1] = true; } // checks whether or not CPU is idle let idle = true; if (queue[n - 1] == 0) { for (let i = 0; i < n && queue[i] != 0; i++) { if (complete[queue[i] - 1] == false) { idle = false; } } } else idle = false; if (idle) { timer++; checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //Maintaining the entries of processes //after each premption in the ready Queue queueMaintainence(queue, n); } } for (let i = 0; i < n; i++) { turn[i] = turn[i] - arrival[i]; wait[i] = turn[i] - burst[i]; } console.log(`Time Quanta : ${tq}`); console.log(`Number of Processes : ${n}`); console.log(`Arrival Time of Processes : ${arrival}`); console.log(`Burst Time of Processes : ${burst}`); console.log("\nProgram No.\tArrival Time\tBurst Time\tWait Time\tTurnAround Time\n"); for (let i = 0; i < n; i++) { console.log(`${i + 1}\t\t\t ${arrival[i]}\t\t\t ${burst[i]}\t\t\t\t ${wait[i]} \t\t\t\t ${turn[i]} \n`); } for (let i = 0; i < n; i++) { avgWait += wait[i]; avgTT += turn[i]; } console.log(`\nAverage wait time : ${avgWait / n}`); console.log(`\nAverage Turn Around Time : ${avgTT / n}`); // This code is contributed by akashish_. </script> Output: Enter the time quanta : 2 Enter the number of processes : 4 Enter the arrival time of the processes : 0 1 2 3 Enter the burst time of the processes : 5 4 2 1 Program No. Arrival Time Burst Time Wait Time TurnAround Time 1 0 5 7 12 2 1 4 6 10 3 2 2 2 4 4 3 1 5 6 Average wait time : 5 Average Turn Around Time : 8 In case of any queries or a problem with the code, please write it in the comment section. Note: A slightly optimized version of the above-implemented code could be done by using Queue data structure as follows: C++ #include <bits/stdc++.h> using namespace std; struct Process{ int pid; int arrivalTime; int burstTime; int burstTimeRemaining; // the amount of CPU time remaining after each execution int completionTime; int turnaroundTime; int waitingTime; bool isComplete; bool inQueue;}; /* * At every time quantum or when a process has been executed before the time quantum, * check for any new arrivals and push them into the queue*/void checkForNewArrivals(Process processes[], const int n, const int currentTime, queue<int> &readyQueue){ for (int i = 0; i < n; i++) { Process p = processes[i]; // checking if any processes has arrived // if so, push them in the ready Queue. if (p.arrivalTime <= currentTime && !p.inQueue && !p.isComplete) { processes[i].inQueue = true; readyQueue.push(i); } }} /* * Context switching takes place at every time quantum * At every iteration, the burst time of the processes in the queue are handled using this method*/void updateQueue(Process processes[], const int n, const int quantum, queue<int> &readyQueue, int ¤tTime, int &programsExecuted){ int i = readyQueue.front(); readyQueue.pop(); // if the process is going to be finished executing, // ie, when it's remaining burst time is less than time quantum // mark it completed and increment the current time // and calculate its waiting time and turnaround time if (processes[i].burstTimeRemaining <= quantum) { processes[i].isComplete = true; currentTime += processes[i].burstTimeRemaining; processes[i].completionTime = currentTime; processes[i].waitingTime = processes[i].completionTime - processes[i].arrivalTime - processes[i].burstTime; processes[i].turnaroundTime = processes[i].waitingTime + processes[i].burstTime; if (processes[i].waitingTime < 0) processes[i].waitingTime = 0; processes[i].burstTimeRemaining = 0; // if all the processes are not yet inserted in the queue, // then check for new arrivals if (programsExecuted != n) { checkForNewArrivals(processes, n, currentTime, readyQueue); } } else { // the process is not done yet. But it's going to be pre-empted // since one quantum is used // but first subtract the time the process used so far processes[i].burstTimeRemaining -= quantum; currentTime += quantum; // if all the processes are not yet inserted in the queue, // then check for new arrivals if (programsExecuted != n) { checkForNewArrivals(processes, n, currentTime, readyQueue); } // insert the incomplete process back into the queue readyQueue.push(i); }} /* * Just a function that outputs the result in terms of their PID.*/void output(Process processes[], const int n){ double avgWaitingTime = 0; double avgTurntaroundTime = 0; // sort the processes array by processes.PID sort(processes, processes + n, [](const Process &p1, const Process &p2) { return p1.pid < p2.pid; }); for (int i = 0; i < n; i++) { cout << "Process " << processes[i].pid << ": Waiting Time: " << processes[i].waitingTime << " Turnaround Time: " << processes[i].turnaroundTime << endl; avgWaitingTime += processes[i].waitingTime; avgTurntaroundTime += processes[i].turnaroundTime; } cout << "Average Waiting Time: " << avgWaitingTime / n << endl; cout << "Average Turnaround Time: " << avgTurntaroundTime / n << endl;} /* * This function assumes that the processes are already sorted according to their arrival time */void roundRobin(Process processes[], int n, int quantum){ queue<int> readyQueue; readyQueue.push(0); // initially, pushing the first process which arrived first processes[0].inQueue = true; int currentTime = 0; // holds the current time after each process has been executed int programsExecuted = 0; // holds the number of programs executed so far while (!readyQueue.empty()) { updateQueue(processes, n, quantum, readyQueue, currentTime, programsExecuted); }} int main(){ int n, quantum; cout << "Enter the number of processes: "; cin >> n; cout << "Enter time quantum: "; cin >> quantum; Process processes[n + 1]; for (int i = 0; i < n; i++) { cout << "Enter arrival time and burst time of each process " << i + 1 << ": "; cin >> processes[i].arrivalTime; cin >> processes[i].burstTime; processes[i].burstTimeRemaining = processes[i].burstTime; processes[i].pid = i + 1; cout << endl; } // stl sort in terms of arrival time sort(processes, processes + n, [](const Process &p1, const Process &p2) { return p1.arrivalTime < p2.arrivalTime; }); roundRobin(processes, n, quantum); output(processes, n); return 0;} Enter the number of processes: 4 Enter time quantum: 2 Enter the arrival time and burst time of each process: 0 5 1 4 2 2 3 1 Process 1: Waiting Time: 7 Turnaround Time: 12 Process 2: Waiting Time: 6 Turnaround Time: 10 Process 3: Waiting Time: 2 Turnaround Time: 4 Process 4: Waiting Time: 5 Turnaround Time: 6 Average Waiting Time: 5 Average Turnaround Time: 8 Petia Davidova Rajput-Ji VikasTomar lohityakumarambashta jindalharsh999 kushalshah18 sparshsharma2510 simranarora5sos gabaa406 ahnafswapnil saurabh1990aror simmytarika5 kothavvsaakash akashish__ cpu-scheduling Operating Systems-CPU Scheduling Java Programs Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 May, 2022" }, { "code": null, "e": 114, "s": 54, "text": "Prerequisite: Round Robin Scheduling with arrival time as 0" }, { "code": null, "e": 390, "s": 114, "text": "A round-robin scheduling algorithm is used to schedule the process fairly for each job a time slot or quantum and the interrupting the job if it is not completed by then the job come after the other job which is arrived in the quantum time that makes these scheduling fairly." }, { "code": null, "e": 398, "s": 390, "text": "Note: " }, { "code": null, "e": 459, "s": 398, "text": "Round-robin is cyclic in nature, so starvation doesn’t occur" }, { "code": null, "e": 523, "s": 459, "text": "Round-robin is a variant of first come, first served scheduling" }, { "code": null, "e": 587, "s": 523, "text": "No priority, special importance is given to any process or task" }, { "code": null, "e": 642, "s": 587, "text": "RR scheduling is also known as Time slicing scheduling" }, { "code": null, "e": 656, "s": 642, "text": "Advantages: " }, { "code": null, "e": 741, "s": 656, "text": "Each process is served by CPU for a fixed time, so priority is the same for each one" }, { "code": null, "e": 797, "s": 741, "text": "Starvation does not occur because of its cyclic nature." }, { "code": null, "e": 814, "s": 797, "text": "Disadvantages: " }, { "code": null, "e": 850, "s": 814, "text": "Throughput depends on quantum time." }, { "code": null, "e": 903, "s": 850, "text": "If we want to give some process priority, we cannot." }, { "code": null, "e": 1035, "s": 903, "text": "Quantum time is 2 this means each process is only executing for 2 units of time at a time.How to compute these process requests:- " }, { "code": null, "e": 1766, "s": 1035, "text": "Take the process which occurs first and start executing the process(for quantum time only).Check if any other process request has arrived. If a process request arrives during the quantum time in which another process is executing, then add the new process to the Ready queueAfter the quantum time has passed, check for any processes in the Ready queue. If the ready queue is empty then continue the current process. If the queue not empty and the current process is not complete, then add the current process to the end of the ready queue.Take the first process from the Ready queue and start executing it (same rules)Repeat all steps above from 2-4If the process is complete and the ready queue is empty then the task is complete" }, { "code": null, "e": 1858, "s": 1766, "text": "Take the process which occurs first and start executing the process(for quantum time only)." }, { "code": null, "e": 2042, "s": 1858, "text": "Check if any other process request has arrived. If a process request arrives during the quantum time in which another process is executing, then add the new process to the Ready queue" }, { "code": null, "e": 2308, "s": 2042, "text": "After the quantum time has passed, check for any processes in the Ready queue. If the ready queue is empty then continue the current process. If the queue not empty and the current process is not complete, then add the current process to the end of the ready queue." }, { "code": null, "e": 2388, "s": 2308, "text": "Take the first process from the Ready queue and start executing it (same rules)" }, { "code": null, "e": 2420, "s": 2388, "text": "Repeat all steps above from 2-4" }, { "code": null, "e": 2502, "s": 2420, "text": "If the process is complete and the ready queue is empty then the task is complete" }, { "code": null, "e": 2554, "s": 2502, "text": "After all these we get the three times which are: " }, { "code": null, "e": 2805, "s": 2554, "text": "Completion Time: the time taken for a process to complete.Turn Around Time: total time the process exists in the system. (completion time – arrival time).Waiting Time: total time waiting for their complete execution. (turn around time – burst time )." }, { "code": null, "e": 2864, "s": 2805, "text": "Completion Time: the time taken for a process to complete." }, { "code": null, "e": 2961, "s": 2864, "text": "Turn Around Time: total time the process exists in the system. (completion time – arrival time)." }, { "code": null, "e": 3058, "s": 2961, "text": "Waiting Time: total time waiting for their complete execution. (turn around time – burst time )." }, { "code": null, "e": 3103, "s": 3058, "text": "How to implement in a programming language " }, { "code": null, "e": 4536, "s": 3103, "text": "1. Declare arrival[], burst[], wait[], turn[] arrays and initialize them. Also declare a timer\n variable and initialize it to zero. To sustain the original burst array create another \n array (temp_burst[]) and copy all the values of burst array in it.\n \n2. To keep a check we create another array of bool type which keeps the record of whether a\n process is completed or not. we also need to maintain a queue array which contains the process\n indices (initially the array is filled with 0).\n \n3. Now we increment the timer variable until the first process arrives and when it does, we add the\n process index to the queue array \n \n4. Now we execute the first process until the time quanta and during that time quanta, we check \n whether any other process has arrived or not and if it has then we add the index in the queue\n (by calling the fxn. queueUpdation()).\n \n5. Now, after doing the above steps if a process has finished, we store its exit time and \n execute the next process in the queue array. Else, we move the currently executed process at \n the end of the queue (by calling another fxn. queueMaintainence()) when the time slice expires.\n \n6. The above steps are then repeated until all the processes have been completely executed. If a\n scenario arises where there are some processes left but they have not arrived yet, then we\n shall wait and the CPU will remain idle during this interval." }, { "code": null, "e": 4588, "s": 4536, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 4683, "s": 4588, "text": "(For the sake of simplicity, we assume that the arrival times are entered in a sorted way) C++" }, { "code": null, "e": 4687, "s": 4683, "text": "C++" }, { "code": null, "e": 4690, "s": 4687, "text": "C#" }, { "code": null, "e": 4695, "s": 4690, "text": "Java" }, { "code": null, "e": 4706, "s": 4695, "text": "Javascript" }, { "code": "//C++ Program for implementing//Round Robin Algorithm//code by sparsh_cbs#include <iostream> using namespace std; void queueUpdation(int queue[],int timer,int arrival[],int n, int maxProccessIndex){ int zeroIndex; for(int i = 0; i < n; i++){ if(queue[i] == 0){ zeroIndex = i; break; } } queue[zeroIndex] = maxProccessIndex + 1;} void queueMaintainence(int queue[], int n){ for(int i = 0; (i < n-1) && (queue[i+1] != 0) ; i++){ int temp = queue[i]; queue[i] = queue[i+1]; queue[i+1] = temp; }} void checkNewArrival(int timer, int arrival[], int n, int maxProccessIndex,int queue[]){ if(timer <= arrival[n-1]){ bool newArrival = false; for(int j = (maxProccessIndex+1); j < n; j++){ if(arrival[j] <= timer){ if(maxProccessIndex < j){ maxProccessIndex = j; newArrival = true; } } } //adds the incoming process to the ready queue //(if any arrives) if(newArrival) queueUpdation(queue,timer,arrival,n, maxProccessIndex); }} //Driver Codeint main(){ int n,tq, timer = 0, maxProccessIndex = 0; float avgWait = 0, avgTT = 0; cout << \"\\nEnter the time quanta : \"; cin>>tq; cout << \"\\nEnter the number of processes : \"; cin>>n; int arrival[n], burst[n], wait[n], turn[n], queue[n], temp_burst[n]; bool complete[n]; cout << \"\\nEnter the arrival time of the processes : \"; for(int i = 0; i < n; i++) cin>>arrival[i]; cout << \"\\nEnter the burst time of the processes : \"; for(int i = 0; i < n; i++){ cin>>burst[i]; temp_burst[i] = burst[i]; } for(int i = 0; i < n; i++){ //Initializing the queue and complete array complete[i] = false; queue[i] = 0; } while(timer < arrival[0]) //Incrementing Timer until the first process arrives timer++; queue[0] = 1; while(true){ bool flag = true; for(int i = 0; i < n; i++){ if(temp_burst[i] != 0){ flag = false; break; } } if(flag) break; for(int i = 0; (i < n) && (queue[i] != 0); i++){ int ctr = 0; while((ctr < tq) && (temp_burst[queue[0]-1] > 0)){ temp_burst[queue[0]-1] -= 1; timer += 1; ctr++; //Checking and Updating the ready queue until all the processes arrive checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //If a process is completed then store its exit time //and mark it as completed if((temp_burst[queue[0]-1] == 0) && (complete[queue[0]-1] == false)){ //turn array currently stores the completion time turn[queue[0]-1] = timer; complete[queue[0]-1] = true; } //checks whether or not CPU is idle bool idle = true; if(queue[n-1] == 0){ for(int i = 0; i < n && queue[i] != 0; i++){ if(complete[queue[i]-1] == false){ idle = false; } } } else idle = false; if(idle){ timer++; checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //Maintaining the entries of processes //after each premption in the ready Queue queueMaintainence(queue,n); } } for(int i = 0; i < n; i++){ turn[i] = turn[i] - arrival[i]; wait[i] = turn[i] - burst[i]; } cout << \"\\nProgram No.\\tArrival Time\\tBurst Time\\tWait Time\\tTurnAround Time\" << endl; for(int i = 0; i < n; i++){ cout<<i+1<<\"\\t\\t\"<<arrival[i]<<\"\\t\\t\" <<burst[i]<<\"\\t\\t\"<<wait[i]<<\"\\t\\t\"<<turn[i]<<endl; } for(int i =0; i< n; i++){ avgWait += wait[i]; avgTT += turn[i]; } cout<<\"\\nAverage wait time : \"<<(avgWait/n) <<\"\\nAverage Turn Around Time : \"<<(avgTT/n); return 0; }", "e": 8871, "s": 4706, "text": null }, { "code": "// C# program to implement Round Robin// Scheduling with different arrival timeusing System; class GFG { public static void roundRobin(String[] p, int[] a, int[] b, int n) { // result of average times int res = 0; int resc = 0; // for sequence storage String seq = \"\"; // copy the burst array and arrival array // for not effecting the actual array int[] res_b = new int[b.Length]; int[] res_a = new int[a.Length]; for (int i = 0; i < res_b.Length; i++) { res_b[i] = b[i]; res_a[i] = a[i]; } // critical time of system int t = 0; // for store the waiting time int[] w = new int[p.Length]; // for store the Completion time int[] comp = new int[p.Length]; while (true) { Boolean flag = true; for (int i = 0; i < p.Length; i++) { // these condition for if // arrival is not on zero // check that if there come before qtime if (res_a[i] <= t) { if (res_a[i] <= n) { if (res_b[i] > 0) { flag = false; if (res_b[i] > n) { // make decrease the b time t = t + n; res_b[i] = res_b[i] - n; res_a[i] = res_a[i] + n; seq += \"->\" + p[i]; } else { // for last time t = t + res_b[i]; // store comp time comp[i] = t - a[i]; // store wait time w[i] = t - b[i] - a[i]; res_b[i] = 0; // add sequence seq += \"->\" + p[i]; } } } else if (res_a[i] > n) { // is any have less arrival time // the coming process then execute // them for (int j = 0; j < p.Length; j++) { // compare if (res_a[j] < res_a[i]) { if (res_b[j] > 0) { flag = false; if (res_b[j] > n) { t = t + n; res_b[j] = res_b[j] - n; res_a[j] = res_a[j] + n; seq += \"->\" + p[j]; } else { t = t + res_b[j]; comp[j] = t - a[j]; w[j] = t - b[j] - a[j]; res_b[j] = 0; seq += \"->\" + p[j]; } } } } // now the previous process // according to ith is process if (res_b[i] > 0) { flag = false; // Check for greaters if (res_b[i] > n) { t = t + n; res_b[i] = res_b[i] - n; res_a[i] = res_a[i] + n; seq += \"->\" + p[i]; } else { t = t + res_b[i]; comp[i] = t - a[i]; w[i] = t - b[i] - a[i]; res_b[i] = 0; seq += \"->\" + p[i]; } } } } // if no process is come on the critical else if (res_a[i] > t) { t++; i--; } } // for exit the while loop if (flag) { break; } } Console.WriteLine(\"name ctime wtime\"); for (int i = 0; i < p.Length; i++) { Console.WriteLine(\" \" + p[i] + \"\\t\" + comp[i] + \"\\t\" + w[i]); res = res + w[i]; resc = resc + comp[i]; } Console.WriteLine(\"Average waiting time is \" + (float)res / p.Length); Console.WriteLine(\"Average compilation time is \" + (float)resc / p.Length); Console.WriteLine(\"Sequence is like that \" + seq); } // Driver Code public static void Main(String[] args) { // name of the process String[] name = { \"p1\", \"p2\", \"p3\", \"p4\" }; // arrival for every process int[] arrivaltime = { 0, 1, 2, 3 }; // burst time for every process int[] bursttime = { 10, 4, 5, 3 }; // quantum time of each process int q = 3; // cal the function for output roundRobin(name, arrivaltime, bursttime, q); }} // This code is contributed by Rajput-Ji", "e": 14604, "s": 8871, "text": null }, { "code": "//JAVA Program for implementing//Round Robin Algorithm// code by Sparsh_cbsimport java.util.*; public class RoundRobin{ private static Scanner inp = new Scanner(System.in); //Driver Code public static void main(String[] args){ int n,tq, timer = 0, maxProccessIndex = 0; float avgWait = 0, avgTT = 0; System.out.print(\"\\nEnter the time quanta : \"); tq = inp.nextInt(); System.out.print(\"\\nEnter the number of processes : \"); n = inp.nextInt(); int arrival[] = new int[n]; int burst[] = new int[n]; int wait[] = new int[n]; int turn[] = new int[n]; int queue[] = new int[n]; int temp_burst[] = new int[n]; boolean complete[] = new boolean[n]; System.out.print(\"\\nEnter the arrival time of the processes : \"); for(int i = 0; i < n; i++) arrival[i] = inp.nextInt(); System.out.print(\"\\nEnter the burst time of the processes : \"); for(int i = 0; i < n; i++){ burst[i] = inp.nextInt(); temp_burst[i] = burst[i]; } for(int i = 0; i < n; i++){ //Initializing the queue and complete array complete[i] = false; queue[i] = 0; } while(timer < arrival[0]) //Incrementing Timer until the first process arrives timer++; queue[0] = 1; while(true){ boolean flag = true; for(int i = 0; i < n; i++){ if(temp_burst[i] != 0){ flag = false; break; } } if(flag) break; for(int i = 0; (i < n) && (queue[i] != 0); i++){ int ctr = 0; while((ctr < tq) && (temp_burst[queue[0]-1] > 0)){ temp_burst[queue[0]-1] -= 1; timer += 1; ctr++; //Updating the ready queue until all the processes arrive checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } if((temp_burst[queue[0]-1] == 0) && (complete[queue[0]-1] == false)){ turn[queue[0]-1] = timer; //turn currently stores exit times complete[queue[0]-1] = true; } //checks whether or not CPU is idle boolean idle = true; if(queue[n-1] == 0){ for(int k = 0; k < n && queue[k] != 0; k++){ if(complete[queue[k]-1] == false){ idle = false; } } } else idle = false; if(idle){ timer++; checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //Maintaining the entries of processes after each premption in the ready Queue queueMaintainence(queue,n); } } for(int i = 0; i < n; i++){ turn[i] = turn[i] - arrival[i]; wait[i] = turn[i] - burst[i]; } System.out.print(\"\\nProgram No.\\tArrival Time\\tBurst Time\\tWait Time\\tTurnAround Time\" + \"\\n\"); for(int i = 0; i < n; i++){ System.out.print(i+1+\"\\t\\t\"+arrival[i]+\"\\t\\t\"+burst[i] +\"\\t\\t\"+wait[i]+\"\\t\\t\"+turn[i]+ \"\\n\"); } for(int i =0; i< n; i++){ avgWait += wait[i]; avgTT += turn[i]; } System.out.print(\"\\nAverage wait time : \"+(avgWait/n) +\"\\nAverage Turn Around Time : \"+(avgTT/n)); } public static void queueUpdation(int queue[],int timer,int arrival[],int n, int maxProccessIndex){ int zeroIndex = -1; for(int i = 0; i < n; i++){ if(queue[i] == 0){ zeroIndex = i; break; } } if(zeroIndex == -1) return; queue[zeroIndex] = maxProccessIndex + 1; } public static void checkNewArrival(int timer, int arrival[], int n, int maxProccessIndex,int queue[]){ if(timer <= arrival[n-1]){ boolean newArrival = false; for(int j = (maxProccessIndex+1); j < n; j++){ if(arrival[j] <= timer){ if(maxProccessIndex < j){ maxProccessIndex = j; newArrival = true; } } } if(newArrival) //adds the index of the arriving process(if any) queueUpdation(queue,timer,arrival,n, maxProccessIndex); } } public static void queueMaintainence(int queue[], int n){ for(int i = 0; (i < n-1) && (queue[i+1] != 0) ; i++){ int temp = queue[i]; queue[i] = queue[i+1]; queue[i+1] = temp; } }}", "e": 19555, "s": 14604, "text": null }, { "code": "<script> const queueUpdation = (queue, timer, arrival, n, maxProccessIndex) => { let zeroIndex; for (let i = 0; i < n; i++) { if (queue[i] == 0) { zeroIndex = i; break; } } queue[zeroIndex] = maxProccessIndex + 1; } const queueMaintainence = (queue, n) => { for (let i = 0; (i < n - 1) && (queue[i + 1] != 0); i++) { let temp = queue[i]; queue[i] = queue[i + 1]; queue[i + 1] = temp; } } const checkNewArrival = (timer, arrival, n, maxProccessIndex, queue) => { if (timer <= arrival[n - 1]) { let newArrival = false; for (let j = (maxProccessIndex + 1); j < n; j++) { if (arrival[j] <= timer) { if (maxProccessIndex < j) { maxProccessIndex = j; newArrival = true; } } } //adds the incoming process to the ready queue //(if any arrives) if (newArrival) queueUpdation(queue, timer, arrival, n, maxProccessIndex); } } //Driver Code let n = 4; let tq = 2; let timer = 0; let maxProccessIndex = 0; let avgWait = 0; let avgTT = 0; const wait = []; const turn = []; const queue = []; const temp_burst = []; const complete = []; const arrival = [0, 1, 2, 3]; const burst = [5, 4, 2, 1]; for (let i = 0; i < n; i++) { temp_burst[i] = burst[i]; } for (let i = 0; i < n; i++) { //Initializing the queue and complete array complete[i] = false; queue[i] = 0; } while (timer < arrival[0]) //Incrementing Timer until the first process arrives timer++; queue[0] = 1; while (true) { let flag = true; for (let i = 0; i < n; i++) { if (temp_burst[i] != 0) { flag = false; break; } } if (flag) break; for (let i = 0; (i < n) && (queue[i] != 0); i++) { let ctr = 0; while ((ctr < tq) && (temp_burst[queue[0] - 1] > 0)) { temp_burst[queue[0] - 1] -= 1; timer += 1; ctr++; // Checking and Updating the ready queue until all the processes arrive checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } // If a process is completed then store its exit time // and mark it as completed if ((temp_burst[queue[0] - 1] == 0) && (complete[queue[0] - 1] == false)) { //turn array currently stores the completion time turn[queue[0] - 1] = timer; complete[queue[0] - 1] = true; } // checks whether or not CPU is idle let idle = true; if (queue[n - 1] == 0) { for (let i = 0; i < n && queue[i] != 0; i++) { if (complete[queue[i] - 1] == false) { idle = false; } } } else idle = false; if (idle) { timer++; checkNewArrival(timer, arrival, n, maxProccessIndex, queue); } //Maintaining the entries of processes //after each premption in the ready Queue queueMaintainence(queue, n); } } for (let i = 0; i < n; i++) { turn[i] = turn[i] - arrival[i]; wait[i] = turn[i] - burst[i]; } console.log(`Time Quanta : ${tq}`); console.log(`Number of Processes : ${n}`); console.log(`Arrival Time of Processes : ${arrival}`); console.log(`Burst Time of Processes : ${burst}`); console.log(\"\\nProgram No.\\tArrival Time\\tBurst Time\\tWait Time\\tTurnAround Time\\n\"); for (let i = 0; i < n; i++) { console.log(`${i + 1}\\t\\t\\t ${arrival[i]}\\t\\t\\t ${burst[i]}\\t\\t\\t\\t ${wait[i]} \\t\\t\\t\\t ${turn[i]} \\n`); } for (let i = 0; i < n; i++) { avgWait += wait[i]; avgTT += turn[i]; } console.log(`\\nAverage wait time : ${avgWait / n}`); console.log(`\\nAverage Turn Around Time : ${avgTT / n}`); // This code is contributed by akashish_. </script>", "e": 24313, "s": 19555, "text": null }, { "code": null, "e": 24321, "s": 24313, "text": "Output:" }, { "code": null, "e": 24881, "s": 24321, "text": "Enter the time quanta : 2\n\nEnter the number of processes : 4\n\nEnter the arrival time of the processes : 0 1 2 3\n\nEnter the burst time of the processes : 5 4 2 1\n\nProgram No. Arrival Time Burst Time Wait Time TurnAround Time\n1 0 5 7 12\n2 1 4 6 10\n3 2 2 2 4\n4 3 1 5 6\n\nAverage wait time : 5\nAverage Turn Around Time : 8" }, { "code": null, "e": 24972, "s": 24881, "text": "In case of any queries or a problem with the code, please write it in the comment section." }, { "code": null, "e": 25093, "s": 24972, "text": "Note: A slightly optimized version of the above-implemented code could be done by using Queue data structure as follows:" }, { "code": null, "e": 25097, "s": 25093, "text": "C++" }, { "code": "#include <bits/stdc++.h> using namespace std; struct Process{ int pid; int arrivalTime; int burstTime; int burstTimeRemaining; // the amount of CPU time remaining after each execution int completionTime; int turnaroundTime; int waitingTime; bool isComplete; bool inQueue;}; /* * At every time quantum or when a process has been executed before the time quantum, * check for any new arrivals and push them into the queue*/void checkForNewArrivals(Process processes[], const int n, const int currentTime, queue<int> &readyQueue){ for (int i = 0; i < n; i++) { Process p = processes[i]; // checking if any processes has arrived // if so, push them in the ready Queue. if (p.arrivalTime <= currentTime && !p.inQueue && !p.isComplete) { processes[i].inQueue = true; readyQueue.push(i); } }} /* * Context switching takes place at every time quantum * At every iteration, the burst time of the processes in the queue are handled using this method*/void updateQueue(Process processes[], const int n, const int quantum, queue<int> &readyQueue, int ¤tTime, int &programsExecuted){ int i = readyQueue.front(); readyQueue.pop(); // if the process is going to be finished executing, // ie, when it's remaining burst time is less than time quantum // mark it completed and increment the current time // and calculate its waiting time and turnaround time if (processes[i].burstTimeRemaining <= quantum) { processes[i].isComplete = true; currentTime += processes[i].burstTimeRemaining; processes[i].completionTime = currentTime; processes[i].waitingTime = processes[i].completionTime - processes[i].arrivalTime - processes[i].burstTime; processes[i].turnaroundTime = processes[i].waitingTime + processes[i].burstTime; if (processes[i].waitingTime < 0) processes[i].waitingTime = 0; processes[i].burstTimeRemaining = 0; // if all the processes are not yet inserted in the queue, // then check for new arrivals if (programsExecuted != n) { checkForNewArrivals(processes, n, currentTime, readyQueue); } } else { // the process is not done yet. But it's going to be pre-empted // since one quantum is used // but first subtract the time the process used so far processes[i].burstTimeRemaining -= quantum; currentTime += quantum; // if all the processes are not yet inserted in the queue, // then check for new arrivals if (programsExecuted != n) { checkForNewArrivals(processes, n, currentTime, readyQueue); } // insert the incomplete process back into the queue readyQueue.push(i); }} /* * Just a function that outputs the result in terms of their PID.*/void output(Process processes[], const int n){ double avgWaitingTime = 0; double avgTurntaroundTime = 0; // sort the processes array by processes.PID sort(processes, processes + n, [](const Process &p1, const Process &p2) { return p1.pid < p2.pid; }); for (int i = 0; i < n; i++) { cout << \"Process \" << processes[i].pid << \": Waiting Time: \" << processes[i].waitingTime << \" Turnaround Time: \" << processes[i].turnaroundTime << endl; avgWaitingTime += processes[i].waitingTime; avgTurntaroundTime += processes[i].turnaroundTime; } cout << \"Average Waiting Time: \" << avgWaitingTime / n << endl; cout << \"Average Turnaround Time: \" << avgTurntaroundTime / n << endl;} /* * This function assumes that the processes are already sorted according to their arrival time */void roundRobin(Process processes[], int n, int quantum){ queue<int> readyQueue; readyQueue.push(0); // initially, pushing the first process which arrived first processes[0].inQueue = true; int currentTime = 0; // holds the current time after each process has been executed int programsExecuted = 0; // holds the number of programs executed so far while (!readyQueue.empty()) { updateQueue(processes, n, quantum, readyQueue, currentTime, programsExecuted); }} int main(){ int n, quantum; cout << \"Enter the number of processes: \"; cin >> n; cout << \"Enter time quantum: \"; cin >> quantum; Process processes[n + 1]; for (int i = 0; i < n; i++) { cout << \"Enter arrival time and burst time of each process \" << i + 1 << \": \"; cin >> processes[i].arrivalTime; cin >> processes[i].burstTime; processes[i].burstTimeRemaining = processes[i].burstTime; processes[i].pid = i + 1; cout << endl; } // stl sort in terms of arrival time sort(processes, processes + n, [](const Process &p1, const Process &p2) { return p1.arrivalTime < p2.arrivalTime; }); roundRobin(processes, n, quantum); output(processes, n); return 0;}", "e": 30043, "s": 25097, "text": null }, { "code": null, "e": 30414, "s": 30046, "text": "Enter the number of processes: 4\n\nEnter time quantum: 2\n\nEnter the arrival time and burst time of each process: \n0 5\n1 4\n2 2\n3 1\n\nProcess 1: Waiting Time: 7 Turnaround Time: 12\nProcess 2: Waiting Time: 6 Turnaround Time: 10\nProcess 3: Waiting Time: 2 Turnaround Time: 4\nProcess 4: Waiting Time: 5 Turnaround Time: 6\n\nAverage Waiting Time: 5\nAverage Turnaround Time: 8" }, { "code": null, "e": 30429, "s": 30414, "text": "Petia Davidova" }, { "code": null, "e": 30439, "s": 30429, "text": "Rajput-Ji" }, { "code": null, "e": 30450, "s": 30439, "text": "VikasTomar" }, { "code": null, "e": 30471, "s": 30450, "text": "lohityakumarambashta" }, { "code": null, "e": 30486, "s": 30471, "text": "jindalharsh999" }, { "code": null, "e": 30499, "s": 30486, "text": "kushalshah18" }, { "code": null, "e": 30516, "s": 30499, "text": "sparshsharma2510" }, { "code": null, "e": 30532, "s": 30516, "text": "simranarora5sos" }, { "code": null, "e": 30541, "s": 30532, "text": "gabaa406" }, { "code": null, "e": 30554, "s": 30541, "text": "ahnafswapnil" }, { "code": null, "e": 30570, "s": 30554, "text": "saurabh1990aror" }, { "code": null, "e": 30583, "s": 30570, "text": "simmytarika5" }, { "code": null, "e": 30598, "s": 30583, "text": "kothavvsaakash" }, { "code": null, "e": 30609, "s": 30598, "text": "akashish__" }, { "code": null, "e": 30624, "s": 30609, "text": "cpu-scheduling" }, { "code": null, "e": 30657, "s": 30624, "text": "Operating Systems-CPU Scheduling" }, { "code": null, "e": 30671, "s": 30657, "text": "Java Programs" }, { "code": null, "e": 30689, "s": 30671, "text": "Operating Systems" }, { "code": null, "e": 30707, "s": 30689, "text": "Operating Systems" } ]
How to toggle a boolean using JavaScript ?
31 Oct, 2019 A boolean value can be toggled in JavaScript by using two approaches which are discussed below: Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value. The NOT operator is used before the variable to be toggled and the result is assigned to the same variable. This will effectively toggle the boolean value. Syntax: booleanValue = !booleanValue Example: <html><head> <title> How to toggle a boolean using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to toggle a boolean using JavaScript? </b> <p> The boolean is toggled whenever the button is pressed. </p> <p> See the console for the output </p> <button onclick="toggle()"> Toggle Bool </button> <script> let testBool = true; console.log('Default value of bool is', testBool); function toggle() { testBool = !testBool; console.log('Toggled bool is', testBool); } </script></body> </html> Output: Clicking the button once: Clicking the button twice: Method 2: Using the ternary operator: The ternary operator is used as a shortcut to using the if/else statement. It is used to make a decision based on the condition of expression. It takes three parameters, the condition statement, the expression to be executed if the condition is satisfied and the expression to be executed if the condition is not satisfied. The boolean value to be toggled is passed as the condition. The expression to be executed if true is given as ‘false’ and expression to be executed if false is given as ‘true’. The result of this operator is assigned back to the boolean value to be toggled. This will effectively toggle the value as a true condition will return false, and a false condition would return true. Syntax: booleanValue = booleanValue? false : true Example: <!DOCTYPE html><html> <head> <title> How to toggle a boolean using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to toggle a boolean using JavaScript? </b> <p> The boolean is toggled whenever the button is pressed. </p> <p> See the console for the output </p> <button onclick="toggle()"> Toggle Bool </button> <script> let testBool = true; console.log('Default value of bool is', testBool); function toggle() { testBool = testBool ? false : true; console.log('Toggled bool is', testBool); } </script></body> </html> Output: Clicking the button once: Clicking the button twice: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2019" }, { "code": null, "e": 124, "s": 28, "text": "A boolean value can be toggled in JavaScript by using two approaches which are discussed below:" }, { "code": null, "e": 565, "s": 124, "text": "Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value. The NOT operator is used before the variable to be toggled and the result is assigned to the same variable. This will effectively toggle the boolean value." }, { "code": null, "e": 573, "s": 565, "text": "Syntax:" }, { "code": null, "e": 602, "s": 573, "text": "booleanValue = !booleanValue" }, { "code": null, "e": 611, "s": 602, "text": "Example:" }, { "code": "<html><head> <title> How to toggle a boolean using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to toggle a boolean using JavaScript? </b> <p> The boolean is toggled whenever the button is pressed. </p> <p> See the console for the output </p> <button onclick=\"toggle()\"> Toggle Bool </button> <script> let testBool = true; console.log('Default value of bool is', testBool); function toggle() { testBool = !testBool; console.log('Toggled bool is', testBool); } </script></body> </html>", "e": 1426, "s": 611, "text": null }, { "code": null, "e": 1434, "s": 1426, "text": "Output:" }, { "code": null, "e": 1460, "s": 1434, "text": "Clicking the button once:" }, { "code": null, "e": 1487, "s": 1460, "text": "Clicking the button twice:" }, { "code": null, "e": 1849, "s": 1487, "text": "Method 2: Using the ternary operator: The ternary operator is used as a shortcut to using the if/else statement. It is used to make a decision based on the condition of expression. It takes three parameters, the condition statement, the expression to be executed if the condition is satisfied and the expression to be executed if the condition is not satisfied." }, { "code": null, "e": 2226, "s": 1849, "text": "The boolean value to be toggled is passed as the condition. The expression to be executed if true is given as ‘false’ and expression to be executed if false is given as ‘true’. The result of this operator is assigned back to the boolean value to be toggled. This will effectively toggle the value as a true condition will return false, and a false condition would return true." }, { "code": null, "e": 2234, "s": 2226, "text": "Syntax:" }, { "code": null, "e": 2276, "s": 2234, "text": "booleanValue = booleanValue? false : true" }, { "code": null, "e": 2285, "s": 2276, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to toggle a boolean using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to toggle a boolean using JavaScript? </b> <p> The boolean is toggled whenever the button is pressed. </p> <p> See the console for the output </p> <button onclick=\"toggle()\"> Toggle Bool </button> <script> let testBool = true; console.log('Default value of bool is', testBool); function toggle() { testBool = testBool ? false : true; console.log('Toggled bool is', testBool); } </script></body> </html>", "e": 3113, "s": 2285, "text": null }, { "code": null, "e": 3121, "s": 3113, "text": "Output:" }, { "code": null, "e": 3147, "s": 3121, "text": "Clicking the button once:" }, { "code": null, "e": 3174, "s": 3147, "text": "Clicking the button twice:" }, { "code": null, "e": 3190, "s": 3174, "text": "JavaScript-Misc" }, { "code": null, "e": 3197, "s": 3190, "text": "Picked" }, { "code": null, "e": 3208, "s": 3197, "text": "JavaScript" }, { "code": null, "e": 3225, "s": 3208, "text": "Web Technologies" }, { "code": null, "e": 3252, "s": 3225, "text": "Web technologies Questions" }, { "code": null, "e": 3350, "s": 3252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3411, "s": 3350, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3483, "s": 3411, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3523, "s": 3483, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3576, "s": 3523, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3617, "s": 3576, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3650, "s": 3617, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3712, "s": 3650, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3773, "s": 3712, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3823, "s": 3773, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to use WebView in Android
04 Jan, 2022 public class WebView extends AbsoluteLayout implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListener WebView is a view that display web pages inside the application. It is used to turn the application into a web application. Class Hierarchy : java.lang.Object ↳ android.view.View ↳ android.view.ViewGroup ↳ android.widget.AbsoluteLayout ↳ android.webkit.WebView MainActivity.java Java package com.example.hp.webview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.webkit.WebView;import android.webkit.WebViewClient; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Binding MainActivity.java with // activity_main.xml file setContentView(R.layout.activity_main); // Find the WebView by its unique ID WebView w = (WebView) findViewById(R.id.web); // loading http://www.google.com url in the the WebView. w.loadUrl("http://www.google.com"); // this will enable the javascript. w.getSettings().setJavaScriptEnabled(true); // WebViewClient allows you to handle // onPageFinished and override Url loading. w.setWebViewClient(new WebViewClient()); }} activity_main.xml In the xml file only use of WebView is made inside RelativeLayout. 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" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.hp.webview.MainActivity"> <WebView <!-- covers 368dp width as required. --> android:layout_width="368dp" <!-- unique ID of WebView --> android:id="@+id/web" <!-- covers 495dp height as required. --> android:layout_height="495dp" tools:layout_editor_absoluteX="8dp" tools:layout_editor_absoluteY="8dp" /></RelativeLayout> In AndroidManifest.xml, one needs to include below permission, in order to access internet: "uses-permission android:name="android.permission.INTERNET" prachisoda1234 android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jan, 2022" }, { "code": null, "e": 204, "s": 54, "text": "public class WebView \nextends AbsoluteLayout \nimplements \n ViewTreeObserver.OnGlobalFocusChangeListener, \n ViewGroup.OnHierarchyChangeListener\n" }, { "code": null, "e": 328, "s": 204, "text": "WebView is a view that display web pages inside the application. It is used to turn the application into a web application." }, { "code": null, "e": 346, "s": 328, "text": "Class Hierarchy :" }, { "code": null, "e": 512, "s": 346, "text": "java.lang.Object\n ↳ android.view.View\n ↳ android.view.ViewGroup\n ↳ android.widget.AbsoluteLayout\n ↳ android.webkit.WebView\n" }, { "code": null, "e": 530, "s": 512, "text": "MainActivity.java" }, { "code": null, "e": 535, "s": 530, "text": "Java" }, { "code": "package com.example.hp.webview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.webkit.WebView;import android.webkit.WebViewClient; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Binding MainActivity.java with // activity_main.xml file setContentView(R.layout.activity_main); // Find the WebView by its unique ID WebView w = (WebView) findViewById(R.id.web); // loading http://www.google.com url in the the WebView. w.loadUrl(\"http://www.google.com\"); // this will enable the javascript. w.getSettings().setJavaScriptEnabled(true); // WebViewClient allows you to handle // onPageFinished and override Url loading. w.setWebViewClient(new WebViewClient()); }}", "e": 1508, "s": 535, "text": null }, { "code": null, "e": 1527, "s": 1508, "text": " activity_main.xml" }, { "code": null, "e": 1594, "s": 1527, "text": "In the xml file only use of WebView is made inside RelativeLayout." }, { "code": null, "e": 1598, "s": 1594, "text": "xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.example.hp.webview.MainActivity\"> <WebView <!-- covers 368dp width as required. --> android:layout_width=\"368dp\" <!-- unique ID of WebView --> android:id=\"@+id/web\" <!-- covers 495dp height as required. --> android:layout_height=\"495dp\" tools:layout_editor_absoluteX=\"8dp\" tools:layout_editor_absoluteY=\"8dp\" /></RelativeLayout>", "e": 2340, "s": 1598, "text": null }, { "code": null, "e": 2432, "s": 2340, "text": "In AndroidManifest.xml, one needs to include below permission, in order to access internet:" }, { "code": null, "e": 2493, "s": 2432, "text": "\"uses-permission android:name=\"android.permission.INTERNET\"\n" }, { "code": null, "e": 2508, "s": 2493, "text": "prachisoda1234" }, { "code": null, "e": 2516, "s": 2508, "text": "android" }, { "code": null, "e": 2529, "s": 2516, "text": "Android-View" }, { "code": null, "e": 2537, "s": 2529, "text": "Android" }, { "code": null, "e": 2542, "s": 2537, "text": "Java" }, { "code": null, "e": 2547, "s": 2542, "text": "Java" }, { "code": null, "e": 2555, "s": 2547, "text": "Android" } ]
MySQL – ON DELETE CASCADE Constraint
08 Feb, 2021 ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id. All the courses in these online learning platforms had their own code, title, and name. Students can enroll in any course according to their wishes. There is no rule that all students must enroll in all courses, or they have to join the course on the same date. A student can enroll in one or more courses. Suppose you delete a row from the “Student” table, now you will also want to delete all rows in the “Enroll” table that references the row in the “Student” table. For that, we need ON DELETE CASCADE. Below are the steps that explain how ON DELETE CASCADE referential action works. Step 1: Create the Student table CREATE TABLE Student ( sno INT PRIMARY KEY, sname VARCHAR(20), age INT ); Step 2: Insert rows into the Student table INSERT INTO Student(sno, sname,age) VALUES(1,'Ankit',17), (2,'Ramya',18), (3,'Ram',16); Step 3: Execute the SELECT query to check the data in the STUDENT table. SELECT * FROM Student; Output: Step 4: Create the Course table CREATE TABLE Course ( cno INT PRIMARY KEY, cname VARCHAR(20) ); Step 5: Insert rows into the Course table INSERT INTO Course(cno, cname) VALUES(101,'c'), (102,'c++'), (103,'DBMS'); Step 6: Execute the SELECT query to check the data in the Course table. SELECT * FROM Course; Output: Step 7: Create the Enroll table CREATE TABLE Enroll ( sno INT, cno INT, jdate date, PRIMARY KEY(sno,cno), FOREIGN KEY(sno) REFERENCES Student(sno) ON DELETE CASCADE FOREIGN KEY(cno) REFERENCES Course(cno) ON DELETE CASCADE ); Step 8: Insert rows into the Enroll table INSERT INTO Enroll(sno,cno,jdate) VALUES(1, 101, '5-jun-2021'), (1, 102, '5-jun-2021'), (2, 103, '6-jun-2021'); Step 9: Execute the SELECT query to check the data in the Enroll table. SELECT * FROM Enroll; Output: Step 10: Here the parent tables are Student and Course whereas the child table is Enroll. If a student drops from the course or a course is removed from the offering list it must affect the child table also. DELETE FROM Student WHERE sname="Ramya"; Step 11: Execute the SELECT query to check the data. Select * from Student; Output: Select * from Enroll; Output: As you delete the contents of sno=2 in the parent table it automatically deletes the details of sno=2 from the child table also. In the same way, if you remove a course from the Course table it automatically deletes the rows of that course in the child table Enroll. This works out because the foreign key constraint ON DELETE CASCADE is specified. DBMS-SQL DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Feb, 2021" }, { "code": null, "e": 501, "s": 54, "text": "ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id. All the courses in these online learning platforms had their own code, title, and name. Students can enroll in any course according to their wishes. " }, { "code": null, "e": 941, "s": 501, "text": "There is no rule that all students must enroll in all courses, or they have to join the course on the same date. A student can enroll in one or more courses. Suppose you delete a row from the “Student” table, now you will also want to delete all rows in the “Enroll” table that references the row in the “Student” table. For that, we need ON DELETE CASCADE. Below are the steps that explain how ON DELETE CASCADE referential action works." }, { "code": null, "e": 974, "s": 941, "text": "Step 1: Create the Student table" }, { "code": null, "e": 1061, "s": 974, "text": "CREATE TABLE Student (\n sno INT PRIMARY KEY,\n sname VARCHAR(20),\n age INT\n\n);" }, { "code": null, "e": 1104, "s": 1061, "text": "Step 2: Insert rows into the Student table" }, { "code": null, "e": 1208, "s": 1104, "text": "INSERT INTO Student(sno, sname,age) \n VALUES(1,'Ankit',17),\n (2,'Ramya',18),\n (3,'Ram',16);" }, { "code": null, "e": 1281, "s": 1208, "text": "Step 3: Execute the SELECT query to check the data in the STUDENT table." }, { "code": null, "e": 1304, "s": 1281, "text": "SELECT *\nFROM Student;" }, { "code": null, "e": 1312, "s": 1304, "text": "Output:" }, { "code": null, "e": 1344, "s": 1312, "text": "Step 4: Create the Course table" }, { "code": null, "e": 1416, "s": 1344, "text": "CREATE TABLE Course (\n cno INT PRIMARY KEY,\n cname VARCHAR(20)\n);" }, { "code": null, "e": 1458, "s": 1416, "text": "Step 5: Insert rows into the Course table" }, { "code": null, "e": 1549, "s": 1458, "text": "INSERT INTO Course(cno, cname) \n VALUES(101,'c'),\n (102,'c++'),\n (103,'DBMS');" }, { "code": null, "e": 1621, "s": 1549, "text": "Step 6: Execute the SELECT query to check the data in the Course table." }, { "code": null, "e": 1643, "s": 1621, "text": "SELECT *\nFROM Course;" }, { "code": null, "e": 1651, "s": 1643, "text": "Output:" }, { "code": null, "e": 1684, "s": 1651, "text": "Step 7: Create the Enroll table " }, { "code": null, "e": 1936, "s": 1684, "text": "CREATE TABLE Enroll (\n sno INT,\n cno INT,\n jdate date,\n PRIMARY KEY(sno,cno),\n FOREIGN KEY(sno) \n REFERENCES Student(sno)\n ON DELETE CASCADE\n FOREIGN KEY(cno) \n REFERENCES Course(cno)\n ON DELETE CASCADE\n);" }, { "code": null, "e": 1978, "s": 1936, "text": "Step 8: Insert rows into the Enroll table" }, { "code": null, "e": 2106, "s": 1978, "text": "INSERT INTO Enroll(sno,cno,jdate) \n VALUES(1, 101, '5-jun-2021'),\n (1, 102, '5-jun-2021'),\n (2, 103, '6-jun-2021');" }, { "code": null, "e": 2178, "s": 2106, "text": "Step 9: Execute the SELECT query to check the data in the Enroll table." }, { "code": null, "e": 2200, "s": 2178, "text": "SELECT *\nFROM Enroll;" }, { "code": null, "e": 2208, "s": 2200, "text": "Output:" }, { "code": null, "e": 2417, "s": 2208, "text": "Step 10: Here the parent tables are Student and Course whereas the child table is Enroll. If a student drops from the course or a course is removed from the offering list it must affect the child table also. " }, { "code": null, "e": 2458, "s": 2417, "text": "DELETE FROM Student\nWHERE sname=\"Ramya\";" }, { "code": null, "e": 2511, "s": 2458, "text": "Step 11: Execute the SELECT query to check the data." }, { "code": null, "e": 2534, "s": 2511, "text": "Select * from Student;" }, { "code": null, "e": 2543, "s": 2534, "text": "Output: " }, { "code": null, "e": 2565, "s": 2543, "text": "Select * from Enroll;" }, { "code": null, "e": 2573, "s": 2565, "text": "Output:" }, { "code": null, "e": 2922, "s": 2573, "text": "As you delete the contents of sno=2 in the parent table it automatically deletes the details of sno=2 from the child table also. In the same way, if you remove a course from the Course table it automatically deletes the rows of that course in the child table Enroll. This works out because the foreign key constraint ON DELETE CASCADE is specified." }, { "code": null, "e": 2931, "s": 2922, "text": "DBMS-SQL" }, { "code": null, "e": 2936, "s": 2931, "text": "DBMS" }, { "code": null, "e": 2940, "s": 2936, "text": "SQL" }, { "code": null, "e": 2945, "s": 2940, "text": "DBMS" }, { "code": null, "e": 2949, "s": 2945, "text": "SQL" } ]
Split a string in equal parts such that all parts are palindromes
29 Jul, 2021 Given a string str, the task is to split the string into minimum parts such that each part is of same length and each part is a palindrome. Print the required number of parts.Examples: Input: str = “civicbob” Output: 8 “b”, “b”, “c”, “c”, “i”, “i”, “v” and “o” are the required partitions. “civic” and “bob” are also palindromes but they are not of equal lengthInput: str = “noonpeep” Output: 1 Approach: Count the number of odd appearing characters and store it in countOdd. Sum the frequencies of all the even occurring characters and store it in sumEven. Since, no more than one odd frequency character can be a part of the same palindrome. So, if (sumEven / 2) % countOdd = 0 then the answer is countOdd as sumEven can be divided into countOdd parts. Else, we can still divide the odd occurring characters into the palindrome pairs. For example, if the character a appears 3 times i.e. aaa then aa can be a part of some palindrome while leaving a as odd (without affecting the original frequency). Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the frequency array// for the given stringint* getFrequencies(string str){ static int freq[26] = { 0 }; for (int i = 0; i < str.length(); i++) { freq[str[i] - 'a']++; } return freq;} // Function to return the required countint countMinParts(string str){ int n = str.length(); int *freq = getFrequencies(str); vector<int> oddFreq, evenFreq; int i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.push_back(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.push_back(freq[i]); } for (i = 0; i < evenFreq.size(); i++) { sumEven += evenFreq[i]; } // If there are no characters with odd frequency if (oddFreq.size() == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.size() == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.size()) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.size() == 0) return oddFreq.size(); // Current character can no longer be an element // in a string other than the mid character if (oddFreq[i] == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq[i] = oddFreq[i] - 2; } // If not possible, then every character of the // string will act as a separate palindrome return n;} // Driver codeint main(){ string s = "noonpeep"; cout<<countMinParts(s);} // Java implementation of the approachimport java.util.*;public class GFG { // Function to return the frequency array // for the given string static int[] getFrequencies(String str) { int freq[] = new int[26]; for (int i = 0; i < str.length(); i++) { freq[str.charAt(i) - 'a']++; } return freq; } // Function to return the required count static int countMinParts(String str) { int n = str.length(); int freq[] = getFrequencies(str); List<Integer> oddFreq = new ArrayList<>(); List<Integer> evenFreq = new ArrayList<>(); int i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.add(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.add(freq[i]); } for (i = 0; i < evenFreq.size(); i++) { sumEven += evenFreq.get(i); } // If there are no characters with odd frequency if (oddFreq.size() == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.size() == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.size()) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.size() == 0) return oddFreq.size(); // Current character can no longer be an element // in a string other than the mid character if (oddFreq.get(i) == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq.set(i, oddFreq.get(i) - 2); } // If not possible, then every character of the // string will act as a separate palindrome return n; } // Driver code public static void main(String[] args) { String s = "noonpeep"; System.out.println(countMinParts(s)); }} // This code is contributed by chitranayal # Python3 implementation of the approach # Function to return the frequency array# for the given stringdef getFrequencies(string) : freq = [0] * 26 for i in range(len(string)) : freq[ord(string[i]) - ord('a')] += 1 return freq # Function to return the required countdef countMinParts(string) : n = len(string) freq = getFrequencies(string) oddFreq = [] evenFreq = [] sumEven = 0 for i in range(26) : if freq[i] == 0 : continue # Add frequencies of the even # appearing characters if freq[i] % 2 == 0 : evenFreq.append(freq[i]) # Count of the characters that # appeared odd number of times else : oddFreq.append(freq[i]) for i in range(len(evenFreq)) : sumEven += evenFreq[i] # If there are no characters with # odd frequency if len(oddFreq) == 0 : return 1 # If there are no characters with # even frequency if sumEven == 0 : # Only a single character with # odd frequency if len(oddFreq) == 1: return 1 # More than 1 character with odd # frequency string isn't a palindrome return 0 i = 0 # All odd appearing characters can also # contribute to the even length palindrome # if one character is removed from the # frequency leaving it as even while(i < len(oddFreq)) : # If k palindromes are possible where # k is the number of characters with # odd frequency if ((sumEven / 2) % len(oddFreq) == 0) : return len(oddFreq) # Current character can no longer be # an element in a string other than # the mid character if (oddFreq[i] == 1) : i += 1 continue # If current character has odd frequency > 1 # take two characters which can be used in # any of the parts sumEven += 2 # Update the frequency oddFreq[i] = oddFreq[i] - 2 # If not possible, then every character of the # string will act as a separate palindrome return n # Driver codeif __name__ == "__main__" : s = "noonpeep" print(countMinParts(s)) # This code is contributed by Ryuga // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the frequency array // for the given string static int[] getFrequencies(String str) { int []freq = new int[26]; for (int i = 0; i < str.Length; i++) { freq[str[i] - 'a']++; } return freq; } // Function to return the required count static int countMinParts(String str) { int n = str.Length; int []freq = getFrequencies(str); List<int> oddFreq = new List<int>(); List<int> evenFreq = new List<int>(); int i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.Add(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.Add(freq[i]); } for (i = 0; i < evenFreq.Count; i++) { sumEven += evenFreq[i]; } // If there are no characters with odd frequency if (oddFreq.Count == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.Count == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.Count) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.Count == 0) return oddFreq.Count; // Current character can no longer be an element // in a string other than the mid character if (oddFreq[i] == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq.Insert(i, oddFreq[i] - 2); } // If not possible, then every character of the // string will act as a separate palindrome return n; } // Driver code public static void Main(String[] args) { String s = "noonpeep"; Console.WriteLine(countMinParts(s)); }} // This code has been contributed by 29AjayKumar <script> // Javascript implementation of the approach // Function to return the frequency array // for the given stringfunction getFrequencies(str){ let freq = new Array(26); for(let i=0;i<26;i++) freq[i]=0; for (let i = 0; i < str.length; i++) { freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } return freq;} // Function to return the required countfunction countMinParts(str){ let n = str.length; let freq = getFrequencies(str); let oddFreq = []; let evenFreq = []; let i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.push(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.push(freq[i]); } for (i = 0; i < evenFreq.length; i++) { sumEven += evenFreq[i]; } // If there are no characters with odd frequency if (oddFreq.length == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.length == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.length) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.length == 0) return oddFreq.length; // Current character can no longer be an element // in a string other than the mid character if (oddFreq[i] == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq[i]= oddFreq[i] - 2; } // If not possible, then every character of the // string will act as a separate palindrome return n;} // Driver codelet s = "noonpeep"; document.write(countMinParts(s)); // This code is contributed by rag2127 </script> 1 ankthon 29AjayKumar Sanjit_Prasad rag2127 C++ C++ Programs Competitive Programming Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jul, 2021" }, { "code": null, "e": 239, "s": 52, "text": "Given a string str, the task is to split the string into minimum parts such that each part is of same length and each part is a palindrome. Print the required number of parts.Examples: " }, { "code": null, "e": 451, "s": 239, "text": "Input: str = “civicbob” Output: 8 “b”, “b”, “c”, “c”, “i”, “i”, “v” and “o” are the required partitions. “civic” and “bob” are also palindromes but they are not of equal lengthInput: str = “noonpeep” Output: 1 " }, { "code": null, "e": 465, "s": 453, "text": "Approach: " }, { "code": null, "e": 536, "s": 465, "text": "Count the number of odd appearing characters and store it in countOdd." }, { "code": null, "e": 618, "s": 536, "text": "Sum the frequencies of all the even occurring characters and store it in sumEven." }, { "code": null, "e": 815, "s": 618, "text": "Since, no more than one odd frequency character can be a part of the same palindrome. So, if (sumEven / 2) % countOdd = 0 then the answer is countOdd as sumEven can be divided into countOdd parts." }, { "code": null, "e": 1062, "s": 815, "text": "Else, we can still divide the odd occurring characters into the palindrome pairs. For example, if the character a appears 3 times i.e. aaa then aa can be a part of some palindrome while leaving a as odd (without affecting the original frequency)." }, { "code": null, "e": 1115, "s": 1062, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1119, "s": 1115, "text": "CPP" }, { "code": null, "e": 1124, "s": 1119, "text": "Java" }, { "code": null, "e": 1132, "s": 1124, "text": "Python3" }, { "code": null, "e": 1135, "s": 1132, "text": "C#" }, { "code": null, "e": 1146, "s": 1135, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the frequency array// for the given stringint* getFrequencies(string str){ static int freq[26] = { 0 }; for (int i = 0; i < str.length(); i++) { freq[str[i] - 'a']++; } return freq;} // Function to return the required countint countMinParts(string str){ int n = str.length(); int *freq = getFrequencies(str); vector<int> oddFreq, evenFreq; int i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.push_back(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.push_back(freq[i]); } for (i = 0; i < evenFreq.size(); i++) { sumEven += evenFreq[i]; } // If there are no characters with odd frequency if (oddFreq.size() == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.size() == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.size()) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.size() == 0) return oddFreq.size(); // Current character can no longer be an element // in a string other than the mid character if (oddFreq[i] == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq[i] = oddFreq[i] - 2; } // If not possible, then every character of the // string will act as a separate palindrome return n;} // Driver codeint main(){ string s = \"noonpeep\"; cout<<countMinParts(s);}", "e": 3469, "s": 1146, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;public class GFG { // Function to return the frequency array // for the given string static int[] getFrequencies(String str) { int freq[] = new int[26]; for (int i = 0; i < str.length(); i++) { freq[str.charAt(i) - 'a']++; } return freq; } // Function to return the required count static int countMinParts(String str) { int n = str.length(); int freq[] = getFrequencies(str); List<Integer> oddFreq = new ArrayList<>(); List<Integer> evenFreq = new ArrayList<>(); int i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.add(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.add(freq[i]); } for (i = 0; i < evenFreq.size(); i++) { sumEven += evenFreq.get(i); } // If there are no characters with odd frequency if (oddFreq.size() == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.size() == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.size()) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.size() == 0) return oddFreq.size(); // Current character can no longer be an element // in a string other than the mid character if (oddFreq.get(i) == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq.set(i, oddFreq.get(i) - 2); } // If not possible, then every character of the // string will act as a separate palindrome return n; } // Driver code public static void main(String[] args) { String s = \"noonpeep\"; System.out.println(countMinParts(s)); }} // This code is contributed by chitranayal", "e": 6259, "s": 3469, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the frequency array# for the given stringdef getFrequencies(string) : freq = [0] * 26 for i in range(len(string)) : freq[ord(string[i]) - ord('a')] += 1 return freq # Function to return the required countdef countMinParts(string) : n = len(string) freq = getFrequencies(string) oddFreq = [] evenFreq = [] sumEven = 0 for i in range(26) : if freq[i] == 0 : continue # Add frequencies of the even # appearing characters if freq[i] % 2 == 0 : evenFreq.append(freq[i]) # Count of the characters that # appeared odd number of times else : oddFreq.append(freq[i]) for i in range(len(evenFreq)) : sumEven += evenFreq[i] # If there are no characters with # odd frequency if len(oddFreq) == 0 : return 1 # If there are no characters with # even frequency if sumEven == 0 : # Only a single character with # odd frequency if len(oddFreq) == 1: return 1 # More than 1 character with odd # frequency string isn't a palindrome return 0 i = 0 # All odd appearing characters can also # contribute to the even length palindrome # if one character is removed from the # frequency leaving it as even while(i < len(oddFreq)) : # If k palindromes are possible where # k is the number of characters with # odd frequency if ((sumEven / 2) % len(oddFreq) == 0) : return len(oddFreq) # Current character can no longer be # an element in a string other than # the mid character if (oddFreq[i] == 1) : i += 1 continue # If current character has odd frequency > 1 # take two characters which can be used in # any of the parts sumEven += 2 # Update the frequency oddFreq[i] = oddFreq[i] - 2 # If not possible, then every character of the # string will act as a separate palindrome return n # Driver codeif __name__ == \"__main__\" : s = \"noonpeep\" print(countMinParts(s)) # This code is contributed by Ryuga", "e": 8943, "s": 6259, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the frequency array // for the given string static int[] getFrequencies(String str) { int []freq = new int[26]; for (int i = 0; i < str.Length; i++) { freq[str[i] - 'a']++; } return freq; } // Function to return the required count static int countMinParts(String str) { int n = str.Length; int []freq = getFrequencies(str); List<int> oddFreq = new List<int>(); List<int> evenFreq = new List<int>(); int i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.Add(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.Add(freq[i]); } for (i = 0; i < evenFreq.Count; i++) { sumEven += evenFreq[i]; } // If there are no characters with odd frequency if (oddFreq.Count == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.Count == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.Count) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.Count == 0) return oddFreq.Count; // Current character can no longer be an element // in a string other than the mid character if (oddFreq[i] == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq.Insert(i, oddFreq[i] - 2); } // If not possible, then every character of the // string will act as a separate palindrome return n; } // Driver code public static void Main(String[] args) { String s = \"noonpeep\"; Console.WriteLine(countMinParts(s)); }} // This code has been contributed by 29AjayKumar", "e": 11764, "s": 8943, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the frequency array // for the given stringfunction getFrequencies(str){ let freq = new Array(26); for(let i=0;i<26;i++) freq[i]=0; for (let i = 0; i < str.length; i++) { freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } return freq;} // Function to return the required countfunction countMinParts(str){ let n = str.length; let freq = getFrequencies(str); let oddFreq = []; let evenFreq = []; let i, sumEven = 0; for (i = 0; i < 26; i++) { if (freq[i] == 0) continue; // Add frequencies of the even appearing // characters if (freq[i] % 2 == 0) evenFreq.push(freq[i]); // Count of the characters that appeared // odd number of times else oddFreq.push(freq[i]); } for (i = 0; i < evenFreq.length; i++) { sumEven += evenFreq[i]; } // If there are no characters with odd frequency if (oddFreq.length == 0) return 1; // If there are no characters with even frequency if (sumEven == 0) { // Only a single character with odd frequency if (oddFreq.length == 1) return 1; // More than 1 character with odd frequency // string isn't a palindrome return 0; } i = 0; // All odd appearing characters can also contribute to // the even length palindrome if one character // is removed from the frequency leaving it as even while (i < oddFreq.length) { // If k palindromes are possible where k // is the number of characters with odd frequency if ((sumEven / 2) % oddFreq.length == 0) return oddFreq.length; // Current character can no longer be an element // in a string other than the mid character if (oddFreq[i] == 1) { i++; continue; } // If current character has odd frequency > 1 // take two characters which can be used in // any of the parts sumEven += 2; // Update the frequency oddFreq[i]= oddFreq[i] - 2; } // If not possible, then every character of the // string will act as a separate palindrome return n;} // Driver codelet s = \"noonpeep\"; document.write(countMinParts(s)); // This code is contributed by rag2127 </script>", "e": 14427, "s": 11764, "text": null }, { "code": null, "e": 14429, "s": 14427, "text": "1" }, { "code": null, "e": 14439, "s": 14431, "text": "ankthon" }, { "code": null, "e": 14451, "s": 14439, "text": "29AjayKumar" }, { "code": null, "e": 14465, "s": 14451, "text": "Sanjit_Prasad" }, { "code": null, "e": 14473, "s": 14465, "text": "rag2127" }, { "code": null, "e": 14477, "s": 14473, "text": "C++" }, { "code": null, "e": 14490, "s": 14477, "text": "C++ Programs" }, { "code": null, "e": 14514, "s": 14490, "text": "Competitive Programming" }, { "code": null, "e": 14522, "s": 14514, "text": "Strings" }, { "code": null, "e": 14530, "s": 14522, "text": "Strings" }, { "code": null, "e": 14534, "s": 14530, "text": "CPP" } ]
SAS - Strings
Strings in SAS are the values which are enclosed with in a pair of single quotes. Also the string variables are declared by adding a space and $ sign at the end of the variable declaration. SAS has many powerful functions to analyze and manipulate strings. We can declare the string variables and their values as shown below. In the code below we declare two character variables of lengths 6 and 5. The LENGTH keyword is used for declaring variables without creating multiple observations. data string_examples; LENGTH string1 $ 6 String2 $ 5; /*String variables of length 6 and 5 */ String1 = 'Hello'; String2 = 'World'; Joined_strings = String1 ||String2 ; run; proc print data = string_examples noobs; run; On running the above code we get the output which shows the variable names and their values. Below are the examples of some SAS functions which are used frequently. This function extracts a substring using the start and end positions. In case of no end position is mentioned it extracts all the characters till end of the string. SUBSTRN('stringval',p1,p2) Following is the description of the parameters used − stringval is the value of the string variable. p1 is the start position of extraction. p2 is the final position of extraction. data string_examples; LENGTH string1 $ 6 ; String1 = 'Hello'; sub_string1 = substrn(String1,2,4) ; /*Extract from position 2 to 4 */ sub_string2 = substrn(String1,3) ; /*Extract from position 3 onwards */ run; proc print data = string_examples noobs; run; On running the above code we get the output which shows the result of substrn function. This function removes the trailing space form a string. TRIMN('stringval') Following is the description of the parameters used − stringval is the value of the string variable. data string_examples; LENGTH string1 $ 7 ; String1='Hello '; length_string1 = lengthc(String1); length_trimmed_string = lengthc(TRIMN(String1)); run; proc print data = string_examples noobs; run; On running the above code we get the output which shows the result of TRIMN function.
[ { "code": null, "e": 2974, "s": 2717, "text": "Strings in SAS are the values which are enclosed with in a pair of single quotes. Also the string variables are declared by adding a space and $ sign at the end of the variable declaration. SAS has many powerful functions to analyze and manipulate strings." }, { "code": null, "e": 3207, "s": 2974, "text": "We can declare the string variables and their values as shown below. In the code below we declare two character variables of lengths 6 and 5. The LENGTH keyword is used for declaring variables without creating multiple observations." }, { "code": null, "e": 3444, "s": 3207, "text": "data string_examples;\n LENGTH string1 $ 6 String2 $ 5;\n /*String variables of length 6 and 5 */\n String1 = 'Hello';\n String2 = 'World';\n Joined_strings = String1 ||String2 ;\nrun;\nproc print data = string_examples noobs;\nrun;\n" }, { "code": null, "e": 3537, "s": 3444, "text": "On running the above code we get the output which shows the variable names and their values." }, { "code": null, "e": 3609, "s": 3537, "text": "Below are the examples of some SAS functions which are used frequently." }, { "code": null, "e": 3774, "s": 3609, "text": "This function extracts a substring using the start and end positions. In case of no end position is mentioned it extracts all the characters till end of the string." }, { "code": null, "e": 3802, "s": 3774, "text": "SUBSTRN('stringval',p1,p2)\n" }, { "code": null, "e": 3856, "s": 3802, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 3903, "s": 3856, "text": "stringval is the value of the string variable." }, { "code": null, "e": 3943, "s": 3903, "text": "p1 is the start position of extraction." }, { "code": null, "e": 3983, "s": 3943, "text": "p2 is the final position of extraction." }, { "code": null, "e": 4258, "s": 3983, "text": "data string_examples;\n LENGTH string1 $ 6 ;\n String1 = 'Hello';\n sub_string1 = substrn(String1,2,4) ;\n /*Extract from position 2 to 4 */\n sub_string2 = substrn(String1,3) ;\n /*Extract from position 3 onwards */\nrun;\nproc print data = string_examples noobs;\nrun;\n" }, { "code": null, "e": 4346, "s": 4258, "text": "On running the above code we get the output which shows the result of substrn function." }, { "code": null, "e": 4402, "s": 4346, "text": "This function removes the trailing space form a string." }, { "code": null, "e": 4422, "s": 4402, "text": "TRIMN('stringval')\n" }, { "code": null, "e": 4476, "s": 4422, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 4523, "s": 4476, "text": "stringval is the value of the string variable." }, { "code": null, "e": 4733, "s": 4523, "text": "data string_examples;\n LENGTH string1 $ 7 ;\n String1='Hello ';\n length_string1 = lengthc(String1);\n length_trimmed_string = lengthc(TRIMN(String1));\nrun;\nproc print data = string_examples noobs;\nrun;" } ]
SQLAlchemy ORM - Using Query
All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it. Query objects are initially generated using the query() method of the Session as follows − q = session.query(mapped class) Following statement is also equivalent to the above given statement − q = Query(mappedClass, session) The query object has all() method which returns a resultset in the form of list of objects. If we execute it on our customers table − result = session.query(Customers).all() This statement is effectively equivalent to following SQL expression − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers The result object can be traversed using For loop as below to obtain all records in underlying customers table. Here is the complete code to display all records in Customers table − from sqlalchemy import Column, Integer, String from sqlalchemy import create_engine engine = create_engine('sqlite:///sales.db', echo = True) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Customers(Base): __tablename__ = 'customers' id = Column(Integer, primary_key = True) name = Column(String) address = Column(String) email = Column(String) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() result = session.query(Customers).all() for row in result: print ("Name: ",row.name, "Address:",row.address, "Email:",row.email) Python console shows list of records as below − Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com Name: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com The Query object also has following useful methods − add_columns() It adds one or more column expressions to the list of result columns to be returned. add_entity() It adds a mapped entity to the list of result columns to be returned. count() It returns a count of rows this Query would return. delete() It performs a bulk delete query. Deletes rows matched by this query from the database. distinct() It applies a DISTINCT clause to the query and return the newly resulting Query. filter() It applies the given filtering criterion to a copy of this Query, using SQL expressions. first() It returns the first result of this Query or None if the result doesn’t contain any row. get() It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. group_by() It applies one or more GROUP BY criterion to the query and return the newly resulting Query join() It creates a SQL JOIN against this Query object’s criterion and apply generatively, returning the newly resulting Query. one() It returns exactly one result or raise an exception. order_by() It applies one or more ORDER BY criterion to the query and returns the newly resulting Query. update() It performs a bulk update query and updates rows matched by this query in the database.
[ { "code": null, "e": 2721, "s": 2474, "text": "All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it." }, { "code": null, "e": 2812, "s": 2721, "text": "Query objects are initially generated using the query() method of the Session as follows −" }, { "code": null, "e": 2844, "s": 2812, "text": "q = session.query(mapped class)" }, { "code": null, "e": 2914, "s": 2844, "text": "Following statement is also equivalent to the above given statement −" }, { "code": null, "e": 2946, "s": 2914, "text": "q = Query(mappedClass, session)" }, { "code": null, "e": 3080, "s": 2946, "text": "The query object has all() method which returns a resultset in the form of list of objects. If we execute it on our customers table −" }, { "code": null, "e": 3120, "s": 3080, "text": "result = session.query(Customers).all()" }, { "code": null, "e": 3191, "s": 3120, "text": "This statement is effectively equivalent to following SQL expression −" }, { "code": null, "e": 3356, "s": 3191, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers" }, { "code": null, "e": 3538, "s": 3356, "text": "The result object can be traversed using For loop as below to obtain all records in underlying customers table. Here is the complete code to display all records in Customers table −" }, { "code": null, "e": 4174, "s": 3538, "text": "from sqlalchemy import Column, Integer, String\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///sales.db', echo = True)\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\nclass Customers(Base):\n __tablename__ = 'customers'\n id = Column(Integer, primary_key = True)\n name = Column(String)\n\n address = Column(String)\n email = Column(String)\n\nfrom sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)\nsession = Session()\nresult = session.query(Customers).all()\n\nfor row in result:\n print (\"Name: \",row.name, \"Address:\",row.address, \"Email:\",row.email)" }, { "code": null, "e": 4222, "s": 4174, "text": "Python console shows list of records as below −" }, { "code": null, "e": 4494, "s": 4222, "text": "Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com\nName: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com\nName: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com\nName: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com\n" }, { "code": null, "e": 4547, "s": 4494, "text": "The Query object also has following useful methods −" }, { "code": null, "e": 4561, "s": 4547, "text": "add_columns()" }, { "code": null, "e": 4646, "s": 4561, "text": "It adds one or more column expressions to the list of result columns to be returned." }, { "code": null, "e": 4659, "s": 4646, "text": "add_entity()" }, { "code": null, "e": 4729, "s": 4659, "text": "It adds a mapped entity to the list of result columns to be returned." }, { "code": null, "e": 4737, "s": 4729, "text": "count()" }, { "code": null, "e": 4789, "s": 4737, "text": "It returns a count of rows this Query would return." }, { "code": null, "e": 4798, "s": 4789, "text": "delete()" }, { "code": null, "e": 4885, "s": 4798, "text": "It performs a bulk delete query. Deletes rows matched by this query from the database." }, { "code": null, "e": 4896, "s": 4885, "text": "distinct()" }, { "code": null, "e": 4976, "s": 4896, "text": "It applies a DISTINCT clause to the query and return the newly resulting Query." }, { "code": null, "e": 4985, "s": 4976, "text": "filter()" }, { "code": null, "e": 5074, "s": 4985, "text": "It applies the given filtering criterion to a copy of this Query, using SQL expressions." }, { "code": null, "e": 5082, "s": 5074, "text": "first()" }, { "code": null, "e": 5171, "s": 5082, "text": "It returns the first result of this Query or None if the result doesn’t contain any row." }, { "code": null, "e": 5177, "s": 5171, "text": "get()" }, { "code": null, "e": 5309, "s": 5177, "text": "It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session." }, { "code": null, "e": 5320, "s": 5309, "text": "group_by()" }, { "code": null, "e": 5412, "s": 5320, "text": "It applies one or more GROUP BY criterion to the query and return the newly resulting Query" }, { "code": null, "e": 5419, "s": 5412, "text": "join()" }, { "code": null, "e": 5540, "s": 5419, "text": "It creates a SQL JOIN against this Query object’s criterion and apply generatively, returning the newly resulting Query." }, { "code": null, "e": 5546, "s": 5540, "text": "one()" }, { "code": null, "e": 5599, "s": 5546, "text": "It returns exactly one result or raise an exception." }, { "code": null, "e": 5610, "s": 5599, "text": "order_by()" }, { "code": null, "e": 5704, "s": 5610, "text": "It applies one or more ORDER BY criterion to the query and returns the newly resulting Query." }, { "code": null, "e": 5713, "s": 5704, "text": "update()" } ]
Python | Pandas Series.str.index()
13 Jul, 2020 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.index() method is used to search and return lowest index of a substring in particular section (Between start and end) of every string in a series. This method works in a similar way to str.find() but on not found case, instead of returning -1, str.index() gives a ValueError. Syntax: Series.str.index(sub, start=0, end=None) Parameters:sub: String or character to be searched in the text value in seriesstart: String or character to be searched in the text value in seriesend: String or character to be searched in the text value in series Return type: Series with least index of substring if found. To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1: Finding index when substring exists in every string In this example, ‘e’ is passed as substring. Since ‘e’ exists in all 5 strings, least index of it’s occurrence is returned. Before applying any operations, null rows were removed using .dropna() method. # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # extracting 5 rowsshort_data = data.head().copy() # calling str.index() methodshort_data["Index Name"]= short_data["Name"].str.index("e") # displayshort_data Output:As shown in the output image, the least index of ‘e’ in series was returned and stored in new column. Example #2: In this example, ‘a’ is searched in top 5 rows. Since ‘a’ doesn’t exist in every string, value error will be returned. To handle error, try and except is used. # importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # extracting 5 rowsshort_data = data.head().copy() # calling str.index() methodtry: short_data["Index Name"]= short_data["Name"].str.index("a")except Exception as err: print(err) # displayshort_data Output:As shown in output image, the output data frame is not having the Index Name column and the error “substring not found” was printed. That is because str.index() returns valueError on not found and hence it must have gone to except case and printed the error. Akanksha_Rai Python pandas-series Python pandas-series-methods Python-pandas Python-pandas-series-str Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jul, 2020" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 529, "s": 242, "text": "Pandas str.index() method is used to search and return lowest index of a substring in particular section (Between start and end) of every string in a series. This method works in a similar way to str.find() but on not found case, instead of returning -1, str.index() gives a ValueError." }, { "code": null, "e": 578, "s": 529, "text": "Syntax: Series.str.index(sub, start=0, end=None)" }, { "code": null, "e": 793, "s": 578, "text": "Parameters:sub: String or character to be searched in the text value in seriesstart: String or character to be searched in the text value in seriesend: String or character to be searched in the text value in series" }, { "code": null, "e": 853, "s": 793, "text": "Return type: Series with least index of substring if found." }, { "code": null, "e": 1063, "s": 853, "text": "To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 1127, "s": 1063, "text": "Example #1: Finding index when substring exists in every string" }, { "code": null, "e": 1330, "s": 1127, "text": "In this example, ‘e’ is passed as substring. Since ‘e’ exists in all 5 strings, least index of it’s occurrence is returned. Before applying any operations, null rows were removed using .dropna() method." }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # extracting 5 rowsshort_data = data.head().copy() # calling str.index() methodshort_data[\"Index Name\"]= short_data[\"Name\"].str.index(\"e\") # displayshort_data", "e": 1723, "s": 1330, "text": null }, { "code": null, "e": 1844, "s": 1723, "text": "Output:As shown in the output image, the least index of ‘e’ in series was returned and stored in new column. Example #2:" }, { "code": null, "e": 2004, "s": 1844, "text": "In this example, ‘a’ is searched in top 5 rows. Since ‘a’ doesn’t exist in every string, value error will be returned. To handle error, try and except is used." }, { "code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # extracting 5 rowsshort_data = data.head().copy() # calling str.index() methodtry: short_data[\"Index Name\"]= short_data[\"Name\"].str.index(\"a\")except Exception as err: print(err) # displayshort_data", "e": 2447, "s": 2004, "text": null }, { "code": null, "e": 2713, "s": 2447, "text": "Output:As shown in output image, the output data frame is not having the Index Name column and the error “substring not found” was printed. That is because str.index() returns valueError on not found and hence it must have gone to except case and printed the error." }, { "code": null, "e": 2726, "s": 2713, "text": "Akanksha_Rai" }, { "code": null, "e": 2747, "s": 2726, "text": "Python pandas-series" }, { "code": null, "e": 2776, "s": 2747, "text": "Python pandas-series-methods" }, { "code": null, "e": 2790, "s": 2776, "text": "Python-pandas" }, { "code": null, "e": 2815, "s": 2790, "text": "Python-pandas-series-str" }, { "code": null, "e": 2822, "s": 2815, "text": "Python" } ]
HTML | Window resizeTo() Method
26 Jul, 2019 The resizeTo() method is used to resizes a window to the specified width and height. Syntax: window.resizeTo(width, height) Parameter Values: width: Sets the width of the window, in pixels. height: Sets the height of the window, in pixels. Example: Resize the window. <!DOCTYPE html><html> <head> <title> Window resizeTo() Method </title> <style> h1 { color: green; } </style> </head> <body> <center> <h1>Geeks for Geeks</h1> <button onclick="openWin()"> New window </button> <button onclick="resizeWin()"> Resize window </button> <script> var myWindow; function openWin() { myWindow = window.open("", "", "width=100, height=100"); } function resizeWin() { myWindow.resizeTo(300, 300); myWindow.focus(); } </script> </center></body> </html> Output:Initial:New window:Resize window: Supported Browsers: The browser supported by Window resizeTo() Method are listed below: Google Chrome Internet Explorer Mozilla Firefox Opera Safari HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Jul, 2019" }, { "code": null, "e": 138, "s": 53, "text": "The resizeTo() method is used to resizes a window to the specified width and height." }, { "code": null, "e": 146, "s": 138, "text": "Syntax:" }, { "code": null, "e": 177, "s": 146, "text": "window.resizeTo(width, height)" }, { "code": null, "e": 195, "s": 177, "text": "Parameter Values:" }, { "code": null, "e": 243, "s": 195, "text": "width: Sets the width of the window, in pixels." }, { "code": null, "e": 293, "s": 243, "text": "height: Sets the height of the window, in pixels." }, { "code": null, "e": 321, "s": 293, "text": "Example: Resize the window." }, { "code": "<!DOCTYPE html><html> <head> <title> Window resizeTo() Method </title> <style> h1 { color: green; } </style> </head> <body> <center> <h1>Geeks for Geeks</h1> <button onclick=\"openWin()\"> New window </button> <button onclick=\"resizeWin()\"> Resize window </button> <script> var myWindow; function openWin() { myWindow = window.open(\"\", \"\", \"width=100, height=100\"); } function resizeWin() { myWindow.resizeTo(300, 300); myWindow.focus(); } </script> </center></body> </html>", "e": 1067, "s": 321, "text": null }, { "code": null, "e": 1108, "s": 1067, "text": "Output:Initial:New window:Resize window:" }, { "code": null, "e": 1196, "s": 1108, "text": "Supported Browsers: The browser supported by Window resizeTo() Method are listed below:" }, { "code": null, "e": 1210, "s": 1196, "text": "Google Chrome" }, { "code": null, "e": 1228, "s": 1210, "text": "Internet Explorer" }, { "code": null, "e": 1244, "s": 1228, "text": "Mozilla Firefox" }, { "code": null, "e": 1250, "s": 1244, "text": "Opera" }, { "code": null, "e": 1257, "s": 1250, "text": "Safari" }, { "code": null, "e": 1266, "s": 1257, "text": "HTML-DOM" }, { "code": null, "e": 1271, "s": 1266, "text": "HTML" }, { "code": null, "e": 1288, "s": 1271, "text": "Web Technologies" }, { "code": null, "e": 1293, "s": 1288, "text": "HTML" }, { "code": null, "e": 1391, "s": 1293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1415, "s": 1391, "text": "REST API (Introduction)" }, { "code": null, "e": 1454, "s": 1415, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1493, "s": 1454, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1530, "s": 1493, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 1550, "s": 1530, "text": "Angular File Upload" }, { "code": null, "e": 1583, "s": 1550, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1644, "s": 1583, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1687, "s": 1644, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1759, "s": 1687, "text": "Differences between Functional Components and Class Components in React" } ]
Java program to accept an integer from user and print it
Scanner class of the util package class is used to read data from user The nextInt() method of this class reads an integer from the user. import java.util.Scanner; public class PrintInteger { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter an integer:"); int num = sc.nextInt(); System.out.print("Given integer is :: "+num); } } Enter an integer: 123 Given integer is :: 123
[ { "code": null, "e": 1200, "s": 1062, "text": "Scanner class of the util package class is used to read data from user The nextInt() method of this class reads an integer from the user." }, { "code": null, "e": 1476, "s": 1200, "text": "import java.util.Scanner;\npublic class PrintInteger {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter an integer:\");\n int num = sc.nextInt();\n System.out.print(\"Given integer is :: \"+num);\n }\n}" }, { "code": null, "e": 1522, "s": 1476, "text": "Enter an integer:\n123\nGiven integer is :: 123" } ]
A Brief Introduction to Supervised Learning | by Aidan Wilson | Towards Data Science
Supervised learning is the most common subbranch of machine learning today. Typically, new machine learning practitioners will begin their journey with supervised learning algorithms. Therefore, the first of this three post series will be about supervised learning. Supervised machine learning algorithms are designed to learn by example. The name “supervised” learning originates from the idea that training this type of algorithm is like having a teacher supervise the whole process. When training a supervised learning algorithm, the training data will consist of inputs paired with the correct outputs. During training, the algorithm will search for patterns in the data that correlate with the desired outputs. After training, a supervised learning algorithm will take in new unseen inputs and will determine which label the new inputs will be classified as based on prior training data. The objective of a supervised learning model is to predict the correct label for newly presented input data. At its most basic form, a supervised learning algorithm can be written simply as: Where Y is the predicted output that is determined by a mapping function that assigns a class to an input value x. The function used to connect input features to a predicted output is created by the machine learning model during training. Supervised learning can be split into two subcategories: Classification and regression. During training, a classification algorithm will be given data points with an assigned category. The job of a classification algorithm is to then take an input value and assign it a class, or category, that it fits into based on the training data provided. The most common example of classification is determining if an email is spam or not. With two classes to choose from (spam, or not spam), this problem is called a binary classification problem. The algorithm will be given training data with emails that are both spam and not spam. The model will find the features within the data that correlate to either class and create the mapping function mentioned earlier: Y=f(x). Then, when provided with an unseen email, the model will use this function to determine whether or not the email is spam. Classification problems can be solved with a numerous amount of algorithms. Whichever algorithm you choose to use depends on the data and the situation. Here are a few popular classification algorithms: Linear Classifiers Support Vector Machines Decision Trees K-Nearest Neighbor Random Forest Regression is a predictive statistical process where the model attempts to find the important relationship between dependent and independent variables. The goal of a regression algorithm is to predict a continuous number such as sales, income, and test scores. The equation for basic linear regression can be written as so: Where x[i] is the feature(s) for the data and where w[i] and b are parameters which are developed during training. For simple linear regression models with only one feature in the data, the formula looks like this: Where w is the slope, x is the single feature and b is the y-intercept. Familiar? For simple regression problems such as this, the models predictions are represented by the line of best fit. For models using two features, the plane will be used. Finally, for a model using more than two features, a hyperplane will be used. Imagine we want to determine a student’s test grade based on how many hours they studied the week of the test. Lets say the plotted data with a line of best fit looks like this: There is a clear positive correlation between hours studied (independent variable) and the student’s final test score (dependent variable). A line of best fit can be drawn through the data points to show the models predictions when given a new input. Say we wanted to know how well a student would do with five hours of studying. We can use the line of best fit to predict the test score based on other student’s performances. There are many different types of regression algorithms. The three most common are listed below: Linear Regression Logistic Regression Polynomial Regression First we will import the needed libraries and then create a random dataset with an increasing output. We can then place our line of best fit onto the plot along with all of the data points. We will then print out the slope and intercept of the regression model. print("Slope: ", reg.coef_[0])print("Intercept:", reg.intercept_) Output: Slope: 65.54726684409927Intercept: -1.8464500230055103 In middle school, we all learned that the equation for a linear line is y = mx + b. We can now create a function called “predict” that will multiply the slope (w) with the new input (x). This function will also use the intercept (b) to return an output value. After creating the function, we can predict the output values when x = 3 and when x = -1.5. Predict y For 3: 194.7953505092923Predict y For -1.5: -100.16735028915441 Now let’s plot the original data points with the line of best fit. We can then add the new points that we predicted (colored red). As expected, they fall on the line of best fit. Supervised learning is the simplest subcategory of machine learning and serves as an introduction to machine learning to many machine learning practitioners. Supervised learning is the most commonly used form of machine learning, and has proven to be an excellent tool in many fields. This post was part one of a three part series. Part two will cover unsupervised learning.
[ { "code": null, "e": 313, "s": 47, "text": "Supervised learning is the most common subbranch of machine learning today. Typically, new machine learning practitioners will begin their journey with supervised learning algorithms. Therefore, the first of this three post series will be about supervised learning." }, { "code": null, "e": 533, "s": 313, "text": "Supervised machine learning algorithms are designed to learn by example. The name “supervised” learning originates from the idea that training this type of algorithm is like having a teacher supervise the whole process." }, { "code": null, "e": 1131, "s": 533, "text": "When training a supervised learning algorithm, the training data will consist of inputs paired with the correct outputs. During training, the algorithm will search for patterns in the data that correlate with the desired outputs. After training, a supervised learning algorithm will take in new unseen inputs and will determine which label the new inputs will be classified as based on prior training data. The objective of a supervised learning model is to predict the correct label for newly presented input data. At its most basic form, a supervised learning algorithm can be written simply as:" }, { "code": null, "e": 1370, "s": 1131, "text": "Where Y is the predicted output that is determined by a mapping function that assigns a class to an input value x. The function used to connect input features to a predicted output is created by the machine learning model during training." }, { "code": null, "e": 1458, "s": 1370, "text": "Supervised learning can be split into two subcategories: Classification and regression." }, { "code": null, "e": 1715, "s": 1458, "text": "During training, a classification algorithm will be given data points with an assigned category. The job of a classification algorithm is to then take an input value and assign it a class, or category, that it fits into based on the training data provided." }, { "code": null, "e": 2257, "s": 1715, "text": "The most common example of classification is determining if an email is spam or not. With two classes to choose from (spam, or not spam), this problem is called a binary classification problem. The algorithm will be given training data with emails that are both spam and not spam. The model will find the features within the data that correlate to either class and create the mapping function mentioned earlier: Y=f(x). Then, when provided with an unseen email, the model will use this function to determine whether or not the email is spam." }, { "code": null, "e": 2460, "s": 2257, "text": "Classification problems can be solved with a numerous amount of algorithms. Whichever algorithm you choose to use depends on the data and the situation. Here are a few popular classification algorithms:" }, { "code": null, "e": 2479, "s": 2460, "text": "Linear Classifiers" }, { "code": null, "e": 2503, "s": 2479, "text": "Support Vector Machines" }, { "code": null, "e": 2518, "s": 2503, "text": "Decision Trees" }, { "code": null, "e": 2537, "s": 2518, "text": "K-Nearest Neighbor" }, { "code": null, "e": 2551, "s": 2537, "text": "Random Forest" }, { "code": null, "e": 2875, "s": 2551, "text": "Regression is a predictive statistical process where the model attempts to find the important relationship between dependent and independent variables. The goal of a regression algorithm is to predict a continuous number such as sales, income, and test scores. The equation for basic linear regression can be written as so:" }, { "code": null, "e": 3090, "s": 2875, "text": "Where x[i] is the feature(s) for the data and where w[i] and b are parameters which are developed during training. For simple linear regression models with only one feature in the data, the formula looks like this:" }, { "code": null, "e": 3414, "s": 3090, "text": "Where w is the slope, x is the single feature and b is the y-intercept. Familiar? For simple regression problems such as this, the models predictions are represented by the line of best fit. For models using two features, the plane will be used. Finally, for a model using more than two features, a hyperplane will be used." }, { "code": null, "e": 3592, "s": 3414, "text": "Imagine we want to determine a student’s test grade based on how many hours they studied the week of the test. Lets say the plotted data with a line of best fit looks like this:" }, { "code": null, "e": 4019, "s": 3592, "text": "There is a clear positive correlation between hours studied (independent variable) and the student’s final test score (dependent variable). A line of best fit can be drawn through the data points to show the models predictions when given a new input. Say we wanted to know how well a student would do with five hours of studying. We can use the line of best fit to predict the test score based on other student’s performances." }, { "code": null, "e": 4116, "s": 4019, "text": "There are many different types of regression algorithms. The three most common are listed below:" }, { "code": null, "e": 4134, "s": 4116, "text": "Linear Regression" }, { "code": null, "e": 4154, "s": 4134, "text": "Logistic Regression" }, { "code": null, "e": 4176, "s": 4154, "text": "Polynomial Regression" }, { "code": null, "e": 4278, "s": 4176, "text": "First we will import the needed libraries and then create a random dataset with an increasing output." }, { "code": null, "e": 4366, "s": 4278, "text": "We can then place our line of best fit onto the plot along with all of the data points." }, { "code": null, "e": 4438, "s": 4366, "text": "We will then print out the slope and intercept of the regression model." }, { "code": null, "e": 4507, "s": 4438, "text": "print(\"Slope: \", reg.coef_[0])print(\"Intercept:\", reg.intercept_)" }, { "code": null, "e": 4515, "s": 4507, "text": "Output:" }, { "code": null, "e": 4574, "s": 4515, "text": "Slope: 65.54726684409927Intercept: -1.8464500230055103" }, { "code": null, "e": 4926, "s": 4574, "text": "In middle school, we all learned that the equation for a linear line is y = mx + b. We can now create a function called “predict” that will multiply the slope (w) with the new input (x). This function will also use the intercept (b) to return an output value. After creating the function, we can predict the output values when x = 3 and when x = -1.5." }, { "code": null, "e": 5006, "s": 4926, "text": "Predict y For 3: 194.7953505092923Predict y For -1.5: -100.16735028915441" }, { "code": null, "e": 5185, "s": 5006, "text": "Now let’s plot the original data points with the line of best fit. We can then add the new points that we predicted (colored red). As expected, they fall on the line of best fit." } ]
Java 8 Clock offset() method with Examples - GeeksforGeeks
10 Dec, 2018 Java Clock class is part of Date Time API, java.time.Clock, of Java. The Java Date Time API was added from Java version 8. The offset() method is a static method of Clock class which returns a clock with instant equal to the sum of the instants of clock passed as parameter and specific Offset duration. If the duration added is positive, then the returned clock represents the instant of the clock later by the specified duration from base clock. If the duration added is negative, then the returned clock is earlier than the date and time of the base clock. A duration of Zero does nothing to the base clock and returns the base clock. If the base clock is immutable, thread-safe and Serializable then returned clock is also immutable, thread-safe and Serializable. Syntax: public static Clock offset(Clock baseClock, Duration offsetDuration) Parameters: This method accepts two mandatory parameters: baseclock – a clock for adding duration. It cannot be a null value. offsetDuration – duration to add with baseClock. It cannot be a null value as well. Return Value: This method returns a clock with instant equal to the sum of instants of clock passed as parameter and Specific Offset duration. Below programs illustrates offset(Clock baseClock, Duration offsetDuration) method of java.time.Clock class: Program 1: When offset is passed as hours. // Java program to demonstrate offset()// method of Clock class import java.time.*; // create classpublic class offsetMethodDemo { // Main method public static void main(String[] args) { // base Clock with default zone Clock realClock = Clock.systemDefaultZone(); // print current time System.out.println("Real clock instant is " + realClock.instant()); // Creating another clock with offset 0 Clock clock = Clock.offset(realClock, Duration.ZERO); // print new clock System.out.println("New clock instant" + " with Duration = 0 is " + clock.instant()); // Creating the clock with 24 hours positive offset clock = Clock.offset(realClock, Duration.ofHours(24)); // print new clock System.out.println("New clock instant" + " with Duration = 24hours is " + clock.instant()); // Creating the clock with 24 hours negative offset clock = Clock.offset(realClock, Duration.ofHours(-24)); // print new clock System.out.println("New clock instant" + " with Duration = -24hours is " + clock.instant()); }} Real clock instant is 2018-08-21T09:43:13.519Z New clock instant with Duration = 0 is 2018-08-21T09:43:13.785Z New clock instant with Duration = 24hours is 2018-08-22T09:43:13.785Z New clock instant with Duration = -24hours is 2018-08-20T09:43:13.785Z Program 2: When offset is passed as seconds and minutes. // Java program to demonstrate offset() // method of Clock class import java.time.*; // create classpublic class offsetMethodDemo { // Main method public static void main(String[] args) { // create a Zone Id for Europe/Paris ZoneId zoneId = ZoneId.of("Europe/Paris"); // base Clock with default zone Clock realClock = Clock.system(zoneId); // print current time System.out.println("Real clock instant is " + realClock.instant()); // Creating the clock with 50 seconds positive offset Clock clock = Clock.offset(realClock, Duration.ofSeconds(50)); // print new clock System.out.println("Time after 50 second later" + " than real Clock is " + clock.instant()); // Creating the clock with 30 minutes positive offset clock = Clock.offset(realClock, Duration.ofMinutes(30)); // print new clock System.out.println("Time after 30 minutes later" + " than real Clock is " + clock.instant()); }} Real clock instant is 2018-08-21T09:43:18.921Z Time after 50 second later than real Clock is 2018-08-21T09:44:08.969Z Time after 30 minutes later than real Clock is 2018-08-21T10:13:18.969Z Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#offset-java.time.Clock-java.time.Duration- java-basics Java-Clock Java-Functions Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java LinkedList in Java Set in Java
[ { "code": null, "e": 24498, "s": 24470, "text": "\n10 Dec, 2018" }, { "code": null, "e": 24621, "s": 24498, "text": "Java Clock class is part of Date Time API, java.time.Clock, of Java. The Java Date Time API was added from Java version 8." }, { "code": null, "e": 25136, "s": 24621, "text": "The offset() method is a static method of Clock class which returns a clock with instant equal to the sum of the instants of clock passed as parameter and specific Offset duration. If the duration added is positive, then the returned clock represents the instant of the clock later by the specified duration from base clock. If the duration added is negative, then the returned clock is earlier than the date and time of the base clock. A duration of Zero does nothing to the base clock and returns the base clock." }, { "code": null, "e": 25266, "s": 25136, "text": "If the base clock is immutable, thread-safe and Serializable then returned clock is also immutable, thread-safe and Serializable." }, { "code": null, "e": 25274, "s": 25266, "text": "Syntax:" }, { "code": null, "e": 25343, "s": 25274, "text": "public static Clock offset(Clock baseClock, Duration offsetDuration)" }, { "code": null, "e": 25401, "s": 25343, "text": "Parameters: This method accepts two mandatory parameters:" }, { "code": null, "e": 25469, "s": 25401, "text": "baseclock – a clock for adding duration. It cannot be a null value." }, { "code": null, "e": 25553, "s": 25469, "text": "offsetDuration – duration to add with baseClock. It cannot be a null value as well." }, { "code": null, "e": 25696, "s": 25553, "text": "Return Value: This method returns a clock with instant equal to the sum of instants of clock passed as parameter and Specific Offset duration." }, { "code": null, "e": 25805, "s": 25696, "text": "Below programs illustrates offset(Clock baseClock, Duration offsetDuration) method of java.time.Clock class:" }, { "code": null, "e": 25848, "s": 25805, "text": "Program 1: When offset is passed as hours." }, { "code": "// Java program to demonstrate offset()// method of Clock class import java.time.*; // create classpublic class offsetMethodDemo { // Main method public static void main(String[] args) { // base Clock with default zone Clock realClock = Clock.systemDefaultZone(); // print current time System.out.println(\"Real clock instant is \" + realClock.instant()); // Creating another clock with offset 0 Clock clock = Clock.offset(realClock, Duration.ZERO); // print new clock System.out.println(\"New clock instant\" + \" with Duration = 0 is \" + clock.instant()); // Creating the clock with 24 hours positive offset clock = Clock.offset(realClock, Duration.ofHours(24)); // print new clock System.out.println(\"New clock instant\" + \" with Duration = 24hours is \" + clock.instant()); // Creating the clock with 24 hours negative offset clock = Clock.offset(realClock, Duration.ofHours(-24)); // print new clock System.out.println(\"New clock instant\" + \" with Duration = -24hours is \" + clock.instant()); }}", "e": 27168, "s": 25848, "text": null }, { "code": null, "e": 27421, "s": 27168, "text": "Real clock instant is 2018-08-21T09:43:13.519Z\nNew clock instant with Duration = 0 is 2018-08-21T09:43:13.785Z\nNew clock instant with Duration = 24hours is 2018-08-22T09:43:13.785Z\nNew clock instant with Duration = -24hours is 2018-08-20T09:43:13.785Z\n" }, { "code": null, "e": 27478, "s": 27421, "text": "Program 2: When offset is passed as seconds and minutes." }, { "code": "// Java program to demonstrate offset() // method of Clock class import java.time.*; // create classpublic class offsetMethodDemo { // Main method public static void main(String[] args) { // create a Zone Id for Europe/Paris ZoneId zoneId = ZoneId.of(\"Europe/Paris\"); // base Clock with default zone Clock realClock = Clock.system(zoneId); // print current time System.out.println(\"Real clock instant is \" + realClock.instant()); // Creating the clock with 50 seconds positive offset Clock clock = Clock.offset(realClock, Duration.ofSeconds(50)); // print new clock System.out.println(\"Time after 50 second later\" + \" than real Clock is \" + clock.instant()); // Creating the clock with 30 minutes positive offset clock = Clock.offset(realClock, Duration.ofMinutes(30)); // print new clock System.out.println(\"Time after 30 minutes later\" + \" than real Clock is \" + clock.instant()); }}", "e": 28570, "s": 27478, "text": null }, { "code": null, "e": 28761, "s": 28570, "text": "Real clock instant is 2018-08-21T09:43:18.921Z\nTime after 50 second later than real Clock is 2018-08-21T09:44:08.969Z\nTime after 30 minutes later than real Clock is 2018-08-21T10:13:18.969Z\n" }, { "code": null, "e": 28878, "s": 28761, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#offset-java.time.Clock-java.time.Duration-" }, { "code": null, "e": 28890, "s": 28878, "text": "java-basics" }, { "code": null, "e": 28901, "s": 28890, "text": "Java-Clock" }, { "code": null, "e": 28916, "s": 28901, "text": "Java-Functions" }, { "code": null, "e": 28934, "s": 28916, "text": "Java-time package" }, { "code": null, "e": 28939, "s": 28934, "text": "Java" }, { "code": null, "e": 28944, "s": 28939, "text": "Java" }, { "code": null, "e": 29042, "s": 28944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29051, "s": 29042, "text": "Comments" }, { "code": null, "e": 29064, "s": 29051, "text": "Old Comments" }, { "code": null, "e": 29096, "s": 29064, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29126, "s": 29096, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29145, "s": 29126, "text": "Interfaces in Java" }, { "code": null, "e": 29196, "s": 29145, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29227, "s": 29196, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29245, "s": 29227, "text": "ArrayList in Java" }, { "code": null, "e": 29277, "s": 29245, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29297, "s": 29277, "text": "Stack Class in Java" }, { "code": null, "e": 29316, "s": 29297, "text": "LinkedList in Java" } ]
How to get the difference between two dates in Android?
This example demonstrates how do I get the difference between two dates 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"?> <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:textSize="16sp" android:textStyle="bold|italic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity{ TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); try { String CurrentDate= "09/24/2018"; String FinalDate= "09/26/2019"; Date date1; Date date2; SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy"); date1 = dates.parse(CurrentDate); date2 = dates.parse(FinalDate); long difference = Math.abs(date1.getTime() - date2.getTime()); long differenceDates = difference / (24 * 60 * 60 * 1000); String dayDifference = Long.toString(differenceDates); textView.setText("The difference between two dates is " + dayDifference + " days"); } catch (Exception exception) { Toast.makeText(this, "Unable to find difference", Toast.LENGTH_SHORT).show(); } } } 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": 1146, "s": 1062, "text": "This example demonstrates how do I get the difference between two dates in android." }, { "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": 1879, "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:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 1936, "s": 1879, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3134, "s": 1936, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class MainActivity extends AppCompatActivity{\n TextView textView;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n try {\n String CurrentDate= \"09/24/2018\";\n String FinalDate= \"09/26/2019\";\n Date date1;\n Date date2;\n SimpleDateFormat dates = new SimpleDateFormat(\"MM/dd/yyyy\");\n date1 = dates.parse(CurrentDate);\n date2 = dates.parse(FinalDate);\n long difference = Math.abs(date1.getTime() - date2.getTime());\n long differenceDates = difference / (24 * 60 * 60 * 1000);\n String dayDifference = Long.toString(differenceDates);\n textView.setText(\"The difference between two dates is \" + dayDifference + \" days\");\n } catch (Exception exception) {\n Toast.makeText(this, \"Unable to find difference\", Toast.LENGTH_SHORT).show();\n }\n }\n}" }, { "code": null, "e": 3190, "s": 3134, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3860, "s": 3190, "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": 4207, "s": 3860, "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": 4248, "s": 4207, "text": "Click here to download the project code." } ]
Firebase Event Analytics with Google BigQuery | by Kritika Jalan | Towards Data Science
I started working with Events Analytics. As most mobile apps do, this app too, was linked to Firebase for event tracking. It was difficult to follow especially because there were limited resources online around this. After 4 months of being into the system, I have some understanding and experience which I would be sharing in this easy-to-digest post on Firebase Analytics. (This post includes some information as is, directly from Google docs). Let’s get started! How beautiful is this,Sitting here at my desk,Looking out the window, and seeing the entire city,Sprawled in front of my eyes The end of concrete jungle, marked by the river,Running through the entire length of the city A world, a very different world lives across the river.Better or worse, you ask.Let’s not label everything on the scale of goodness,When all things really are, are just different. As wiki says, Firebase provides a real-time database and backend as a service. The service provides application developers an API that allows application data to be synchronized across clients (users basically) and stored on Firebase’s cloud. At the heart of Firebase is Google Analytics, an analytics solution that integrates across Firebase features and provides with reporting for up to 500 distinct events that can be defined using the Firebase SDK. In short, Firebase lets you track what your users are doing on the app (events), saves it on its cloud (real-time database) and also lets you visualize this data. Below is a screenshot of a Firebase Analytics Dashboard. You can choose to see the performance for different time periods. On the dashboard, you’ll get information about your active users, about their engagement (how long they spend on which screen), about conversion event (when an in-app purchase is made, for example), your audience’s geography, their retention, mobile platform and a lot more details. As Google’s documentation says, events provide insight on what is happening in your app, such as user actions, system events, or errors. There are some events (and user properties) that Firebase tracks automatically, for example the event of app first opened after it was installed, the notification dismissed event, the OS update or an app update event etc. Apart from the automatic events, developers can create their own events to track user activity or system events/errors. There is no limit on the total volume of events your app logs. For example, if you’re a dating app, you can choose to record an event when a user swipes right on someone, or when a user changes their search preferences from a radius of 5km to 500km. If you’re an e-commerce app, you can choose to record an event when user adds/removes an item from cart or when a user checks out etc. With each event, firebase lets you track a bunch of other relevant information. They can be grouped as event property (screen from which the event originated, which user ID was swiped right, what new search distance was set etc.), user property (user ID , their age, gender etc.), device property (device type, brand, model, OS, language etc.), location property (where was the event originated country, region, city etc.), app property (app version, store through which the app was installed) etc. If you need answers to questions which Firebase dashboard doesn’t provide, you can connect your Analytics data to BigQuery, which allows for more complex analysis like querying large data sets, joining with other data sources, creating business reports etc. That is what we will be talking about next. Since you want to import your raw data from Firebase to BigQuery, you would likely be interested in doing user level analysis and for this, you must add User ID in order to track user across platform and devices. Why? Firebase doesn’t identify unique users on your platform. All it does is track activity across unique app instances called user_pseudo_id. This means, if you uninstall your dating app and reinstall it, if you change your device or if you are using multiple apps from the same provider, Firebase doesn’t have an automatic way of informing that it’s all just one user. To have the ability of identifying an individual on your platform, you need to set user IDs for them on your own. After setting the user ID, all your events will be automatically tagged by this value. Questions! How do I set user ID? How do I connect data from Firebase to BigQuery? Answer — Well, this isn’t something you will do as a data scientist. The app developer is better equipped to do it all for you. Here is the guide from Google they can use to connect Firebase data to BigQuery. Now that we have our raw data pushed into BQ, let’s hop on to BigQuery to see how we can work with it! (I know it looks scary :p) I had never before seen a table with repeated records, and this one was it. A few things to know about the exported data - After linking a BQ project with firebase, the first export creates a dataset named analytics_xxx where x represents your Analytics Property ID (don’t worry about this). In this dataset, a table is exported for each day (BQ tables partitioned by date) named events_YYYYMMDD You also see an events_intraday_<date> table which is the real-time table getting updated with raw events for today. Since the table is partitioned by day, you can either query a single table for a particular day or filter for multiple tables usingFROM analytics_xxxxxxxxx.events_20200131 OR FROM analytics_xxxxxxxxx.events_* WHERE _table_suffix BETWEEN ‘20190201’ AND ‘20200131’ These tables are event level tables with repeated records for event properties, user properties, device properties etc. What this means is, for each event there’s going to be multiple event properties which will be saved as key, value pairs (an array) instead of in a flat table format, as shown below. Due to this structure, two things happen, You won’t be able to query the DB using regular SQL. For example, when you want to filter your engagement events for user_gender property, you will not be able to simply write where user_gender = ‘Male’ You won’t be able to export this kind of table structure into Google Sheets or on your local. To deal with this table format, let’s talk about some querying style and functions. As you might have guessed it, the unnest function helps in flattening our confusing (at first) table. The UNNEST function takes an array and breaks it out into each of its individual elements. For example, the query to count male users on your app for the week of 20th Jan will look something like - SELECT count(DISTINCT user_id) FROM (SELECT user_id, (SELECT value.string_value FROM UNNEST(user_properties) WHERE key = “user_gender”) AS gender FROM analytics_xxxxxxxxx.events_*` WHERE _table_suffix BETWEEN ‘20200120’ AND ‘20200126’ ) WHERE gender = “Male” Here, the UNNEST function took the array user_properties and unfolded it. From all the key, value pairs for user properties then, we filtered for user_gender and extracted the string value where we had saved ‘Male’ and ‘Female’. We called this extraction as gender and then finally filtered for Male here in the enclosing query. While creating a report which involves multiple steps say when calculating retention, you will need to create a few intermediate tables before you can finally write select users, their day-7 retention for a period of 30 days from table x Now, BigQuery isn’t SAS or Python where you can write multiple steps and run them all at once. The platform only runs one query at a time. So here’s to your rescue the with..as style. It lets you create multiple table within the same query using table aliases. For example retention - withcohort_items as (SELECT user_pseudo_id, MIN( TIMESTAMP_TRUNC(TIMESTAMP_MICROS(event_timestamp), DAY)) as cohort_day FROM analytics_xxx.events_* WHERE _table_suffix BETWEEN ‘20170101’ AND ‘20191231’ AND event_name = ‘first_open’ GROUP BY 1 ), user_activites AS (SELECT A.user_pseudo_id, DATE(C.cohort_day) as cohort_day,DATE_DIFF(DATE(TIMESTAMP_TRUNC(TIMESTAMP_MICROS(event_timestamp), DAY)), DATE(C.cohort_day), DAY) AS day_number FROM analytics_xxx.events_* ALEFT JOIN cohort_items C ON A.user_pseudo_id = C.user_pseudo_idWHERE _table_suffix BETWEEN ‘20170101’ AND ‘20191231’GROUP BY 1,2,3),cohort_size AS ( SELECT cohort_day, count(1) as number_of_users FROM cohort_items GROUP BY 1 ),retention_table AS(SELECT C.cohort_day, A.day_number, COUNT(1) AS number_of_usersFROM user_activites ALEFT JOIN cohort_items C ON A.user_pseudo_id = C.user_pseudo_idGROUP BY 1,2)SELECTB.cohort_day, ifnull(B.number_of_users,0) as total_users,B.day_number, safe_divide((ifnull(B.number_of_users,0)), S.number_of_users) as retention,FROM retention_table BLEFT JOIN cohort_size S ON B.cohort_day = S.cohort_dayWHERE B.cohort_day IS NOT NULL and B.day_number >= 0 and B.day_number < 31) Here, we created 3 intermediate tables named cohort_items, user_activities and retention_table before we could use them all to aggregate and get our final retention table. cohort_items — Identifying the new user cohort based on the date they first opened the application user_activities — For these identified users, getting their daily activity on the app. If a user logged single event on firebase, we consider them active for that day. retention_table — Aggregating the above table on day level (cohort_day) and identifying for each day (day_number), how many users were retained on day 0, day 1, day 7, . . . upto day n. Finally, in the last select statement, we calculate the retention percent for each cohort day and day_number combination and keep only day 0 to day 30 retentions. After you start creating reports using exported data in BigQuery, you’ll encounter discrepancy between Analytics and your reports. You can use the following best practices to get better results: Use the table for a specific day instead of using a date comparison on the event timestamp in the WHERE clause. The event timestamp is based on client device time, which is often skewed.Never compare events like session_start or user_engagement that are triggered quite often.If any query runs out of allocated resources, remove the ORDER BY clause since it is a quite expensive operation and cannot be processed in parallel so try to avoid it (or try applying it in a limited result set)Always get a report past 3 days so that the data exported from GA4F to BigQuery gets normalized. Data is only exported to BigQuery once per day. And so, queries which include the most recent three days will show different results between Firebase Analytics and BigQuery. Use the table for a specific day instead of using a date comparison on the event timestamp in the WHERE clause. The event timestamp is based on client device time, which is often skewed. Never compare events like session_start or user_engagement that are triggered quite often. If any query runs out of allocated resources, remove the ORDER BY clause since it is a quite expensive operation and cannot be processed in parallel so try to avoid it (or try applying it in a limited result set) Always get a report past 3 days so that the data exported from GA4F to BigQuery gets normalized. Data is only exported to BigQuery once per day. And so, queries which include the most recent three days will show different results between Firebase Analytics and BigQuery. I hope this post helped you learn a bit about Firebase Analytics. There will be more posts following this one to talk about more specific tasks like using events data to map user behaviour, create user journey etc. If you have any questions/suggestions, feel free to reach out with your comments and connect with me on LinkedIn, or Twitter
[ { "code": null, "e": 637, "s": 171, "text": "I started working with Events Analytics. As most mobile apps do, this app too, was linked to Firebase for event tracking. It was difficult to follow especially because there were limited resources online around this. After 4 months of being into the system, I have some understanding and experience which I would be sharing in this easy-to-digest post on Firebase Analytics. (This post includes some information as is, directly from Google docs). Let’s get started!" }, { "code": null, "e": 763, "s": 637, "text": "How beautiful is this,Sitting here at my desk,Looking out the window, and seeing the entire city,Sprawled in front of my eyes" }, { "code": null, "e": 857, "s": 763, "text": "The end of concrete jungle, marked by the river,Running through the entire length of the city" }, { "code": null, "e": 1037, "s": 857, "text": "A world, a very different world lives across the river.Better or worse, you ask.Let’s not label everything on the scale of goodness,When all things really are, are just different." }, { "code": null, "e": 1280, "s": 1037, "text": "As wiki says, Firebase provides a real-time database and backend as a service. The service provides application developers an API that allows application data to be synchronized across clients (users basically) and stored on Firebase’s cloud." }, { "code": null, "e": 1491, "s": 1280, "text": "At the heart of Firebase is Google Analytics, an analytics solution that integrates across Firebase features and provides with reporting for up to 500 distinct events that can be defined using the Firebase SDK." }, { "code": null, "e": 1654, "s": 1491, "text": "In short, Firebase lets you track what your users are doing on the app (events), saves it on its cloud (real-time database) and also lets you visualize this data." }, { "code": null, "e": 2060, "s": 1654, "text": "Below is a screenshot of a Firebase Analytics Dashboard. You can choose to see the performance for different time periods. On the dashboard, you’ll get information about your active users, about their engagement (how long they spend on which screen), about conversion event (when an in-app purchase is made, for example), your audience’s geography, their retention, mobile platform and a lot more details." }, { "code": null, "e": 2197, "s": 2060, "text": "As Google’s documentation says, events provide insight on what is happening in your app, such as user actions, system events, or errors." }, { "code": null, "e": 2419, "s": 2197, "text": "There are some events (and user properties) that Firebase tracks automatically, for example the event of app first opened after it was installed, the notification dismissed event, the OS update or an app update event etc." }, { "code": null, "e": 2924, "s": 2419, "text": "Apart from the automatic events, developers can create their own events to track user activity or system events/errors. There is no limit on the total volume of events your app logs. For example, if you’re a dating app, you can choose to record an event when a user swipes right on someone, or when a user changes their search preferences from a radius of 5km to 500km. If you’re an e-commerce app, you can choose to record an event when user adds/removes an item from cart or when a user checks out etc." }, { "code": null, "e": 3423, "s": 2924, "text": "With each event, firebase lets you track a bunch of other relevant information. They can be grouped as event property (screen from which the event originated, which user ID was swiped right, what new search distance was set etc.), user property (user ID , their age, gender etc.), device property (device type, brand, model, OS, language etc.), location property (where was the event originated country, region, city etc.), app property (app version, store through which the app was installed) etc." }, { "code": null, "e": 3725, "s": 3423, "text": "If you need answers to questions which Firebase dashboard doesn’t provide, you can connect your Analytics data to BigQuery, which allows for more complex analysis like querying large data sets, joining with other data sources, creating business reports etc. That is what we will be talking about next." }, { "code": null, "e": 3943, "s": 3725, "text": "Since you want to import your raw data from Firebase to BigQuery, you would likely be interested in doing user level analysis and for this, you must add User ID in order to track user across platform and devices. Why?" }, { "code": null, "e": 4510, "s": 3943, "text": "Firebase doesn’t identify unique users on your platform. All it does is track activity across unique app instances called user_pseudo_id. This means, if you uninstall your dating app and reinstall it, if you change your device or if you are using multiple apps from the same provider, Firebase doesn’t have an automatic way of informing that it’s all just one user. To have the ability of identifying an individual on your platform, you need to set user IDs for them on your own. After setting the user ID, all your events will be automatically tagged by this value." }, { "code": null, "e": 4904, "s": 4510, "text": "Questions! How do I set user ID? How do I connect data from Firebase to BigQuery? Answer — Well, this isn’t something you will do as a data scientist. The app developer is better equipped to do it all for you. Here is the guide from Google they can use to connect Firebase data to BigQuery. Now that we have our raw data pushed into BQ, let’s hop on to BigQuery to see how we can work with it!" }, { "code": null, "e": 4931, "s": 4904, "text": "(I know it looks scary :p)" }, { "code": null, "e": 5054, "s": 4931, "text": "I had never before seen a table with repeated records, and this one was it. A few things to know about the exported data -" }, { "code": null, "e": 5223, "s": 5054, "text": "After linking a BQ project with firebase, the first export creates a dataset named analytics_xxx where x represents your Analytics Property ID (don’t worry about this)." }, { "code": null, "e": 5327, "s": 5223, "text": "In this dataset, a table is exported for each day (BQ tables partitioned by date) named events_YYYYMMDD" }, { "code": null, "e": 5444, "s": 5327, "text": "You also see an events_intraday_<date> table which is the real-time table getting updated with raw events for today." }, { "code": null, "e": 5708, "s": 5444, "text": "Since the table is partitioned by day, you can either query a single table for a particular day or filter for multiple tables usingFROM analytics_xxxxxxxxx.events_20200131 OR FROM analytics_xxxxxxxxx.events_* WHERE _table_suffix BETWEEN ‘20190201’ AND ‘20200131’" }, { "code": null, "e": 6011, "s": 5708, "text": "These tables are event level tables with repeated records for event properties, user properties, device properties etc. What this means is, for each event there’s going to be multiple event properties which will be saved as key, value pairs (an array) instead of in a flat table format, as shown below." }, { "code": null, "e": 6053, "s": 6011, "text": "Due to this structure, two things happen," }, { "code": null, "e": 6256, "s": 6053, "text": "You won’t be able to query the DB using regular SQL. For example, when you want to filter your engagement events for user_gender property, you will not be able to simply write where user_gender = ‘Male’" }, { "code": null, "e": 6350, "s": 6256, "text": "You won’t be able to export this kind of table structure into Google Sheets or on your local." }, { "code": null, "e": 6434, "s": 6350, "text": "To deal with this table format, let’s talk about some querying style and functions." }, { "code": null, "e": 6734, "s": 6434, "text": "As you might have guessed it, the unnest function helps in flattening our confusing (at first) table. The UNNEST function takes an array and breaks it out into each of its individual elements. For example, the query to count male users on your app for the week of 20th Jan will look something like -" }, { "code": null, "e": 6994, "s": 6734, "text": "SELECT count(DISTINCT user_id) FROM (SELECT user_id, (SELECT value.string_value FROM UNNEST(user_properties) WHERE key = “user_gender”) AS gender FROM analytics_xxxxxxxxx.events_*` WHERE _table_suffix BETWEEN ‘20200120’ AND ‘20200126’ ) WHERE gender = “Male”" }, { "code": null, "e": 7323, "s": 6994, "text": "Here, the UNNEST function took the array user_properties and unfolded it. From all the key, value pairs for user properties then, we filtered for user_gender and extracted the string value where we had saved ‘Male’ and ‘Female’. We called this extraction as gender and then finally filtered for Male here in the enclosing query." }, { "code": null, "e": 7561, "s": 7323, "text": "While creating a report which involves multiple steps say when calculating retention, you will need to create a few intermediate tables before you can finally write select users, their day-7 retention for a period of 30 days from table x" }, { "code": null, "e": 7846, "s": 7561, "text": "Now, BigQuery isn’t SAS or Python where you can write multiple steps and run them all at once. The platform only runs one query at a time. So here’s to your rescue the with..as style. It lets you create multiple table within the same query using table aliases. For example retention -" }, { "code": null, "e": 9020, "s": 7846, "text": "withcohort_items as (SELECT user_pseudo_id, MIN( TIMESTAMP_TRUNC(TIMESTAMP_MICROS(event_timestamp), DAY)) as cohort_day FROM analytics_xxx.events_* WHERE _table_suffix BETWEEN ‘20170101’ AND ‘20191231’ AND event_name = ‘first_open’ GROUP BY 1 ), user_activites AS (SELECT A.user_pseudo_id, DATE(C.cohort_day) as cohort_day,DATE_DIFF(DATE(TIMESTAMP_TRUNC(TIMESTAMP_MICROS(event_timestamp), DAY)), DATE(C.cohort_day), DAY) AS day_number FROM analytics_xxx.events_* ALEFT JOIN cohort_items C ON A.user_pseudo_id = C.user_pseudo_idWHERE _table_suffix BETWEEN ‘20170101’ AND ‘20191231’GROUP BY 1,2,3),cohort_size AS ( SELECT cohort_day, count(1) as number_of_users FROM cohort_items GROUP BY 1 ),retention_table AS(SELECT C.cohort_day, A.day_number, COUNT(1) AS number_of_usersFROM user_activites ALEFT JOIN cohort_items C ON A.user_pseudo_id = C.user_pseudo_idGROUP BY 1,2)SELECTB.cohort_day, ifnull(B.number_of_users,0) as total_users,B.day_number, safe_divide((ifnull(B.number_of_users,0)), S.number_of_users) as retention,FROM retention_table BLEFT JOIN cohort_size S ON B.cohort_day = S.cohort_dayWHERE B.cohort_day IS NOT NULL and B.day_number >= 0 and B.day_number < 31)" }, { "code": null, "e": 9192, "s": 9020, "text": "Here, we created 3 intermediate tables named cohort_items, user_activities and retention_table before we could use them all to aggregate and get our final retention table." }, { "code": null, "e": 9291, "s": 9192, "text": "cohort_items — Identifying the new user cohort based on the date they first opened the application" }, { "code": null, "e": 9459, "s": 9291, "text": "user_activities — For these identified users, getting their daily activity on the app. If a user logged single event on firebase, we consider them active for that day." }, { "code": null, "e": 9645, "s": 9459, "text": "retention_table — Aggregating the above table on day level (cohort_day) and identifying for each day (day_number), how many users were retained on day 0, day 1, day 7, . . . upto day n." }, { "code": null, "e": 9808, "s": 9645, "text": "Finally, in the last select statement, we calculate the retention percent for each cohort day and day_number combination and keep only day 0 to day 30 retentions." }, { "code": null, "e": 10003, "s": 9808, "text": "After you start creating reports using exported data in BigQuery, you’ll encounter discrepancy between Analytics and your reports. You can use the following best practices to get better results:" }, { "code": null, "e": 10762, "s": 10003, "text": "Use the table for a specific day instead of using a date comparison on the event timestamp in the WHERE clause. The event timestamp is based on client device time, which is often skewed.Never compare events like session_start or user_engagement that are triggered quite often.If any query runs out of allocated resources, remove the ORDER BY clause since it is a quite expensive operation and cannot be processed in parallel so try to avoid it (or try applying it in a limited result set)Always get a report past 3 days so that the data exported from GA4F to BigQuery gets normalized. Data is only exported to BigQuery once per day. And so, queries which include the most recent three days will show different results between Firebase Analytics and BigQuery." }, { "code": null, "e": 10949, "s": 10762, "text": "Use the table for a specific day instead of using a date comparison on the event timestamp in the WHERE clause. The event timestamp is based on client device time, which is often skewed." }, { "code": null, "e": 11040, "s": 10949, "text": "Never compare events like session_start or user_engagement that are triggered quite often." }, { "code": null, "e": 11253, "s": 11040, "text": "If any query runs out of allocated resources, remove the ORDER BY clause since it is a quite expensive operation and cannot be processed in parallel so try to avoid it (or try applying it in a limited result set)" }, { "code": null, "e": 11524, "s": 11253, "text": "Always get a report past 3 days so that the data exported from GA4F to BigQuery gets normalized. Data is only exported to BigQuery once per day. And so, queries which include the most recent three days will show different results between Firebase Analytics and BigQuery." }, { "code": null, "e": 11739, "s": 11524, "text": "I hope this post helped you learn a bit about Firebase Analytics. There will be more posts following this one to talk about more specific tasks like using events data to map user behaviour, create user journey etc." } ]
Check if a given number is sparse or not - GeeksforGeeks
18 Jan, 2022 A number is said to be a sparse number if in binary representation of the number no two or more consecutive bits are set. Write a function to check if a given number is Sparse or not.Example : Input: x = 72 Output: true Explanation: Binary representation of 72 is 01001000. There are no two consecutive 1's in binary representation Input: x = 12 Output: false Explanation: Binary representation of 12 is 1100. Third and fourth bits (from end) are set. If we observer carefully, then we can notice that if we can use bitwise AND of binary representation of the “given number its “right shifted number”(i.e., half the given number) to figure out whether the number is sparse or not. Result of AND operator would be 0 if number is sparse and non-zero if not sparse. Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to check if n is sparse or not#include<iostream>using namespace std; // Return true if n is sparse, else falsebool checkSparse(int n){ // n is not sparse if there is set // in AND of n and n/2 if (n & (n>>1)) return false; return true;} // Driver programint main(){ cout << checkSparse(72) << endl; cout << checkSparse(12) << endl; cout << checkSparse(2) << endl; cout << checkSparse(3) << endl; return 0;} // JAVA Code to Check if a// given number is sparse or notimport java.util.*; class GFG { // Return true if n is // sparse,else false static int checkSparse(int n) { // n is not sparse if there // is set in AND of n and n/2 if ((n & (n>>1)) >=1) return 0; return 1; } // Driver code public static void main(String[] args) { System.out.println(checkSparse(72)) ; System.out.println(checkSparse(12)) ; System.out.println(checkSparse(2)) ; System.out.println(checkSparse(3)) ; } } //This code is contributed by Arnav Kr. Mandal. # Python program to check# if n is sparse or not # Return true if n is# sparse, else falsedef checkSparse(n): # n is not sparse if there is set # in AND of n and n/2 if (n & (n>>1)): return 0 return 1 # Driver codeprint(checkSparse(72))print(checkSparse(12))print(checkSparse(2))print(checkSparse(30)) # This code is contributed# by Anant Agarwal. // C# Code to Check if a given// number is sparse or notusing System; class GFG { // Return true if n is // sparse,else false static int checkSparse(int n) { // n is not sparse if there // is set in AND of n and n/2 if ((n & (n >> 1)) >= 1) return 0; return 1; } // Driver code public static void Main() { Console.WriteLine(checkSparse(72)); Console.WriteLine(checkSparse(12)); Console.WriteLine(checkSparse(2)); Console.WriteLine(checkSparse(3)); }} // This code is contributed by Sam007. <?php// PHP program to check if// n is sparse or not// Return true if n is sparse,// else false function checkSparse($n){ // n is not sparse if // there is set in AND // of n and n/2 if ($n & ($n >> 1)) return 0; return 1;} // Driver Codeecho checkSparse(72), "\n";echo checkSparse(12), "\n";echo checkSparse(2), "\n";echo checkSparse(3), "\n"; // This code is contributed by Ajit.?> <script> // Javascript program to check if n is sparse or not // Return true if n is sparse, else false function checkSparse(n) { // n is not sparse if there is set // in AND of n and n/2 if ((n & (n>>1)) > 0) return 0; return 1; } document.write(checkSparse(72) + "</br>"); document.write(checkSparse(12) + "</br>"); document.write(checkSparse(2) + "</br>"); document.write(checkSparse(3) + "</br>"); </script> Output : 1 0 1 0 Time Complexity: O(1) Auxiliary Space: O(1) Note: Instead of right shift, we could have used left shift also, but left shift might lead to overflow in some cases.This article is contributed by Vimal Vestron. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 jit_t decode2207 souravmahato348 germanshephered48 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bit Fields in C Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Find the element that appears once Bits manipulation (Important tactics) C++ bitset and its application 1's and 2's complement of a Binary Number Program to find parity Find the Number Occurring Odd Number of Times Divide two integers without using multiplication, division and mod operator
[ { "code": null, "e": 25076, "s": 25048, "text": "\n18 Jan, 2022" }, { "code": null, "e": 25270, "s": 25076, "text": "A number is said to be a sparse number if in binary representation of the number no two or more consecutive bits are set. Write a function to check if a given number is Sparse or not.Example : " }, { "code": null, "e": 25538, "s": 25270, "text": "Input: x = 72\nOutput: true\nExplanation: Binary representation of 72 is 01001000. \nThere are no two consecutive 1's in binary representation\n\nInput: x = 12\nOutput: false\nExplanation: Binary representation of 12 is 1100. \nThird and fourth bits (from end) are set." }, { "code": null, "e": 25852, "s": 25540, "text": "If we observer carefully, then we can notice that if we can use bitwise AND of binary representation of the “given number its “right shifted number”(i.e., half the given number) to figure out whether the number is sparse or not. Result of AND operator would be 0 if number is sparse and non-zero if not sparse. " }, { "code": null, "e": 25897, "s": 25852, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 25901, "s": 25897, "text": "C++" }, { "code": null, "e": 25906, "s": 25901, "text": "Java" }, { "code": null, "e": 25914, "s": 25906, "text": "Python3" }, { "code": null, "e": 25917, "s": 25914, "text": "C#" }, { "code": null, "e": 25921, "s": 25917, "text": "PHP" }, { "code": null, "e": 25932, "s": 25921, "text": "Javascript" }, { "code": "// C++ program to check if n is sparse or not#include<iostream>using namespace std; // Return true if n is sparse, else falsebool checkSparse(int n){ // n is not sparse if there is set // in AND of n and n/2 if (n & (n>>1)) return false; return true;} // Driver programint main(){ cout << checkSparse(72) << endl; cout << checkSparse(12) << endl; cout << checkSparse(2) << endl; cout << checkSparse(3) << endl; return 0;}", "e": 26389, "s": 25932, "text": null }, { "code": "// JAVA Code to Check if a// given number is sparse or notimport java.util.*; class GFG { // Return true if n is // sparse,else false static int checkSparse(int n) { // n is not sparse if there // is set in AND of n and n/2 if ((n & (n>>1)) >=1) return 0; return 1; } // Driver code public static void main(String[] args) { System.out.println(checkSparse(72)) ; System.out.println(checkSparse(12)) ; System.out.println(checkSparse(2)) ; System.out.println(checkSparse(3)) ; } } //This code is contributed by Arnav Kr. Mandal.", "e": 27033, "s": 26389, "text": null }, { "code": "# Python program to check# if n is sparse or not # Return true if n is# sparse, else falsedef checkSparse(n): # n is not sparse if there is set # in AND of n and n/2 if (n & (n>>1)): return 0 return 1 # Driver codeprint(checkSparse(72))print(checkSparse(12))print(checkSparse(2))print(checkSparse(30)) # This code is contributed# by Anant Agarwal.", "e": 27407, "s": 27033, "text": null }, { "code": "// C# Code to Check if a given// number is sparse or notusing System; class GFG { // Return true if n is // sparse,else false static int checkSparse(int n) { // n is not sparse if there // is set in AND of n and n/2 if ((n & (n >> 1)) >= 1) return 0; return 1; } // Driver code public static void Main() { Console.WriteLine(checkSparse(72)); Console.WriteLine(checkSparse(12)); Console.WriteLine(checkSparse(2)); Console.WriteLine(checkSparse(3)); }} // This code is contributed by Sam007.", "e": 28007, "s": 27407, "text": null }, { "code": "<?php// PHP program to check if// n is sparse or not// Return true if n is sparse,// else false function checkSparse($n){ // n is not sparse if // there is set in AND // of n and n/2 if ($n & ($n >> 1)) return 0; return 1;} // Driver Codeecho checkSparse(72), \"\\n\";echo checkSparse(12), \"\\n\";echo checkSparse(2), \"\\n\";echo checkSparse(3), \"\\n\"; // This code is contributed by Ajit.?>", "e": 28414, "s": 28007, "text": null }, { "code": "<script> // Javascript program to check if n is sparse or not // Return true if n is sparse, else false function checkSparse(n) { // n is not sparse if there is set // in AND of n and n/2 if ((n & (n>>1)) > 0) return 0; return 1; } document.write(checkSparse(72) + \"</br>\"); document.write(checkSparse(12) + \"</br>\"); document.write(checkSparse(2) + \"</br>\"); document.write(checkSparse(3) + \"</br>\"); </script>", "e": 28908, "s": 28414, "text": null }, { "code": null, "e": 28918, "s": 28908, "text": "Output : " }, { "code": null, "e": 28926, "s": 28918, "text": "1\n0\n1\n0" }, { "code": null, "e": 28948, "s": 28926, "text": "Time Complexity: O(1)" }, { "code": null, "e": 28970, "s": 28948, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29259, "s": 28970, "text": "Note: Instead of right shift, we could have used left shift also, but left shift might lead to overflow in some cases.This article is contributed by Vimal Vestron. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29266, "s": 29259, "text": "Sam007" }, { "code": null, "e": 29272, "s": 29266, "text": "jit_t" }, { "code": null, "e": 29283, "s": 29272, "text": "decode2207" }, { "code": null, "e": 29299, "s": 29283, "text": "souravmahato348" }, { "code": null, "e": 29317, "s": 29299, "text": "germanshephered48" }, { "code": null, "e": 29327, "s": 29317, "text": "Bit Magic" }, { "code": null, "e": 29337, "s": 29327, "text": "Bit Magic" }, { "code": null, "e": 29435, "s": 29337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29444, "s": 29435, "text": "Comments" }, { "code": null, "e": 29457, "s": 29444, "text": "Old Comments" }, { "code": null, "e": 29473, "s": 29457, "text": "Bit Fields in C" }, { "code": null, "e": 29524, "s": 29473, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 29575, "s": 29524, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 29610, "s": 29575, "text": "Find the element that appears once" }, { "code": null, "e": 29648, "s": 29610, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 29679, "s": 29648, "text": "C++ bitset and its application" }, { "code": null, "e": 29721, "s": 29679, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 29744, "s": 29721, "text": "Program to find parity" }, { "code": null, "e": 29790, "s": 29744, "text": "Find the Number Occurring Odd Number of Times" } ]
numpy.einsum() Method - GeeksforGeeks
10 Aug, 2020 In NumPy, we can find Einstein’s summation convention of two given multidimensional arrays with the help of numpy.einsum(). We will pass two arrays as a parameter and it will return the Einstein’s summation convention. Syntax: numpy.einsum() Parameter: Two arrays. Return : It will return the Einstein’s summation convention. Example 1: Python import numpy as np array1 = np.array([1, 2, 3])array2 = np.array([4, 5, 6]) # Original 1-d arraysprint(array1)print(array2)r = np.einsum("n,n", a, b) # Einstein’s summation convention of # the said arraysprint(r) Output: [1 2 3] [4 5 6] 32 Example 2: Python import numpy as np ar1 = np.arange(9).reshape(3, 3)ar2 = np.arange(10, 19).reshape(3, 3) # Original Higher dimensionprint(ar1) print(ar2)print("")r = np.einsum("mk,kn", ar1, ar2) # Einstein’s summation convention of # the said arraysprint(r) Output: [[0 1 2] [3 4 5] [6 7 8]] [[10 11 12] [13 14 15] [16 17 18]] [[ 45 48 51] [162 174 186] [279 300 321]] Python numpy-ndarray Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n10 Aug, 2020" }, { "code": null, "e": 24431, "s": 24212, "text": "In NumPy, we can find Einstein’s summation convention of two given multidimensional arrays with the help of numpy.einsum(). We will pass two arrays as a parameter and it will return the Einstein’s summation convention." }, { "code": null, "e": 24454, "s": 24431, "text": "Syntax: numpy.einsum()" }, { "code": null, "e": 24477, "s": 24454, "text": "Parameter: Two arrays." }, { "code": null, "e": 24538, "s": 24477, "text": "Return : It will return the Einstein’s summation convention." }, { "code": null, "e": 24549, "s": 24538, "text": "Example 1:" }, { "code": null, "e": 24556, "s": 24549, "text": "Python" }, { "code": "import numpy as np array1 = np.array([1, 2, 3])array2 = np.array([4, 5, 6]) # Original 1-d arraysprint(array1)print(array2)r = np.einsum(\"n,n\", a, b) # Einstein’s summation convention of # the said arraysprint(r)", "e": 24774, "s": 24556, "text": null }, { "code": null, "e": 24782, "s": 24774, "text": "Output:" }, { "code": null, "e": 24802, "s": 24782, "text": "[1 2 3]\n[4 5 6]\n32\n" }, { "code": null, "e": 24813, "s": 24802, "text": "Example 2:" }, { "code": null, "e": 24820, "s": 24813, "text": "Python" }, { "code": "import numpy as np ar1 = np.arange(9).reshape(3, 3)ar2 = np.arange(10, 19).reshape(3, 3) # Original Higher dimensionprint(ar1) print(ar2)print(\"\")r = np.einsum(\"mk,kn\", ar1, ar2) # Einstein’s summation convention of # the said arraysprint(r)", "e": 25068, "s": 24820, "text": null }, { "code": null, "e": 25077, "s": 25068, "text": " Output:" }, { "code": null, "e": 25189, "s": 25077, "text": "[[0 1 2]\n [3 4 5]\n [6 7 8]]\n[[10 11 12]\n [13 14 15]\n [16 17 18]]\n\n[[ 45 48 51]\n [162 174 186]\n [279 300 321]]" }, { "code": null, "e": 25210, "s": 25189, "text": "Python numpy-ndarray" }, { "code": null, "e": 25223, "s": 25210, "text": "Python-numpy" }, { "code": null, "e": 25230, "s": 25223, "text": "Python" }, { "code": null, "e": 25328, "s": 25230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25337, "s": 25328, "text": "Comments" }, { "code": null, "e": 25350, "s": 25337, "text": "Old Comments" }, { "code": null, "e": 25382, "s": 25350, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25438, "s": 25382, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25459, "s": 25438, "text": "Python OOPs Concepts" }, { "code": null, "e": 25498, "s": 25459, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25540, "s": 25498, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25567, "s": 25540, "text": "Python Classes and Objects" }, { "code": null, "e": 25598, "s": 25567, "text": "Python | os.path.join() method" }, { "code": null, "e": 25640, "s": 25598, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25676, "s": 25640, "text": "Python | Pandas dataframe.groupby()" } ]
Go Decision Making (if, if-else, Nested-if, if-else-if) - GeeksforGeeks
23 Feb, 2022 Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Golang uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. The Decision making statements of Go programming are: This is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Syntax: if condition { // Statements to execute if // condition is true } Flow Chart: Example: C // Go program to illustrate the // use of if statementpackage main import "fmt" func main() { // taking a local variable var v int = 700 // using if statement for // checking the condition if v < 1000 { // print the following if // condition evaluates to true fmt.Printf("v is less than 1000\n") } fmt.Printf("Value of v is : %d\n", v) } Output: v is less than 1000 value of v is : 700 The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.Syntax: if condition { // Executes this block if // condition is true } else { // Executes this block if // condition is false } Flow Chart: Example: C // Go program to illustrate the // use of if...else statementpackage main import "fmt" func main() { // taking a local variable var v int = 1200 // using if statement for // checking the condition if v < 1000 { // print the following if // condition evaluates to true fmt.Printf("v is less than 1000\n") } else { // print the following if // condition evaluates to true fmt.Printf("v is greater than 1000\n") } } Output: v is greater than 1000 In Go Language, a nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement. Yes, Golang allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.Syntax: if condition1 { // Executes when condition1 is true if condition2 { // Executes when condition2 is true } } Flow Chart: Example: C // Go program to illustrate the // use of nested if statementpackage mainimport "fmt" func main() { // taking two local variable var v1 int = 400 var v2 int = 700 // using if statement if( v1 == 400 ) { // if condition is true then // check the following if( v2 == 700 ) { // if condition is true // then display the following fmt.Printf("Value of v1 is 400 and v2 is 700\n" ); } } } Output: Value of v1 is 400 and v2 is 700 Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.Important Points: if statement can have zero or one else’s and it must come after any else if’s. if statement can have zero to many else if’s and it must come before the else. None of the remaining else if’s or else’s will be tested if an else if succeeds, Syntax: if condition_1 { // this block will execute // when condition_1 is true } else if condition_2 { // this block will execute // when condition2 is true } . . . else { // this block will execute when none // of the condition is true } Flow Chart: Example: C // Go program to illustrate the // use of if..else..if ladderpackage mainimport "fmt" func main() { // taking a local variable var v1 int = 700 // checking the condition if v1 == 100 { // if condition is true then // display the following */ fmt.Printf("Value of v1 is 100\n") } else if v1 == 200 { fmt.Printf("Value of a is 20\n") } else if v1 == 300 { fmt.Printf("Value of a is 300\n") } else { // if none of the conditions is true fmt.Printf("None of the values is matching\n") }} Output: None of the values is matching nidhi_biet sagar0719kumar gimolai Go-Control-Flow Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Replace() Function in Golang With Examples strings.Contains Function in Golang with Examples Time Formatting in Golang fmt.Sprintf() Function in Golang With Examples Golang Maps How to convert a string in lower case in Golang? Different Ways to Find the Type of Variable in Golang Inheritance in GoLang
[ { "code": null, "e": 24540, "s": 24512, "text": "\n23 Feb, 2022" }, { "code": null, "e": 25040, "s": 24540, "text": "Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Golang uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. The Decision making statements of Go programming are:" }, { "code": null, "e": 25285, "s": 25042, "text": "This is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.Syntax: " }, { "code": null, "e": 25358, "s": 25285, "text": "if condition {\n\n // Statements to execute if\n // condition is true\n}" }, { "code": null, "e": 25371, "s": 25358, "text": "Flow Chart: " }, { "code": null, "e": 25381, "s": 25371, "text": "Example: " }, { "code": null, "e": 25383, "s": 25381, "text": "C" }, { "code": "// Go program to illustrate the // use of if statementpackage main import \"fmt\" func main() { // taking a local variable var v int = 700 // using if statement for // checking the condition if v < 1000 { // print the following if // condition evaluates to true fmt.Printf(\"v is less than 1000\\n\") } fmt.Printf(\"Value of v is : %d\\n\", v) }", "e": 25781, "s": 25383, "text": null }, { "code": null, "e": 25790, "s": 25781, "text": "Output: " }, { "code": null, "e": 25830, "s": 25790, "text": "v is less than 1000\nvalue of v is : 700" }, { "code": null, "e": 26182, "s": 25832, "text": "The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.Syntax: " }, { "code": null, "e": 26323, "s": 26182, "text": " \nif condition {\n\n // Executes this block if\n // condition is true\n} else {\n\n // Executes this block if\n // condition is false\n}" }, { "code": null, "e": 26336, "s": 26323, "text": "Flow Chart: " }, { "code": null, "e": 26346, "s": 26336, "text": "Example: " }, { "code": null, "e": 26348, "s": 26346, "text": "C" }, { "code": "// Go program to illustrate the // use of if...else statementpackage main import \"fmt\" func main() { // taking a local variable var v int = 1200 // using if statement for // checking the condition if v < 1000 { // print the following if // condition evaluates to true fmt.Printf(\"v is less than 1000\\n\") } else { // print the following if // condition evaluates to true fmt.Printf(\"v is greater than 1000\\n\") } }", "e": 26850, "s": 26348, "text": null }, { "code": null, "e": 26860, "s": 26850, "text": "Output: " }, { "code": null, "e": 26883, "s": 26860, "text": "v is greater than 1000" }, { "code": null, "e": 27177, "s": 26885, "text": "In Go Language, a nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement. Yes, Golang allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.Syntax: " }, { "code": null, "e": 27306, "s": 27177, "text": "if condition1 {\n\n // Executes when condition1 is true\n \n if condition2 {\n\n // Executes when condition2 is true\n }\n}" }, { "code": null, "e": 27319, "s": 27306, "text": "Flow Chart: " }, { "code": null, "e": 27329, "s": 27319, "text": "Example: " }, { "code": null, "e": 27331, "s": 27329, "text": "C" }, { "code": "// Go program to illustrate the // use of nested if statementpackage mainimport \"fmt\" func main() { // taking two local variable var v1 int = 400 var v2 int = 700 // using if statement if( v1 == 400 ) { // if condition is true then // check the following if( v2 == 700 ) { // if condition is true // then display the following fmt.Printf(\"Value of v1 is 400 and v2 is 700\\n\" ); } } }", "e": 27810, "s": 27331, "text": null }, { "code": null, "e": 27820, "s": 27810, "text": "Output: " }, { "code": null, "e": 27853, "s": 27820, "text": "Value of v1 is 400 and v2 is 700" }, { "code": null, "e": 28206, "s": 27855, "text": "Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.Important Points: " }, { "code": null, "e": 28285, "s": 28206, "text": "if statement can have zero or one else’s and it must come after any else if’s." }, { "code": null, "e": 28364, "s": 28285, "text": "if statement can have zero to many else if’s and it must come before the else." }, { "code": null, "e": 28445, "s": 28364, "text": "None of the remaining else if’s or else’s will be tested if an else if succeeds," }, { "code": null, "e": 28454, "s": 28445, "text": "Syntax: " }, { "code": null, "e": 28721, "s": 28454, "text": "if condition_1 {\n\n // this block will execute \n // when condition_1 is true\n\n} else if condition_2 {\n\n // this block will execute \n // when condition2 is true\n}\n.\n.\n. else {\n\n // this block will execute when none\n // of the condition is true\n}" }, { "code": null, "e": 28734, "s": 28721, "text": "Flow Chart: " }, { "code": null, "e": 28744, "s": 28734, "text": "Example: " }, { "code": null, "e": 28746, "s": 28744, "text": "C" }, { "code": "// Go program to illustrate the // use of if..else..if ladderpackage mainimport \"fmt\" func main() { // taking a local variable var v1 int = 700 // checking the condition if v1 == 100 { // if condition is true then // display the following */ fmt.Printf(\"Value of v1 is 100\\n\") } else if v1 == 200 { fmt.Printf(\"Value of a is 20\\n\") } else if v1 == 300 { fmt.Printf(\"Value of a is 300\\n\") } else { // if none of the conditions is true fmt.Printf(\"None of the values is matching\\n\") }}", "e": 29352, "s": 28746, "text": null }, { "code": null, "e": 29362, "s": 29352, "text": "Output: " }, { "code": null, "e": 29393, "s": 29362, "text": "None of the values is matching" }, { "code": null, "e": 29406, "s": 29395, "text": "nidhi_biet" }, { "code": null, "e": 29421, "s": 29406, "text": "sagar0719kumar" }, { "code": null, "e": 29429, "s": 29421, "text": "gimolai" }, { "code": null, "e": 29445, "s": 29429, "text": "Go-Control-Flow" }, { "code": null, "e": 29452, "s": 29445, "text": "Golang" }, { "code": null, "e": 29464, "s": 29452, "text": "Go Language" }, { "code": null, "e": 29562, "s": 29464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29571, "s": 29562, "text": "Comments" }, { "code": null, "e": 29584, "s": 29571, "text": "Old Comments" }, { "code": null, "e": 29636, "s": 29584, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 29682, "s": 29636, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 29733, "s": 29682, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 29783, "s": 29733, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 29809, "s": 29783, "text": "Time Formatting in Golang" }, { "code": null, "e": 29856, "s": 29809, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 29868, "s": 29856, "text": "Golang Maps" }, { "code": null, "e": 29917, "s": 29868, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 29971, "s": 29917, "text": "Different Ways to Find the Type of Variable in Golang" } ]
wxPython - Change Background colour of Button - GeeksforGeeks
18 Jun, 2020 In this article we are going to learn about how can we change background colour of a button present in a frame. We use SetBackgroundColour() function to set background colour of the button to some different colour.It takes a wx.Colour class object as an argument. Syntax: wx.Button.SetBackgroundColour(self, colour) Parameters: Code Example: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) font = wx.Font(10, family = wx.FONTFAMILY_MODERN, style = 0, weight = 90, underline = False, faceName ="", encoding = wx.FONTENCODING_DEFAULT) self.btn = wx.Button(self.pnl, id = 1, label ="Click", pos =(20, 20), size = wx.DefaultSize, name ="statictext") self.btn.SetFont(font) # SET BACKGROUND COLOUR self.btn.SetBackgroundColour((255, 230, 200, 255)) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output Widow: Python wxPython-Button Python-gui Python-wxPython Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24447, "s": 24419, "text": "\n18 Jun, 2020" }, { "code": null, "e": 24711, "s": 24447, "text": "In this article we are going to learn about how can we change background colour of a button present in a frame. We use SetBackgroundColour() function to set background colour of the button to some different colour.It takes a wx.Colour class object as an argument." }, { "code": null, "e": 24763, "s": 24711, "text": "Syntax: wx.Button.SetBackgroundColour(self, colour)" }, { "code": null, "e": 24775, "s": 24763, "text": "Parameters:" }, { "code": null, "e": 24789, "s": 24775, "text": "Code Example:" }, { "code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) font = wx.Font(10, family = wx.FONTFAMILY_MODERN, style = 0, weight = 90, underline = False, faceName =\"\", encoding = wx.FONTENCODING_DEFAULT) self.btn = wx.Button(self.pnl, id = 1, label =\"Click\", pos =(20, 20), size = wx.DefaultSize, name =\"statictext\") self.btn.SetFont(font) # SET BACKGROUND COLOUR self.btn.SetBackgroundColour((255, 230, 200, 255)) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 25718, "s": 24789, "text": null }, { "code": null, "e": 25732, "s": 25718, "text": "Output Widow:" }, { "code": null, "e": 25755, "s": 25732, "text": "Python wxPython-Button" }, { "code": null, "e": 25766, "s": 25755, "text": "Python-gui" }, { "code": null, "e": 25782, "s": 25766, "text": "Python-wxPython" }, { "code": null, "e": 25789, "s": 25782, "text": "Python" }, { "code": null, "e": 25887, "s": 25789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25896, "s": 25887, "text": "Comments" }, { "code": null, "e": 25909, "s": 25896, "text": "Old Comments" }, { "code": null, "e": 25927, "s": 25909, "text": "Python Dictionary" }, { "code": null, "e": 25962, "s": 25927, "text": "Read a file line by line in Python" }, { "code": null, "e": 25984, "s": 25962, "text": "Enumerate() in Python" }, { "code": null, "e": 26016, "s": 25984, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26046, "s": 26016, "text": "Iterate over a list in Python" }, { "code": null, "e": 26088, "s": 26046, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26131, "s": 26088, "text": "Python program to convert a list to string" }, { "code": null, "e": 26157, "s": 26131, "text": "Python String | replace()" }, { "code": null, "e": 26201, "s": 26157, "text": "Reading and Writing to text files in Python" } ]
2’s compliment for a given string using XOR ?
In this section we will see how we can find the 2’s complement using the XOR operation on a binary string. The 2’s complement is actually the 1’s complement + 1. We will use XOR operation to get the 1’s complement. We will traverse the string from LSb, and look for 0. We will flip all 1’s to 0 until we get a 0. Then flip the found 0. We will traverse from LSb. Then ignoring all 0’s until we get 1. Ignoring the first 1, we will toggle all bits using the XOR operation. begin len := length of the binary string flag := false for i := len-1 down to 0, do if bin[i] is 0, and flag is not set, then ignore the next part, jump to next iteration else if flag is set, then bin[i] := flip of bin[i] end if flag := true end if done if the flag is not set, then attach 1 with bin and return else return bin end if end Live Demo #include <iostream> using namespace std; string get2sComplement(string bin) { int n = bin.length(); bool flag = false; //flag is used if 1 is seen for (int i = n - 1; i >= 0; i--) { //traverse from last bit if (bin[i] == '0' && !flag) { continue; } else { if (flag) bin[i] = (bin[i] - '0') ^ 1 + '0'; //flip bit using XOR, then convert to ASCII flag = true; } } if (!flag) //if no 1 is there, just insert 1 return "1" + bin; else return bin; } int main() { string str; cout << "Enter a binary string: "; cin >> str; cout << "2's complement of " << str <<" is " << get2sComplement(str); } Enter a binary string: 10110110 2's complement of 10110110 is 01001010
[ { "code": null, "e": 1277, "s": 1062, "text": "In this section we will see how we can find the 2’s complement using the XOR operation on a binary string. The 2’s complement is actually the 1’s complement + 1. We will use XOR operation to get the 1’s complement." }, { "code": null, "e": 1398, "s": 1277, "text": "We will traverse the string from LSb, and look for 0. We will flip all 1’s to 0 until we get a 0. Then flip the found 0." }, { "code": null, "e": 1534, "s": 1398, "text": "We will traverse from LSb. Then ignoring all 0’s until we get 1. Ignoring the first 1, we will toggle all bits using the XOR operation." }, { "code": null, "e": 1972, "s": 1534, "text": "begin\n len := length of the binary string\n flag := false\n for i := len-1 down to 0, do\n if bin[i] is 0, and flag is not set, then\n ignore the next part, jump to next iteration\n else\n if flag is set, then\n bin[i] := flip of bin[i]\n end if\n flag := true\n end if\n done\n if the flag is not set, then\n attach 1 with bin and return\n else\n return bin\n end if\nend" }, { "code": null, "e": 1983, "s": 1972, "text": " Live Demo" }, { "code": null, "e": 2670, "s": 1983, "text": "#include <iostream>\nusing namespace std;\nstring get2sComplement(string bin) {\n int n = bin.length();\n bool flag = false; //flag is used if 1 is seen\n for (int i = n - 1; i >= 0; i--) { //traverse from last bit\n if (bin[i] == '0' && !flag) {\n continue;\n } else {\n if (flag)\n bin[i] = (bin[i] - '0') ^ 1 + '0'; //flip bit using XOR, then convert to ASCII\n flag = true;\n }\n }\n if (!flag) //if no 1 is there, just insert 1\n return \"1\" + bin;\n else\n return bin;\n}\nint main() {\n string str;\n cout << \"Enter a binary string: \";\n cin >> str;\n cout << \"2's complement of \" << str <<\" is \" << get2sComplement(str);\n}" }, { "code": null, "e": 2741, "s": 2670, "text": "Enter a binary string: 10110110\n2's complement of 10110110 is 01001010" } ]
C - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types − char Typically a single octet(one byte). It is an integer type. int The most natural size of integer for the machine. float A single-precision floating point value. double A double-precision floating point value. void Represents the absence of type. C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types. A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − type variable_list; Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value; Some examples are − extern int d = 3, f = 5; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = 'x'; // the variable x has the value 'x'. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined. A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program. A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code. Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function − #include <stdio.h> // Variable declaration: extern int a, b; extern int c; extern float f; int main () { /* variable definition: */ int a, b; int c; float f; /* actual initialization */ a = 10; b = 20; c = a + b; printf("value of c : %d \n", c); f = 70.0/3.0; printf("value of f : %f \n", f); return 0; } When the above code is compiled and executed, it produces the following result − value of c : 30 value of f : 23.333334 The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example − // function declaration int func(); int main() { // function call int i = func(); } // function definition int func() { return 0; } There are two kinds of expressions in C − lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment. lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements − int g = 20; // valid statement 10 = 20; // invalid statement; would generate compile-time error Print Add Notes Bookmark this page
[ { "code": null, "e": 2400, "s": 2084, "text": "A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable." }, { "code": null, "e": 2723, "s": 2400, "text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −" }, { "code": null, "e": 2728, "s": 2723, "text": "char" }, { "code": null, "e": 2787, "s": 2728, "text": "Typically a single octet(one byte). It is an integer type." }, { "code": null, "e": 2791, "s": 2787, "text": "int" }, { "code": null, "e": 2841, "s": 2791, "text": "The most natural size of integer for the machine." }, { "code": null, "e": 2847, "s": 2841, "text": "float" }, { "code": null, "e": 2888, "s": 2847, "text": "A single-precision floating point value." }, { "code": null, "e": 2895, "s": 2888, "text": "double" }, { "code": null, "e": 2936, "s": 2895, "text": "A double-precision floating point value." }, { "code": null, "e": 2941, "s": 2936, "text": "void" }, { "code": null, "e": 2973, "s": 2941, "text": "Represents the absence of type." }, { "code": null, "e": 3210, "s": 2973, "text": "C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types." }, { "code": null, "e": 3421, "s": 3210, "text": "A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −" }, { "code": null, "e": 3442, "s": 3421, "text": "type variable_list;\n" }, { "code": null, "e": 3683, "s": 3442, "text": "Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −" }, { "code": null, "e": 3742, "s": 3683, "text": "int i, j, k;\nchar c, ch;\nfloat f, salary;\ndouble d;\n" }, { "code": null, "e": 3891, "s": 3742, "text": "The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int." }, { "code": null, "e": 4059, "s": 3891, "text": "Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −" }, { "code": null, "e": 4088, "s": 4059, "text": "type variable_name = value;\n" }, { "code": null, "e": 4108, "s": 4088, "text": "Some examples are −" }, { "code": null, "e": 4361, "s": 4108, "text": "extern int d = 3, f = 5; // declaration of d and f. \nint d = 3, f = 5; // definition and initializing d and f. \nbyte z = 22; // definition and initializes z. \nchar x = 'x'; // the variable x has the value 'x'.\n" }, { "code": null, "e": 4562, "s": 4361, "text": "For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined." }, { "code": null, "e": 4946, "s": 4562, "text": "A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program." }, { "code": null, "e": 5333, "s": 4946, "text": "A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code." }, { "code": null, "e": 5477, "s": 5333, "text": "Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function −" }, { "code": null, "e": 5829, "s": 5477, "text": "#include <stdio.h>\n\n// Variable declaration:\nextern int a, b;\nextern int c;\nextern float f;\n\nint main () {\n\n /* variable definition: */\n int a, b;\n int c;\n float f;\n \n /* actual initialization */\n a = 10;\n b = 20;\n \n c = a + b;\n printf(\"value of c : %d \\n\", c);\n\n f = 70.0/3.0;\n printf(\"value of f : %f \\n\", f);\n \n return 0;\n}" }, { "code": null, "e": 5910, "s": 5829, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5950, "s": 5910, "text": "value of c : 30\nvalue of f : 23.333334\n" }, { "code": null, "e": 6132, "s": 5950, "text": "The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −" }, { "code": null, "e": 6276, "s": 6132, "text": "// function declaration\nint func();\n\nint main() {\n\n // function call\n int i = func();\n}\n\n// function definition\nint func() {\n return 0;\n}" }, { "code": null, "e": 6318, "s": 6276, "text": "There are two kinds of expressions in C −" }, { "code": null, "e": 6486, "s": 6318, "text": "lvalue − Expressions that refer to a memory location are called \"lvalue\" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment." }, { "code": null, "e": 6654, "s": 6486, "text": "lvalue − Expressions that refer to a memory location are called \"lvalue\" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment." }, { "code": null, "e": 6915, "s": 6654, "text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment." }, { "code": null, "e": 7176, "s": 6915, "text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment." }, { "code": null, "e": 7423, "s": 7176, "text": "Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −" }, { "code": null, "e": 7521, "s": 7423, "text": "int g = 20; // valid statement\n\n10 = 20; // invalid statement; would generate compile-time error\n" }, { "code": null, "e": 7528, "s": 7521, "text": " Print" }, { "code": null, "e": 7539, "s": 7528, "text": " Add Notes" } ]
What is autoboxing in Java?
Autoboxing refers to the automatic conversion of a primitive type variable to its corresponding wrapper class object. The compiler automatically handles the conversion when a primitive value is − Passed as an argument to a function which is expecting a wrapper class object. assigned to a variable of the type of wrapper class. Live Demo public class Test{ public static void main(String[] args) { int num = 122; Integer dat = num; System.out.println(dat); } } 122
[ { "code": null, "e": 1258, "s": 1062, "text": "Autoboxing refers to the automatic conversion of a primitive type variable to its corresponding wrapper class object. The compiler automatically handles the conversion when a primitive value is −" }, { "code": null, "e": 1390, "s": 1258, "text": "Passed as an argument to a function which is expecting a wrapper class object. assigned to a variable of the type of wrapper class." }, { "code": null, "e": 1401, "s": 1390, "text": " Live Demo" }, { "code": null, "e": 1548, "s": 1401, "text": "public class Test{\n public static void main(String[] args) {\n int num = 122;\n Integer dat = num;\n System.out.println(dat);\n }\n}" }, { "code": null, "e": 1553, "s": 1548, "text": "122\n" } ]
Dart Programming - Parameterized Function
Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined. Let us now discuss the ways in which parameters can be used by functions. It is mandatory to pass values to required parameters during the function call. Function_name(data_type param_1, data_type param_2[...]) { //statements } The following code snippet declares a function test_param with two parameters namely, n1 and s1 It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameters type is determined dynamically at runtime. It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameters type is determined dynamically at runtime. The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error. The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error. void main() { test_param(123,"this is a string"); } test_param(int n1,String s1) { print(n1); print(s1); } The output of the above code is as follows − 123 this is a string 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2820, "s": 2525, "text": "Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined." }, { "code": null, "e": 2894, "s": 2820, "text": "Let us now discuss the ways in which parameters can be used by functions." }, { "code": null, "e": 2974, "s": 2894, "text": "It is mandatory to pass values to required parameters during the function call." }, { "code": null, "e": 3054, "s": 2974, "text": "Function_name(data_type param_1, data_type param_2[...]) { \n //statements \n}\n" }, { "code": null, "e": 3150, "s": 3054, "text": "The following code snippet declares a function test_param with two parameters namely, n1 and s1" }, { "code": null, "e": 3302, "s": 3150, "text": "It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameters type is determined dynamically at runtime." }, { "code": null, "e": 3454, "s": 3302, "text": "It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameters type is determined dynamically at runtime." }, { "code": null, "e": 3615, "s": 3454, "text": "The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error." }, { "code": null, "e": 3776, "s": 3615, "text": "The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error." }, { "code": null, "e": 3900, "s": 3776, "text": "void main() { \n test_param(123,\"this is a string\"); \n} \ntest_param(int n1,String s1) { \n print(n1); \n print(s1); \n} " }, { "code": null, "e": 3945, "s": 3900, "text": "The output of the above code is as follows −" }, { "code": null, "e": 3969, "s": 3945, "text": "123 \nthis is a string \n" }, { "code": null, "e": 4004, "s": 3969, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4024, "s": 4004, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4057, "s": 4024, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4077, "s": 4057, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4110, "s": 4077, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 4127, "s": 4110, "text": " Frahaan Hussain" }, { "code": null, "e": 4162, "s": 4127, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 4179, "s": 4162, "text": " Frahaan Hussain" }, { "code": null, "e": 4214, "s": 4179, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4234, "s": 4214, "text": " Pranjal Srivastava" }, { "code": null, "e": 4267, "s": 4234, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 4287, "s": 4267, "text": " Pranjal Srivastava" }, { "code": null, "e": 4294, "s": 4287, "text": " Print" }, { "code": null, "e": 4305, "s": 4294, "text": " Add Notes" } ]
The Best Practice of Reading Text Files In Python | by Christopher Tao | Towards Data Science
Reading text files in Python is relatively easy to compare with most of the other programming languages. Usually, we just use the “open()” function with reading or writing mode and then start to loop the text files line by line. This is already the best practice and it cannot be any easier ways. However, when we want to read content from multiple files, there is definitely a better way. That is, using the “File Input” module that is built-in to Python. It combines the content from multiple files that allow us to process everything in a single for-loop and plenty of other benefits. In this article, I’ll demonstrate this module with examples. Let’s have a look at the “ordinary” way of reading multiple text files using the open() function. But before that, we need to create two sample files for demonstration purpose. with open('my_file1.txt', mode='w') as f: f.write('This is line 1-1\n') f.write('This is line 1-2\n')with open('my_file2.txt', mode='w') as f: f.write('This is line 2-1\n') f.write('This is line 2-2\n') In the above code, we open a file with the mode w which means “write”. Then, we write two lines in the file. Please be noticed that we need to add the new line \n. Otherwise, the two sentences will be written in a single line. After that, we should have two text files in the current working directory. Now, let’s say we want to read from both the text files and print the content line by line. Of course, we can still do that use the open() function. # Iterate through all filefor file in ['my_file1.txt', 'my_file2.txt']: with open(file, 'r') as f: for line in f: print(line) Here we have to use two nested for-loops. The outer loop is for the files, while the inner one is for the lines within each file. Well, nothing prevents us from using the open() function. However, the fileinput module just provides us with a neater way of reading multiple text files into a single stream. First of all, we need to import the module. This is a Python built-in module so that we don’t need to download anything. import fileinput as fi Then, we can use it for reading from the two files. with fi.input(files=['my_file1.txt', 'my_file2.txt']) as f: for line in f: print(line) Because the fileinput module is designed for reading from multiple files, we don’t need to loop the file names anymore. Instead, the input() function takes an iterable collection type such as a list as a parameter. Also, the great thing is that all the lines from both files are accessible in a single for-loop. Sometimes, it may not be practical to have such a file name list with all the names that are manually typed. It is quite common to read all the files from a directory. Also, we might be only interested in certain types of files. In this case, we can use the glob module which is another Python built-in module together with the fileinput module. We can do a simple experiment before that. The os module can help us to list all the files in the current working directory. It can be seen that there are many files other than the two text files. Therefore, we want to filter the file names because we want to read the text files only. We can use the glob module as follows. from glob import globglob('*.txt') Now, we can put the glob() function into the fileinput.input() function as the parameter. So, only these two text files will be read. with fi.input(files=glob('*.txt')) as f: for line in f: print(line) You may ask how can we know which file exactly the “line” is from when we are reading from the stream that is actually combined with multiple files? Indeed, using the open() function with nested loop seems to be very easy to get such information because we can access the current file name from the outer loop. However, this is in fact much easier in the fileinput module. with fi.input(files=glob('*.txt')) as f: for line in f: print(f'File Name: {f.filename()} | Line No: {f.lineno()} | {line}') See, in the above code, we use the filename() to access the current file that the line comes from and the lineno() to access the current index of the line we are getting. Apart from that, there are more functions from the fileinput module that we can make use of. For example, what if we want to do something when we reach a new file? The function isfirstline() helps us to decide whether we’re reading the first line from a new file. with fi.input(files=glob('*.txt')) as f: for line in f: if f.isfirstline(): print(f'> Start to read {f.filename()}...') print(line) This could be very useful for logging purpose. So, we can be indicated with the current progress. We can also easily stop reading the current file and jump to the next one. The function nextfile() allows us to do so. Before we can demo this feature, please let me re-write the two sample files. with open('my_file1.txt', mode='w') as f: f.write('This is line 1-1\n') f.write('stop reading\n') f.write('This is line 1-2\n')with open('my_file2.txt', mode='w') as f: f.write('This is line 2-1\n') f.write('This is line 2-2\n') The only difference from the original files is that I added a line of text stop reading in the first text file. Let’s say that we want the fileinput module to stop reading the first file and jump to the second when it sees such content. with fi.input(files=glob('*.txt')) as f: for line in f: if f.isfirstline(): print(f'> Start to read {f.filename()}...') if line == 'stop reading\n': f.nextfile() else: print(line) In the above code, another if-condition is added. When the line text is stop reading it will jump to the next file. Therefore, we can see that the line “1–2” was not read and output. Sometimes we may have compressed files to read. Usually, we will have to uncompress them before we can read the content. However, with the fileinput module, we may not have to extract the content from the compressed files before we can read it. Let’s make up a compressed text file using Gzip. This file will be used for demonstration purposes later. import gzipimport shutilwith open('my_file1.txt', 'rb') as f_in: with gzip.open('my_file.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) In the above code, we added the file my_file1.txt into a compressed file using gzip. Now, let’s see how fileinput can read it without extra steps for uncompressing. with fi.input(files='my_file.gz', openhook=fi.hook_compressed) as f: for line in f: print(line) By using the parameter openhook and the flag fi.hook_compressed, the gzip file will be uncompressed on the fly. The fileinput module currently supports gzip and bzip2. Unfortunately not the other format. In this article, I have introduced the Python built-in module fileinput and how to use it to read multiple text files. Of course, it will never replace the open() function, but in terms of reading multiple files into a single stream, I believe it is the best practice. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 401, "s": 172, "text": "Reading text files in Python is relatively easy to compare with most of the other programming languages. Usually, we just use the “open()” function with reading or writing mode and then start to loop the text files line by line." }, { "code": null, "e": 760, "s": 401, "text": "This is already the best practice and it cannot be any easier ways. However, when we want to read content from multiple files, there is definitely a better way. That is, using the “File Input” module that is built-in to Python. It combines the content from multiple files that allow us to process everything in a single for-loop and plenty of other benefits." }, { "code": null, "e": 821, "s": 760, "text": "In this article, I’ll demonstrate this module with examples." }, { "code": null, "e": 998, "s": 821, "text": "Let’s have a look at the “ordinary” way of reading multiple text files using the open() function. But before that, we need to create two sample files for demonstration purpose." }, { "code": null, "e": 1213, "s": 998, "text": "with open('my_file1.txt', mode='w') as f: f.write('This is line 1-1\\n') f.write('This is line 1-2\\n')with open('my_file2.txt', mode='w') as f: f.write('This is line 2-1\\n') f.write('This is line 2-2\\n')" }, { "code": null, "e": 1440, "s": 1213, "text": "In the above code, we open a file with the mode w which means “write”. Then, we write two lines in the file. Please be noticed that we need to add the new line \\n. Otherwise, the two sentences will be written in a single line." }, { "code": null, "e": 1516, "s": 1440, "text": "After that, we should have two text files in the current working directory." }, { "code": null, "e": 1665, "s": 1516, "text": "Now, let’s say we want to read from both the text files and print the content line by line. Of course, we can still do that use the open() function." }, { "code": null, "e": 1812, "s": 1665, "text": "# Iterate through all filefor file in ['my_file1.txt', 'my_file2.txt']: with open(file, 'r') as f: for line in f: print(line)" }, { "code": null, "e": 1942, "s": 1812, "text": "Here we have to use two nested for-loops. The outer loop is for the files, while the inner one is for the lines within each file." }, { "code": null, "e": 2118, "s": 1942, "text": "Well, nothing prevents us from using the open() function. However, the fileinput module just provides us with a neater way of reading multiple text files into a single stream." }, { "code": null, "e": 2239, "s": 2118, "text": "First of all, we need to import the module. This is a Python built-in module so that we don’t need to download anything." }, { "code": null, "e": 2262, "s": 2239, "text": "import fileinput as fi" }, { "code": null, "e": 2314, "s": 2262, "text": "Then, we can use it for reading from the two files." }, { "code": null, "e": 2411, "s": 2314, "text": "with fi.input(files=['my_file1.txt', 'my_file2.txt']) as f: for line in f: print(line)" }, { "code": null, "e": 2723, "s": 2411, "text": "Because the fileinput module is designed for reading from multiple files, we don’t need to loop the file names anymore. Instead, the input() function takes an iterable collection type such as a list as a parameter. Also, the great thing is that all the lines from both files are accessible in a single for-loop." }, { "code": null, "e": 2952, "s": 2723, "text": "Sometimes, it may not be practical to have such a file name list with all the names that are manually typed. It is quite common to read all the files from a directory. Also, we might be only interested in certain types of files." }, { "code": null, "e": 3069, "s": 2952, "text": "In this case, we can use the glob module which is another Python built-in module together with the fileinput module." }, { "code": null, "e": 3194, "s": 3069, "text": "We can do a simple experiment before that. The os module can help us to list all the files in the current working directory." }, { "code": null, "e": 3394, "s": 3194, "text": "It can be seen that there are many files other than the two text files. Therefore, we want to filter the file names because we want to read the text files only. We can use the glob module as follows." }, { "code": null, "e": 3429, "s": 3394, "text": "from glob import globglob('*.txt')" }, { "code": null, "e": 3563, "s": 3429, "text": "Now, we can put the glob() function into the fileinput.input() function as the parameter. So, only these two text files will be read." }, { "code": null, "e": 3641, "s": 3563, "text": "with fi.input(files=glob('*.txt')) as f: for line in f: print(line)" }, { "code": null, "e": 3790, "s": 3641, "text": "You may ask how can we know which file exactly the “line” is from when we are reading from the stream that is actually combined with multiple files?" }, { "code": null, "e": 4014, "s": 3790, "text": "Indeed, using the open() function with nested loop seems to be very easy to get such information because we can access the current file name from the outer loop. However, this is in fact much easier in the fileinput module." }, { "code": null, "e": 4149, "s": 4014, "text": "with fi.input(files=glob('*.txt')) as f: for line in f: print(f'File Name: {f.filename()} | Line No: {f.lineno()} | {line}')" }, { "code": null, "e": 4320, "s": 4149, "text": "See, in the above code, we use the filename() to access the current file that the line comes from and the lineno() to access the current index of the line we are getting." }, { "code": null, "e": 4484, "s": 4320, "text": "Apart from that, there are more functions from the fileinput module that we can make use of. For example, what if we want to do something when we reach a new file?" }, { "code": null, "e": 4584, "s": 4484, "text": "The function isfirstline() helps us to decide whether we’re reading the first line from a new file." }, { "code": null, "e": 4744, "s": 4584, "text": "with fi.input(files=glob('*.txt')) as f: for line in f: if f.isfirstline(): print(f'> Start to read {f.filename()}...') print(line)" }, { "code": null, "e": 4842, "s": 4744, "text": "This could be very useful for logging purpose. So, we can be indicated with the current progress." }, { "code": null, "e": 4961, "s": 4842, "text": "We can also easily stop reading the current file and jump to the next one. The function nextfile() allows us to do so." }, { "code": null, "e": 5039, "s": 4961, "text": "Before we can demo this feature, please let me re-write the two sample files." }, { "code": null, "e": 5283, "s": 5039, "text": "with open('my_file1.txt', mode='w') as f: f.write('This is line 1-1\\n') f.write('stop reading\\n') f.write('This is line 1-2\\n')with open('my_file2.txt', mode='w') as f: f.write('This is line 2-1\\n') f.write('This is line 2-2\\n')" }, { "code": null, "e": 5520, "s": 5283, "text": "The only difference from the original files is that I added a line of text stop reading in the first text file. Let’s say that we want the fileinput module to stop reading the first file and jump to the second when it sees such content." }, { "code": null, "e": 5757, "s": 5520, "text": "with fi.input(files=glob('*.txt')) as f: for line in f: if f.isfirstline(): print(f'> Start to read {f.filename()}...') if line == 'stop reading\\n': f.nextfile() else: print(line)" }, { "code": null, "e": 5940, "s": 5757, "text": "In the above code, another if-condition is added. When the line text is stop reading it will jump to the next file. Therefore, we can see that the line “1–2” was not read and output." }, { "code": null, "e": 6185, "s": 5940, "text": "Sometimes we may have compressed files to read. Usually, we will have to uncompress them before we can read the content. However, with the fileinput module, we may not have to extract the content from the compressed files before we can read it." }, { "code": null, "e": 6291, "s": 6185, "text": "Let’s make up a compressed text file using Gzip. This file will be used for demonstration purposes later." }, { "code": null, "e": 6443, "s": 6291, "text": "import gzipimport shutilwith open('my_file1.txt', 'rb') as f_in: with gzip.open('my_file.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out)" }, { "code": null, "e": 6608, "s": 6443, "text": "In the above code, we added the file my_file1.txt into a compressed file using gzip. Now, let’s see how fileinput can read it without extra steps for uncompressing." }, { "code": null, "e": 6714, "s": 6608, "text": "with fi.input(files='my_file.gz', openhook=fi.hook_compressed) as f: for line in f: print(line)" }, { "code": null, "e": 6826, "s": 6714, "text": "By using the parameter openhook and the flag fi.hook_compressed, the gzip file will be uncompressed on the fly." }, { "code": null, "e": 6918, "s": 6826, "text": "The fileinput module currently supports gzip and bzip2. Unfortunately not the other format." }, { "code": null, "e": 7187, "s": 6918, "text": "In this article, I have introduced the Python built-in module fileinput and how to use it to read multiple text files. Of course, it will never replace the open() function, but in terms of reading multiple files into a single stream, I believe it is the best practice." }, { "code": null, "e": 7198, "s": 7187, "text": "medium.com" } ]
Aggregation in MongoDB using Python - GeeksforGeeks
10 Jul, 2020 MongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is most recently used database which provide mechanism for storage and retrieval of data. Instead of using tables and rows as in relational databases, mongodb architechture is made up of collections and documents. Aggregation operation groups the values from multiple documents(rows in case of MongoDB) together to perform a variety of operations on the grouped data and is going to return a single result for each grouped data after aggregation. Syntax: db.collection_name.aggregate(aggregate operations) Sample Database used in all the below examples: Example 1: Python3 from pymongo import MongoClient my_client = MongoClient('localhost', 27017)db = my_client["GFG"]coll = db["Student"] # Aggregationcursor = coll.aggregate([{"$group": {"_id":"$Branch", "similar_branches":{"$sum":1} } }]) for document in cursor: print(document) Output: Here, we use “$group” command for grouping then by “_id”:”branches” we are grouping ids according to the branches. “similar_branches” is the keyword used for the total number of similar branches,we can use any keyword here. “$sum:1” is used as a counter of total number of each branches. The sum is incrementing by 1. Example 2: We can also use the aggregation query for counting the number of document in the database. Python3 from pymongo import MongoClient my_client = MongoClient('localhost', 27017)db = my_client["GFG"]coll = db["Student"] # Aggregationcursor = coll.aggregate([{"$group": {"_id":"$None", "total collections":{"$sum": 1} } }]) for document in cursor: print(document) Output: {'_id': None, 'total collections': 8} Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 23941, "s": 23913, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24454, "s": 23941, "text": "MongoDB is free, open-source,cross-platform and document-oriented database management system(dbms). It is a NoSQL type of database. It store the data in BSON format on hard disk. BSON is binary form for representing simple data structure, associative array and various data types in MongoDB. NoSQL is most recently used database which provide mechanism for storage and retrieval of data. Instead of using tables and rows as in relational databases, mongodb architechture is made up of collections and documents. " }, { "code": null, "e": 24688, "s": 24454, "text": "Aggregation operation groups the values from multiple documents(rows in case of MongoDB) together to perform a variety of operations on the grouped data and is going to return a single result for each grouped data after aggregation. " }, { "code": null, "e": 24696, "s": 24688, "text": "Syntax:" }, { "code": null, "e": 24748, "s": 24696, "text": "db.collection_name.aggregate(aggregate operations)\n" }, { "code": null, "e": 24796, "s": 24748, "text": "Sample Database used in all the below examples:" }, { "code": null, "e": 24807, "s": 24796, "text": "Example 1:" }, { "code": null, "e": 24815, "s": 24807, "text": "Python3" }, { "code": "from pymongo import MongoClient my_client = MongoClient('localhost', 27017)db = my_client[\"GFG\"]coll = db[\"Student\"] # Aggregationcursor = coll.aggregate([{\"$group\": {\"_id\":\"$Branch\", \"similar_branches\":{\"$sum\":1} } }]) for document in cursor: print(document)", "e": 25108, "s": 24815, "text": null }, { "code": null, "e": 25116, "s": 25108, "text": "Output:" }, { "code": null, "e": 25435, "s": 25116, "text": "Here, we use “$group” command for grouping then by “_id”:”branches” we are grouping ids according to the branches. “similar_branches” is the keyword used for the total number of similar branches,we can use any keyword here. “$sum:1” is used as a counter of total number of each branches. The sum is incrementing by 1. " }, { "code": null, "e": 25538, "s": 25435, "text": "Example 2: We can also use the aggregation query for counting the number of document in the database." }, { "code": null, "e": 25546, "s": 25538, "text": "Python3" }, { "code": "from pymongo import MongoClient my_client = MongoClient('localhost', 27017)db = my_client[\"GFG\"]coll = db[\"Student\"] # Aggregationcursor = coll.aggregate([{\"$group\": {\"_id\":\"$None\", \"total collections\":{\"$sum\": 1} } }]) for document in cursor: print(document)", "e": 25839, "s": 25546, "text": null }, { "code": null, "e": 25847, "s": 25839, "text": "Output:" }, { "code": null, "e": 25885, "s": 25847, "text": "{'_id': None, 'total collections': 8}" }, { "code": null, "e": 25900, "s": 25885, "text": "Python-mongoDB" }, { "code": null, "e": 25907, "s": 25900, "text": "Python" }, { "code": null, "e": 26005, "s": 25907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26014, "s": 26005, "text": "Comments" }, { "code": null, "e": 26027, "s": 26014, "text": "Old Comments" }, { "code": null, "e": 26045, "s": 26027, "text": "Python Dictionary" }, { "code": null, "e": 26067, "s": 26045, "text": "Enumerate() in Python" }, { "code": null, "e": 26099, "s": 26067, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26129, "s": 26099, "text": "Iterate over a list in Python" }, { "code": null, "e": 26171, "s": 26129, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26214, "s": 26171, "text": "Python program to convert a list to string" }, { "code": null, "e": 26240, "s": 26214, "text": "Python String | replace()" }, { "code": null, "e": 26265, "s": 26240, "text": "sum() function in Python" }, { "code": null, "e": 26302, "s": 26265, "text": "Create a Pandas DataFrame from Lists" } ]
Convert number string to integers in C++
Here we will see how to convert a number string to integer type data. We can solve this problem by using the atoi() function. This function takes string as input and converts into integer data. The atoi() function is present in the <cstdlib> library. Input: A number string “1234” Output: 1234 Step 1: Take a number string Step 2: Convert it to integer using atoi() function Step 3: Print the result. Step 4: End Live Demo #include<iostream> #include<cstdlib> using namespace std; main() { int n; char num_string[20] = "1234"; n = atoi(num_string); cout << n; } 1234
[ { "code": null, "e": 1256, "s": 1062, "text": "Here we will see how to convert a number string to integer type data. We can solve this problem by using the atoi() function. This function takes string as input and converts into integer data." }, { "code": null, "e": 1313, "s": 1256, "text": "The atoi() function is present in the <cstdlib> library." }, { "code": null, "e": 1356, "s": 1313, "text": "Input: A number string “1234”\nOutput: 1234" }, { "code": null, "e": 1475, "s": 1356, "text": "Step 1: Take a number string\nStep 2: Convert it to integer using atoi() function\nStep 3: Print the result.\nStep 4: End" }, { "code": null, "e": 1486, "s": 1475, "text": " Live Demo" }, { "code": null, "e": 1637, "s": 1486, "text": "#include<iostream>\n#include<cstdlib>\nusing namespace std;\nmain() {\n int n;\n char num_string[20] = \"1234\";\n n = atoi(num_string);\n cout << n;\n}" }, { "code": null, "e": 1642, "s": 1637, "text": "1234" } ]
How to hide HTML element with JavaScript?
Use the visibility property in JavaScript to hide an element. You can try to run the following code to learn how to work with visibility property to hide an element − <!DOCTYPE html> <html> <body> <p id = "pid">Demo Text</p> <button type = "button" onclick = "displayHide()">Hide</button> <button type = "button" onclick = "displayShow()">Show</button> <script> function displayHide() { document.getElementById("pid").style.visibility = "hidden"; } function displayShow() { document.getElementById("pid").style.visibility = "visible"; } </script> </body> </html>
[ { "code": null, "e": 1229, "s": 1062, "text": "Use the visibility property in JavaScript to hide an element. You can try to run the following code to learn how to work with visibility property to hide an element −" }, { "code": null, "e": 1728, "s": 1229, "text": "<!DOCTYPE html>\n<html>\n <body>\n <p id = \"pid\">Demo Text</p>\n\n <button type = \"button\" onclick = \"displayHide()\">Hide</button>\n <button type = \"button\" onclick = \"displayShow()\">Show</button>\n \n <script>\n function displayHide() {\n document.getElementById(\"pid\").style.visibility = \"hidden\";\n }\n function displayShow() {\n document.getElementById(\"pid\").style.visibility = \"visible\";\n }\n </script>\n </body>\n</html>" } ]
How to insert elements in C++ STL List ? - GeeksforGeeks
28 Jun, 2021 List has been discussed in many articles, but the sole purpose of this article is to cover all types of insertions that are possible to be carried in a list container and to give a detailed insight on the insertion operations.List and its many functions are defined under the header file “list” . Various list insertions functions are discussed below. assign() function is used to insert multiple elements in a list in a single operation. “assign()” works in following ways : To insert multiple elements at once in a list.syntax : list.assign(number of times, element). To copy elements of 1 list into another.syntax : list.assign(lis2.begin(),lis2.end()) To copy array elements into list.syntax : list.assign(arr,arr+size). // C++ code to demonstrate the working of assign() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; list<int> list2; list<int> list3; // initializing array int arr[10] = { 1, 2, 3, 4 }; // using assign() to insert multiple numbers // creates 4 occurrences of "2" list1.assign(4,2); // Printing the assigned list cout << "The list after inserting multiple elements is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; cout << endl; // using assign() to copy elements of list to other // assigns 4 occurrences of "2" list2.assign(list1.begin(),list1.end()); // Printing the assigned list cout << "The list after copying list elements is : "; for (list<int>::iterator i=list2.begin(); i!=list2.end(); i++) cout << *i << " "; cout << endl; // using assign() to copy elements of array to list // assigns array elements list3.assign(arr,arr+4); // Printing the assigned list cout << "The list after copying array elements is : "; for (list<int>::iterator i=list3.begin(); i!=list3.end(); i++) cout << *i << " "; cout << endl; } Output: The list after inserting multiple elements is : 2 2 2 2 The list after copying list elements is : 2 2 2 2 The list after copying array elements is : 1 2 3 4 Using push_front() : push_front() is used to insert the element at the beginning of list. Increases list size by 1. Using emplace_front() : Works in a similar way as push_front, but the values are constructed in-place in front position of container, where in push_front, an object is created first, and then copied to the container. // C++ code to demonstrate the working of // push_front() and emplace_front() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 2 occurrences of "2" list1.assign(2,2); // using push_front to insert elements at beginning // inserts 5 at beginning list1.push_front(5); // Printing the new list cout << "The list after inserting elements using push_front is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; cout << endl; // using emplace_front to insert elements at beginning // inserts 7 at beginning list1.emplace_front(7); // Printing the new list cout << "The list after inserting elements using emplace_front is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; } Output: The list after inserting elements using push_front is : 5 2 2 The list after inserting elements using emplace_front is : 7 5 2 2 Using push_back() : push_back() is used to insert the element at the end of list. Increases list size by 1. Using emplace_back() : Works in a similar way as push_back, but the values are constructed in-place at back position of container, where in push_back, an object is created first, and then copied to the container. // C++ code to demonstrate the working of // push_back() and emplace_back() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 2 occurrences of "2" list1.assign(2,2); // using push_back to insert elements at the end // inserts 5 at end list1.push_back(5); // Printing the new list cout << "The list after inserting elements using push_back is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; cout << endl; // using emplace_back to insert elements at the end // inserts 7 at end list1.emplace_back(7); // Printing the new list cout << "The list after inserting elements using emplace_back is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; } Output: The list after inserting elements using push_back is : 2 2 5 The list after inserting elements using emplace_back is : 2 2 5 7 Using insert(pos_iter,ele_num,ele) : insert() is used to insert the elements at any position of list.. This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1. . This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1. Using emplace(pos_iter,ele) : Works in a similar way as insert(), but the values are constructed in-place in front position of container, where in push_front, an object is created first, and then copied to the container. And only 1 value is allowed to insert at 1 time. // C++ code to demonstrate the working of // insert() and emplace() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 3 occurrences of "2" list1.assign(3,2); // initializing list iterator to beginning list<int>::iterator it = list1.begin(); // iterator to point to 3rd position advance(it,2); // using insert to insert 1 element at the 3rd position // inserts 5 at 3rd position list1.insert(it,5); // Printing the new list cout << "The list after inserting 1 element using insert() is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; cout << endl; // using insert to insert 2 element at the 4th position // inserts 2 occurrences of 7 at 4th position list1.insert(it,2,7); // Printing the new list cout << "The list after inserting multiple elements using insert() is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; cout << endl; // using emplace to insert elements at the 6th position // inserts 8 at 6th position list1.emplace(it,8); // Printing the new list cout << "The list after inserting elements using emplace() is : "; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << " "; } Output: The list after inserting 1 element using insert() is : 2 2 5 2 The list after inserting multiple elements using insert() is : 2 2 5 7 7 2 The list after inserting elements using emplace() is : 2 2 5 7 7 8 2 This article is contributed by Manjeet Singh. 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. nidhi_biet cpp-containers-library CPP-Library cpp-list STL Misc Misc Misc STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to write Regular Expressions? Recursive Functions Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move) Software Engineering | Prototyping Model Association Rule Advantages and Disadvantages of OOP Java Math min() method with Examples OOPs | Object Oriented Design Set add() method in Java with Examples Consensus Algorithms in Blockchain
[ { "code": null, "e": 24780, "s": 24752, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25132, "s": 24780, "text": "List has been discussed in many articles, but the sole purpose of this article is to cover all types of insertions that are possible to be carried in a list container and to give a detailed insight on the insertion operations.List and its many functions are defined under the header file “list” . Various list insertions functions are discussed below." }, { "code": null, "e": 25256, "s": 25132, "text": "assign() function is used to insert multiple elements in a list in a single operation. “assign()” works in following ways :" }, { "code": null, "e": 25350, "s": 25256, "text": "To insert multiple elements at once in a list.syntax : list.assign(number of times, element)." }, { "code": null, "e": 25436, "s": 25350, "text": "To copy elements of 1 list into another.syntax : list.assign(lis2.begin(),lis2.end())" }, { "code": null, "e": 25505, "s": 25436, "text": "To copy array elements into list.syntax : list.assign(arr,arr+size)." }, { "code": "// C++ code to demonstrate the working of assign() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; list<int> list2; list<int> list3; // initializing array int arr[10] = { 1, 2, 3, 4 }; // using assign() to insert multiple numbers // creates 4 occurrences of \"2\" list1.assign(4,2); // Printing the assigned list cout << \"The list after inserting multiple elements is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; cout << endl; // using assign() to copy elements of list to other // assigns 4 occurrences of \"2\" list2.assign(list1.begin(),list1.end()); // Printing the assigned list cout << \"The list after copying list elements is : \"; for (list<int>::iterator i=list2.begin(); i!=list2.end(); i++) cout << *i << \" \"; cout << endl; // using assign() to copy elements of array to list // assigns array elements list3.assign(arr,arr+4); // Printing the assigned list cout << \"The list after copying array elements is : \"; for (list<int>::iterator i=list3.begin(); i!=list3.end(); i++) cout << *i << \" \"; cout << endl; }", "e": 26807, "s": 25505, "text": null }, { "code": null, "e": 26815, "s": 26807, "text": "Output:" }, { "code": null, "e": 26976, "s": 26815, "text": "The list after inserting multiple elements is : 2 2 2 2 \nThe list after copying list elements is : 2 2 2 2 \nThe list after copying array elements is : 1 2 3 4 \n" }, { "code": null, "e": 27092, "s": 26976, "text": "Using push_front() : push_front() is used to insert the element at the beginning of list. Increases list size by 1." }, { "code": null, "e": 27309, "s": 27092, "text": "Using emplace_front() : Works in a similar way as push_front, but the values are constructed in-place in front position of container, where in push_front, an object is created first, and then copied to the container." }, { "code": "// C++ code to demonstrate the working of // push_front() and emplace_front() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 2 occurrences of \"2\" list1.assign(2,2); // using push_front to insert elements at beginning // inserts 5 at beginning list1.push_front(5); // Printing the new list cout << \"The list after inserting elements using push_front is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; cout << endl; // using emplace_front to insert elements at beginning // inserts 7 at beginning list1.emplace_front(7); // Printing the new list cout << \"The list after inserting elements using emplace_front is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; }", "e": 28289, "s": 27309, "text": null }, { "code": null, "e": 28297, "s": 28289, "text": "Output:" }, { "code": null, "e": 28429, "s": 28297, "text": "The list after inserting elements using push_front is : 5 2 2 \nThe list after inserting elements using emplace_front is : 7 5 2 2 \n" }, { "code": null, "e": 28537, "s": 28429, "text": "Using push_back() : push_back() is used to insert the element at the end of list. Increases list size by 1." }, { "code": null, "e": 28750, "s": 28537, "text": "Using emplace_back() : Works in a similar way as push_back, but the values are constructed in-place at back position of container, where in push_back, an object is created first, and then copied to the container." }, { "code": "// C++ code to demonstrate the working of // push_back() and emplace_back() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 2 occurrences of \"2\" list1.assign(2,2); // using push_back to insert elements at the end // inserts 5 at end list1.push_back(5); // Printing the new list cout << \"The list after inserting elements using push_back is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; cout << endl; // using emplace_back to insert elements at the end // inserts 7 at end list1.emplace_back(7); // Printing the new list cout << \"The list after inserting elements using emplace_back is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; }", "e": 29708, "s": 28750, "text": null }, { "code": null, "e": 29716, "s": 29708, "text": "Output:" }, { "code": null, "e": 29846, "s": 29716, "text": "The list after inserting elements using push_back is : 2 2 5 \nThe list after inserting elements using emplace_back is : 2 2 5 7 \n" }, { "code": null, "e": 30099, "s": 29846, "text": "Using insert(pos_iter,ele_num,ele) : insert() is used to insert the elements at any position of list.. This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1." }, { "code": null, "e": 30251, "s": 30099, "text": ". This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1." }, { "code": null, "e": 30521, "s": 30251, "text": "Using emplace(pos_iter,ele) : Works in a similar way as insert(), but the values are constructed in-place in front position of container, where in push_front, an object is created first, and then copied to the container. And only 1 value is allowed to insert at 1 time." }, { "code": "// C++ code to demonstrate the working of // insert() and emplace() #include <iostream>#include <list> // for list operationsusing namespace std; int main() { // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 3 occurrences of \"2\" list1.assign(3,2); // initializing list iterator to beginning list<int>::iterator it = list1.begin(); // iterator to point to 3rd position advance(it,2); // using insert to insert 1 element at the 3rd position // inserts 5 at 3rd position list1.insert(it,5); // Printing the new list cout << \"The list after inserting 1 element using insert() is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; cout << endl; // using insert to insert 2 element at the 4th position // inserts 2 occurrences of 7 at 4th position list1.insert(it,2,7); // Printing the new list cout << \"The list after inserting multiple elements using insert() is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; cout << endl; // using emplace to insert elements at the 6th position // inserts 8 at 6th position list1.emplace(it,8); // Printing the new list cout << \"The list after inserting elements using emplace() is : \"; for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++) cout << *i << \" \"; }", "e": 32019, "s": 30521, "text": null }, { "code": null, "e": 32027, "s": 32019, "text": "Output:" }, { "code": null, "e": 32238, "s": 32027, "text": "The list after inserting 1 element using insert() is : 2 2 5 2 \nThe list after inserting multiple elements using insert() is : 2 2 5 7 7 2 \nThe list after inserting elements using emplace() is : 2 2 5 7 7 8 2 \n" }, { "code": null, "e": 32535, "s": 32238, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 32660, "s": 32535, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32671, "s": 32660, "text": "nidhi_biet" }, { "code": null, "e": 32694, "s": 32671, "text": "cpp-containers-library" }, { "code": null, "e": 32706, "s": 32694, "text": "CPP-Library" }, { "code": null, "e": 32715, "s": 32706, "text": "cpp-list" }, { "code": null, "e": 32719, "s": 32715, "text": "STL" }, { "code": null, "e": 32724, "s": 32719, "text": "Misc" }, { "code": null, "e": 32729, "s": 32724, "text": "Misc" }, { "code": null, "e": 32734, "s": 32729, "text": "Misc" }, { "code": null, "e": 32738, "s": 32734, "text": "STL" }, { "code": null, "e": 32836, "s": 32738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32845, "s": 32836, "text": "Comments" }, { "code": null, "e": 32858, "s": 32845, "text": "Old Comments" }, { "code": null, "e": 32892, "s": 32858, "text": "How to write Regular Expressions?" }, { "code": null, "e": 32912, "s": 32892, "text": "Recursive Functions" }, { "code": null, "e": 32993, "s": 32912, "text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)" }, { "code": null, "e": 33034, "s": 32993, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 33051, "s": 33034, "text": "Association Rule" }, { "code": null, "e": 33087, "s": 33051, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 33124, "s": 33087, "text": "Java Math min() method with Examples" }, { "code": null, "e": 33154, "s": 33124, "text": "OOPs | Object Oriented Design" }, { "code": null, "e": 33193, "s": 33154, "text": "Set add() method in Java with Examples" } ]
C++ Program to Implement Splay Tree
This is a C++ program to implement Splay Tree. Begin class SplayTree has the functions: Create a function Splay() to implement top-down splay tree. Here head.rch points to the Left tree and head.lch points to the right tree. Create a link to Right tree. Create a link to Left tree. Assemble left, middle and right tree. Create a function Insert() to insert nodes into the tree. If root->k >= all keys will be the root→lch Else if root->k <=all keys will be the root→rch Else Return root. End Begin Create a structure s to declare variable k and left child pointer lch and right child pointer rch. Create a class SplayTree : Create a function RR_Rotate to rotate to the right. Create a function LL_Rotate to rotate to the left. Create a function Splay to implement top-down splay tree. Here head.rch points to the Left tree and head.lch points to the right tree. Create a link to Right tree. Create a link to Left tree. Assemble left, middle and right tree. Create a function New_Node() to create nodes in the tree. Create a function Insert() to insert nodes into the tree. If root→k >= all keys will be the root→lch Else if root->k >=all keys will be the root→rch Else Return root. Create a function Delete() to delete nodes from the tree. Create a function Search() to search the nodes in the tree. Create a function InOrder() for InOrder traversal of the tree. Create a function main(), and perform selective function calls as per choice. End #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; struct s//node declaration { int k; s* lch; s* rch; }; class SplayTree { public: s* RR_Rotate(s* k2) { s* k1 = k2->lch; k2->lch = k1->rch; k1->rch = k2; return k1; } s* LL_Rotate(s* k2) { s* k1 = k2->rch; k2->rch = k1->lch; k1->lch = k2; return k1; } s* Splay(int key, s* root) { if (!root) return NULL; s header; header.lch= header.rch = NULL; s* LeftTreeMax = &header; s* RightTreeMin = &header; while (1) { if (key < root->k) { if (!root->lch) break; if (key< root->lch->k) { root = RR_Rotate(root); if (!root->lch) break; } RightTreeMin->lch= root; RightTreeMin = RightTreeMin->lch; root = root->lch; RightTreeMin->lch = NULL; } else if (key> root->k) { if (!root->rch) break; if (key > root->rch->k) { root = LL_Rotate(root); if (!root->rch) break; } LeftTreeMax->rch= root; LeftTreeMax = LeftTreeMax->rch; root = root->rch; LeftTreeMax->rch = NULL; } else break; } LeftTreeMax→rch = root->lch; RightTreeMin→lch = root->rch; root->lch = header.rch; root->rch = header.lch; return root; } s* New_Node(int key) { s* p_node = new s; if (!p_node) { fprintf(stderr, "Out of memory!\n"); exit(1); } p_node->k = key; p_node->lch = p_node->rch = NULL; return p_node; } s* Insert(int key, s* root) { static s* p_node = NULL; if (!p_node) p_node = New_Node(key); else p_node->k = key; if (!root) { root = p_node; p_node = NULL; return root; } root = Splay(key, root); if (key < root->k) { p_node->lch= root->lch; p_node->rch = root; root->lch = NULL; root = p_node; } else if (key > root->k) { p_node->rch = root->rch; p_node->lch = root; root->rch = NULL; root = p_node; } else return root; p_node = NULL; return root; } s* Delete(int key, s* root)//delete node { s* temp; if (!root)//if tree is empty return NULL; root = Splay(key, root); if (key != root->k)//if tree has one item return root; else { if (!root->lch) { temp = root; root = root->rch; } else { temp = root; root = Splay(key, root->lch); root->rch = temp->rch; } free(temp); return root; } } s* Search(int key, s* root)//seraching { return Splay(key, root); } void InOrder(s* root)//inorder traversal { if (root) { InOrder(root->lch); cout<< "key: " <<root->k; if(root->lch) cout<< " | left child: "<< root->lch->k; if(root->rch) cout << " | right child: " << root->rch->k; cout<< "\n"; InOrder(root->rch); } } }; int main() { SplayTree st; s *root; root = NULL; st.InOrder(root); int i, c; while(1) { cout<<"1. Insert "<<endl; cout<<"2. Delete"<<endl; cout<<"3. Search"<<endl; cout<<"4. Exit"<<endl; cout<<"Enter your choice: "; cin>>c; switch©//perform switch operation { case 1: cout<<"Enter value to be inserted: "; cin>>i; root = st.Insert(i, root); cout<<"\nAfter Insert: "<<i<<endl; st.InOrder(root); break; case 2: cout<<"Enter value to be deleted: "; cin>>i; root = st.Delete(i, root); cout<<"\nAfter Delete: "<<i<<endl; st.InOrder(root); break; case 3: cout<<"Enter value to be searched: "; cin>>i; root = st.Search(i, root); cout<<"\nAfter Search "<<i<<endl; st.InOrder(root); break; case 4: exit(1); default: cout<<"\nInvalid type! \n"; } } cout<<"\n"; return 0; } 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 1 Enter value to be inserted: 7 After Insert: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 1 Enter value to be inserted: 6 After Insert: 6 key: 6 | right child: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 1 Enter value to be inserted: 4 After Insert: 4 key: 4 | right child: 6 key: 6 | right child: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 1 Enter value to be inserted: 5 After Insert: 5 key: 4 key: 5 | left child: 4 | right child: 6 key: 6 | right child: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 1 Enter value to be inserted: 3 After Insert: 3 key: 3 | right child: 4 key: 4 | right child: 5 key: 5 | right child: 6 key: 6 | right child: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 1 Enter value to be inserted: 2 After Insert: 2 key: 2 | right child: 3 key: 3 | right child: 4 key: 4 | right child: 5 key: 5 | right child: 6 key: 6 | right child: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 3 Enter value to be searched: 2 After Search 2 key: 2 | right child: 3 key: 3 | right child: 4 key: 4 | right child: 5 key: 5 | right child: 6 key: 6 | right child: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 2 Enter value to be deleted: 3 After Delete: 3 key: 2 | right child: 4 key: 4 | right child: 5 key: 5 | right child: 6 key: 6 | right child: 7 key: 7 1. Insert 2. Delete 3. Search 4. Exit Enter your choice: 4
[ { "code": null, "e": 1109, "s": 1062, "text": "This is a C++ program to implement Splay Tree." }, { "code": null, "e": 1620, "s": 1109, "text": "Begin\n class SplayTree has the functions:\n Create a function Splay() to implement top-down splay tree.\n Here head.rch points to the Left tree and head.lch points to the right tree.\n Create a link to Right tree.\n Create a link to Left tree.\n Assemble left, middle and right tree.\n Create a function Insert() to insert nodes into the tree.\n If root->k >= all keys will be the root→lch\n Else if\n root->k <=all keys will be the root→rch\n Else\n Return root.\nEnd" }, { "code": null, "e": 2675, "s": 1620, "text": "Begin\n Create a structure s to declare variable k and left child pointer lch and right child pointer rch.\n Create a class SplayTree :\n Create a function RR_Rotate to rotate to the right.\n Create a function LL_Rotate to rotate to the left.\n Create a function Splay to implement top-down splay tree.\n Here head.rch points to the Left tree and head.lch\n points to the right tree.\n Create a link to Right tree.\n Create a link to Left tree.\n Assemble left, middle and right tree.\n Create a function New_Node() to create nodes in the tree.\n Create a function Insert() to insert nodes into the tree.\n If root→k >= all keys will be the root→lch\n Else if\n root->k >=all keys will be the root→rch\n Else\n Return root.\n Create a function Delete() to delete nodes from the tree.\n Create a function Search() to search the nodes in the tree.\n Create a function InOrder() for InOrder traversal of the tree.\n Create a function main(), and perform selective function calls as per choice.\nEnd" }, { "code": null, "e": 7311, "s": 2675, "text": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\nstruct s//node declaration\n{\n int k; \n s* lch;\n s* rch;\n};\nclass SplayTree\n{\n public:\n s* RR_Rotate(s* k2)\n {\n s* k1 = k2->lch;\n k2->lch = k1->rch;\n k1->rch = k2;\n return k1;\n }\n s* LL_Rotate(s* k2)\n {\n s* k1 = k2->rch;\n k2->rch = k1->lch;\n k1->lch = k2;\n return k1;\n }\n s* Splay(int key, s* root)\n {\n if (!root)\n return NULL;\n s header;\n header.lch= header.rch = NULL;\n s* LeftTreeMax = &header;\n s* RightTreeMin = &header;\n while (1)\n {\n if (key < root->k)\n {\n if (!root->lch)\n break;\n if (key< root->lch->k)\n {\n root = RR_Rotate(root);\n if (!root->lch)\n break;\n }\n RightTreeMin->lch= root;\n RightTreeMin = RightTreeMin->lch;\n root = root->lch;\n RightTreeMin->lch = NULL;\n }\n else if (key> root->k)\n {\n if (!root->rch)\n break;\n if (key > root->rch->k)\n {\n root = LL_Rotate(root);\n if (!root->rch)\n break;\n }\n LeftTreeMax->rch= root;\n LeftTreeMax = LeftTreeMax->rch;\n root = root->rch;\n LeftTreeMax->rch = NULL;\n }\n else\n break;\n }\n LeftTreeMax→rch = root->lch;\n RightTreeMin→lch = root->rch;\n root->lch = header.rch;\n root->rch = header.lch;\n return root;\n }\n s* New_Node(int key)\n {\n s* p_node = new s;\n if (!p_node)\n {\n fprintf(stderr, \"Out of memory!\\n\");\n exit(1);\n }\n p_node->k = key;\n p_node->lch = p_node->rch = NULL;\n return p_node;\n }\n s* Insert(int key, s* root)\n {\n static s* p_node = NULL;\n if (!p_node)\n p_node = New_Node(key);\n else\n p_node->k = key;\n if (!root)\n {\n root = p_node;\n p_node = NULL;\n return root;\n }\n root = Splay(key, root);\n if (key < root->k)\n {\n p_node->lch= root->lch;\n p_node->rch = root;\n root->lch = NULL;\n root = p_node;\n }\n else if (key > root->k)\n {\n p_node->rch = root->rch;\n p_node->lch = root;\n root->rch = NULL;\n root = p_node;\n }\n else\n return root;\n p_node = NULL;\n return root;\n }\n s* Delete(int key, s* root)//delete node\n {\n s* temp;\n if (!root)//if tree is empty\n return NULL;\n root = Splay(key, root);\n if (key != root->k)//if tree has one item\n return root;\n else\n {\n if (!root->lch)\n {\n temp = root;\n root = root->rch;\n }\n else\n {\n temp = root;\n root = Splay(key, root->lch);\n root->rch = temp->rch;\n }\n free(temp);\n return root;\n }\n }\n s* Search(int key, s* root)//seraching\n {\n return Splay(key, root);\n }\n void InOrder(s* root)//inorder traversal\n {\n if (root)\n {\n InOrder(root->lch);\n cout<< \"key: \" <<root->k;\n if(root->lch)\n cout<< \" | left child: \"<< root->lch->k;\n if(root->rch)\n cout << \" | right child: \" << root->rch->k;\n cout<< \"\\n\";\n InOrder(root->rch);\n }\n }\n};\nint main()\n{\n SplayTree st;\n s *root;\n root = NULL;\n st.InOrder(root);\n int i, c;\n while(1)\n {\n cout<<\"1. Insert \"<<endl;\n cout<<\"2. Delete\"<<endl;\n cout<<\"3. Search\"<<endl;\n cout<<\"4. Exit\"<<endl;\n cout<<\"Enter your choice: \";\n cin>>c;\n switch©//perform switch operation\n {\n case 1:\n cout<<\"Enter value to be inserted: \";\n cin>>i;\n root = st.Insert(i, root);\n cout<<\"\\nAfter Insert: \"<<i<<endl;\n st.InOrder(root);\n break;\n case 2:\n cout<<\"Enter value to be deleted: \";\n cin>>i;\n root = st.Delete(i, root);\n cout<<\"\\nAfter Delete: \"<<i<<endl;\n st.InOrder(root);\n break;\n case 3:\n cout<<\"Enter value to be searched: \";\n cin>>i;\n root = st.Search(i, root);\n cout<<\"\\nAfter Search \"<<i<<endl;\n st.InOrder(root);\n break;\n case 4:\n exit(1);\n default:\n cout<<\"\\nInvalid type! \\n\";\n }\n }\n cout<<\"\\n\";\n return 0;\n}" }, { "code": null, "e": 8839, "s": 7311, "text": "1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 1\nEnter value to be inserted: 7\nAfter Insert: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 1\nEnter value to be inserted: 6\nAfter Insert: 6\nkey: 6 | right child: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 1\nEnter value to be inserted: 4\nAfter Insert: 4\nkey: 4 | right child: 6\nkey: 6 | right child: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 1\nEnter value to be inserted: 5\nAfter Insert: 5\nkey: 4\nkey: 5 | left child: 4 | right child: 6\nkey: 6 | right child: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 1\nEnter value to be inserted: 3\nAfter Insert: 3\nkey: 3 | right child: 4\nkey: 4 | right child: 5\nkey: 5 | right child: 6\nkey: 6 | right child: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 1\nEnter value to be inserted: 2\nAfter Insert: 2\nkey: 2 | right child: 3\nkey: 3 | right child: 4\nkey: 4 | right child: 5\nkey: 5 | right child: 6\nkey: 6 | right child: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 3\nEnter value to be searched: 2\nAfter Search 2\nkey: 2 | right child: 3\nkey: 3 | right child: 4\nkey: 4 | right child: 5\nkey: 5 | right child: 6\nkey: 6 | right child: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 2\nEnter value to be deleted: 3\nAfter Delete: 3\nkey: 2 | right child: 4\nkey: 4 | right child: 5\nkey: 5 | right child: 6\nkey: 6 | right child: 7\nkey: 7\n1. Insert\n2. Delete\n3. Search\n4. Exit\nEnter your choice: 4" } ]
How to create a user defined exception (custom exception) in java?
An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Live Demo import java.util.Scanner; public class ExceptionExample { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: "+c); } } Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10) You can create your own exceptions in Java. All exceptions must be a child of Throwable. All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. If you want to write a runtime exception, you need to extend the RuntimeException class. To create a user defined exception extend one of the above mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor by passing the message in String format. AgeDoesnotMatchException(String msg){ super(msg); } Or, public String toString(){ return "CustomException[Age is not between 17 and 24]"; } Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword. MyException ex = new MyException (); If(condition..........){ throw ex; } In the following Java program, we are creating a custom exception class with name AgeDoesnotMatchException. public class AgeDoesnotMatchException extends Exception{ (String msg){ super(msg); } } Another class Student contains two private variables name, age and, a parameterized constructor which initializes the instance variables. Form the main method we are accepting name and age values from user and initializing Student class by passing the accepted values. In the constructor of the Student class we have created an object of the exception AgeDoesnotMatchException and raised the exception (using throws) if the age value is between 17 and 24. public class Student extends RuntimeException { private String name; private int age; public Student(String name, int age){ try { if (age<17||age>24) { String msg = "Age is not between 17 and 24"; AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg); throw ex; } } catch(AgeDoesnotMatchException e) { e.printStackTrace(); } this.name = name; this.age = age; } public void display(){ System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); } public static void main(String args[]) { Scanner sc= new Scanner(System.in); System.out.println("Enter the name of the Student: "); String name = sc.next(); System.out.println("Enter the age of the Student should be 17 to 24 (including 17 and 24): "); int age = sc.nextInt(); Student obj = new Student(name, age); obj.display(); } } On executing this program, you need to pass name and age values from keyboard. If the given age value id not between 17 and 24 then exception occurs as shown below − Enter the name of the Student: Krishna Enter the age of the Student should be 17 to 24 (including 17 and 24): 14 AgeDoesnotMatchException: Age is not between 17 and 24 Name of the Student: Krishna' Age of the Student: 14 at Student.<init>(Student.java:18) at Student.main(Student.java:39)
[ { "code": null, "e": 1290, "s": 1062, "text": "An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed." }, { "code": null, "e": 1301, "s": 1290, "text": " Live Demo" }, { "code": null, "e": 1676, "s": 1301, "text": "import java.util.Scanner;\npublic class ExceptionExample {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter first number: \");\n int a = sc.nextInt();\n System.out.println(\"Enter second number: \");\n int b = sc.nextInt();\n int c = a/b;\n System.out.println(\"The result is: \"+c);\n }\n}" }, { "code": null, "e": 1842, "s": 1676, "text": "Enter first number:\n100\nEnter second number:\n0\nException in thread \"main\" java.lang.ArithmeticException: / by zero\nat ExceptionExample.main(ExceptionExample.java:10)" }, { "code": null, "e": 1886, "s": 1842, "text": "You can create your own exceptions in Java." }, { "code": null, "e": 1931, "s": 1886, "text": "All exceptions must be a child of Throwable." }, { "code": null, "e": 1976, "s": 1931, "text": "All exceptions must be a child of Throwable." }, { "code": null, "e": 2119, "s": 1976, "text": "If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class." }, { "code": null, "e": 2262, "s": 2119, "text": "If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class." }, { "code": null, "e": 2351, "s": 2262, "text": "If you want to write a runtime exception, you need to extend the RuntimeException class." }, { "code": null, "e": 2440, "s": 2351, "text": "If you want to write a runtime exception, you need to extend the RuntimeException class." }, { "code": null, "e": 2663, "s": 2440, "text": "To create a user defined exception extend one of the above mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor by passing the message in String format." }, { "code": null, "e": 2809, "s": 2663, "text": "AgeDoesnotMatchException(String msg){\n super(msg);\n}\nOr,\npublic String toString(){\n return \"CustomException[Age is not between 17 and 24]\";\n}" }, { "code": null, "e": 2984, "s": 2809, "text": "Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword." }, { "code": null, "e": 3061, "s": 2984, "text": "MyException ex = new MyException ();\nIf(condition..........){\n throw ex;\n}" }, { "code": null, "e": 3169, "s": 3061, "text": "In the following Java program, we are creating a custom exception class with name AgeDoesnotMatchException." }, { "code": null, "e": 3268, "s": 3169, "text": "public class AgeDoesnotMatchException extends Exception{\n (String msg){\n super(msg);\n }\n}" }, { "code": null, "e": 3406, "s": 3268, "text": "Another class Student contains two private variables name, age and, a parameterized constructor which initializes the instance variables." }, { "code": null, "e": 3537, "s": 3406, "text": "Form the main method we are accepting name and age values from user and initializing Student class by passing the accepted values." }, { "code": null, "e": 3724, "s": 3537, "text": "In the constructor of the Student class we have created an object of the exception AgeDoesnotMatchException and raised the exception (using throws) if the age value is between 17 and 24." }, { "code": null, "e": 4748, "s": 3724, "text": "public class Student extends RuntimeException {\n private String name;\n private int age;\n public Student(String name, int age){\n try {\n if (age<17||age>24) {\n String msg = \"Age is not between 17 and 24\";\n AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg);\n throw ex;\n }\n }\n catch(AgeDoesnotMatchException e) {\n e.printStackTrace();\n }\n this.name = name;\n this.age = age;\n } \n public void display(){\n System.out.println(\"Name of the Student: \"+this.name );\n System.out.println(\"Age of the Student: \"+this.age );\n }\n public static void main(String args[]) {\n Scanner sc= new Scanner(System.in);\n System.out.println(\"Enter the name of the Student: \");\n String name = sc.next();\n System.out.println(\"Enter the age of the Student should be 17 to 24\n (including 17 and 24): \");\n int age = sc.nextInt();\n Student obj = new Student(name, age);\n obj.display();\n }\n}" }, { "code": null, "e": 4914, "s": 4748, "text": "On executing this program, you need to pass name and age values from keyboard. If the given age value id not between 17 and 24 then exception occurs as shown below −" }, { "code": null, "e": 5203, "s": 4914, "text": "Enter the name of the Student:\nKrishna\nEnter the age of the Student should be 17 to 24 (including 17 and 24):\n14\nAgeDoesnotMatchException: Age is not between 17 and 24\nName of the Student: Krishna'\nAge of the Student: 14\nat Student.<init>(Student.java:18)\nat Student.main(Student.java:39)" } ]
How can we drop UNIQUE constraint from a MySQL table?
For dropping UNIQUE constraint from a MySQL table, first of all, we must have to check the name of the index created by the UNIQUE constraint on the table. As we know that SHOW INDEX statement is used for this purpose. The ‘key_name’ in the result set of SHOW INDEX statement contains the name of the index. Now either with the help of DROP INDEX statement or ALTER TABLE statement, we can drop the UNIQUE constraint. The syntax for both the statements is as follows − DROP INDEX index_name ON table_name; OR ALTER TABLE table_name DROP INDEX index_name; Suppose we have the table ‘empl’ which have a UNIQUE constraint on column ‘empno’. The index name can be checked as follows − mysql> Show Index from empl\G *************************** 1. row *************************** Table: empl Non_unique: 0 Key_name: empno Seq_in_index: 1 Column_name: empno Collation: A Cardinality: 0 Sub_part: NULL Packed: NULL Null: YES Index_type: BTREE Comment: Index_comment: 1 row in set (0.02 sec) Now for dropping the UNIQUE constraint, we can write the following query − mysql> ALTER TABLE empl DROP INDEX empno; Query OK, 0 rows affected (0.26 sec) Records: 0 Duplicates: 0 Warnings: 0 The result set of the query below will show that there is no UNIQUE constraint on column ‘empno’ − mysql> describe empl; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | empno | int(11) | YES | | NULL | | | F_name | varchar(20) | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 2 rows in set (0.04 sec) Even if we will run the SHOW INDEX from empl query then MySQL will result in an empty set as follows − mysql> Show index from empl; Empty set (0.00 sec) The UNIQUE constraint can also be dropped from ‘empl’ table with the help of DROP INDEX statement as follows − mysql> DROP INDEX empno on empl; Query OK, 0 rows affected (0.17 sec) Records: 0 Duplicates: 0 Warnings: 0
[ { "code": null, "e": 1531, "s": 1062, "text": "For dropping UNIQUE constraint from a MySQL table, first of all, we must have to check the name of the index created by the UNIQUE constraint on the table. As we know that SHOW INDEX statement is used for this purpose. The ‘key_name’ in the result set of SHOW INDEX statement contains the name of the index. Now either with the help of DROP INDEX statement or ALTER TABLE statement, we can drop the UNIQUE constraint. The syntax for both the statements is as follows −" }, { "code": null, "e": 1617, "s": 1531, "text": "DROP INDEX index_name ON table_name;\nOR\nALTER TABLE table_name DROP INDEX index_name;" }, { "code": null, "e": 1743, "s": 1617, "text": "Suppose we have the table ‘empl’ which have a UNIQUE constraint on column ‘empno’. The index name can be checked as follows −" }, { "code": null, "e": 2045, "s": 1743, "text": "mysql> Show Index from empl\\G\n*************************** 1. row ***************************\nTable: empl\nNon_unique: 0\nKey_name: empno\nSeq_in_index: 1\nColumn_name: empno\nCollation: A\nCardinality: 0\nSub_part: NULL\nPacked: NULL\nNull: YES\nIndex_type: BTREE\nComment:\nIndex_comment:\n1 row in set (0.02 sec)" }, { "code": null, "e": 2120, "s": 2045, "text": "Now for dropping the UNIQUE constraint, we can write the following query −" }, { "code": null, "e": 2236, "s": 2120, "text": "mysql> ALTER TABLE empl DROP INDEX empno;\nQuery OK, 0 rows affected (0.26 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2335, "s": 2236, "text": "The result set of the query below will show that there is no UNIQUE constraint on column ‘empno’ −" }, { "code": null, "e": 2679, "s": 2335, "text": "mysql> describe empl;\n\n+--------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+-------------+------+-----+---------+-------+\n| empno | int(11) | YES | | NULL | |\n| F_name | varchar(20) | YES | | NULL | |\n+--------+-------------+------+-----+---------+-------+\n\n2 rows in set (0.04 sec)" }, { "code": null, "e": 2782, "s": 2679, "text": "Even if we will run the SHOW INDEX from empl query then MySQL will result in an empty set as follows −" }, { "code": null, "e": 2832, "s": 2782, "text": "mysql> Show index from empl;\nEmpty set (0.00 sec)" }, { "code": null, "e": 2943, "s": 2832, "text": "The UNIQUE constraint can also be dropped from ‘empl’ table with the help of DROP INDEX statement as follows −" }, { "code": null, "e": 3050, "s": 2943, "text": "mysql> DROP INDEX empno on empl;\nQuery OK, 0 rows affected (0.17 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" } ]
Fortran - Intrinsic Functions
Intrinsic functions are some common and important functions that are provided as a part of the Fortran language. We have already discussed some of these functions in the Arrays, Characters and String chapters. Intrinsic functions can be categorised as − Numeric Functions Mathematical Functions Numeric Inquiry Functions Floating-Point Manipulation Functions Bit Manipulation Functions Character Functions Kind Functions Logical Functions Array Functions. We have discussed the array functions in the Arrays chapter. In the following section we provide brief descriptions of all these functions from other categories. In the function name column, A represents any type of numeric variable R represents a real or integer variable X and Y represent real variables Z represents complex variable W represents real or complex variable ABS (A) It returns the absolute value of A AIMAG (Z) It returns the imaginary part of a complex number Z AINT (A [, KIND]) It truncates fractional part of A towards zero, returning a real, whole number. ANINT (A [, KIND]) It returns a real value, the nearest integer or whole number. CEILING (A [, KIND]) It returns the least integer greater than or equal to number A. CMPLX (X [, Y, KIND]) It converts the real variables X and Y to a complex number X+iY; if Y is absent, 0 is used. CONJG (Z) It returns the complex conjugate of any complex number Z. DBLE (A) It converts A to a double precision real number. DIM (X, Y) It returns the positive difference of X and Y. DPROD (X, Y) It returns the double precision real product of X and Y. FLOOR (A [, KIND]) It provides the greatest integer less than or equal to number A. INT (A [, KIND]) It converts a number (real or integer) to integer, truncating the real part towards zero. MAX (A1, A2 [, A3,...]) It returns the maximum value from the arguments, all being of same type. MIN (A1, A2 [, A3,...]) It returns the minimum value from the arguments, all being of same type. MOD (A, P) It returns the remainder of A on division by P, both arguments being of the same type (A-INT(A/P)*P) MODULO (A, P) It returns A modulo P: (A-FLOOR(A/P)*P) NINT (A [, KIND]) It returns the nearest integer of number A REAL (A [, KIND]) It Converts to real type SIGN (A, B) It returns the absolute value of A multiplied by the sign of P. Basically it transfers the of sign of B to A. program numericFunctions implicit none ! define constants ! define variables real :: a, b complex :: z ! values for a, b a = 15.2345 b = -20.7689 write(*,*) 'abs(a): ',abs(a),' abs(b): ',abs(b) write(*,*) 'aint(a): ',aint(a),' aint(b): ',aint(b) write(*,*) 'ceiling(a): ',ceiling(a),' ceiling(b): ',ceiling(b) write(*,*) 'floor(a): ',floor(a),' floor(b): ',floor(b) z = cmplx(a, b) write(*,*) 'z: ',z end program numericFunctions When you compile and execute the above program, it produces the following result − abs(a): 15.2344999 abs(b): 20.7688999 aint(a): 15.0000000 aint(b): -20.0000000 ceiling(a): 16 ceiling(b): -20 floor(a): 15 floor(b): -21 z: (15.2344999, -20.7688999) ACOS (X) It returns the inverse cosine in the range (0, π), in radians. ASIN (X) It returns the inverse sine in the range (-π/2, π/2), in radians. ATAN (X) It returns the inverse tangent in the range (-π/2, π/2), in radians. ATAN2 (Y, X) It returns the inverse tangent in the range (-π, π), in radians. COS (X) It returns the cosine of argument in radians. COSH (X) It returns the hyperbolic cosine of argument in radians. EXP (X) It returns the exponential value of X. LOG (X) It returns the natural logarithmic value of X. LOG10 (X) It returns the common logarithmic (base 10) value of X. SIN (X) It returns the sine of argument in radians. SINH (X) It returns the hyperbolic sine of argument in radians. SQRT (X) It returns square root of X. TAN (X) It returns the tangent of argument in radians. TANH (X) It returns the hyperbolic tangent of argument in radians. The following program computes the horizontal and vertical position x and y respectively of a projectile after a time, t − Where, x = u t cos a and y = u t sin a - g t2 / 2 program projectileMotion implicit none ! define constants real, parameter :: g = 9.8 real, parameter :: pi = 3.1415927 !define variables real :: a, t, u, x, y !values for a, t, and u a = 45.0 t = 20.0 u = 10.0 ! convert angle to radians a = a * pi / 180.0 x = u * cos(a) * t y = u * sin(a) * t - 0.5 * g * t * t write(*,*) 'x: ',x,' y: ',y end program projectileMotion When you compile and execute the above program, it produces the following result − x: 141.421356 y: -1818.57861 These functions work with a certain model of integer and floating-point arithmetic. The functions return properties of numbers of the same kind as the variable X, which can be real and in some cases integer. DIGITS (X) It returns the number of significant digits of the model. EPSILON (X) It returns the number that is almost negligible compared to one. In other words, it returns the smallest value such that REAL( 1.0, KIND(X)) + EPSILON(X) is not equal to REAL( 1.0, KIND(X)). HUGE (X) It returns the largest number of the model MAXEXPONENT (X) It returns the maximum exponent of the model MINEXPONENT (X) It returns the minimum exponent of the model PRECISION (X) It returns the decimal precision RADIX (X) It returns the base of the model RANGE (X) It returns the decimal exponent range TINY (X) It returns the smallest positive number of the model EXPONENT (X) It returns the exponent part of a model number FRACTION (X) It returns the fractional part of a number NEAREST (X, S) It returns the nearest different processor number in given direction RRSPACING (X) It returns the reciprocal of the relative spacing of model numbers near given number SCALE (X, I) It multiplies a real by its base to an integer power SET_EXPONENT (X, I) it returns the exponent part of a number SPACING (X) It returns the absolute spacing of model numbers near given number BIT_SIZE (I) It returns the number of bits of the model BTEST (I, POS) Bit testing IAND (I, J) Logical AND IBCLR (I, POS) Clear bit IBITS (I, POS, LEN) Bit extraction IBSET (I, POS) Set bit IEOR (I, J) Exclusive OR IOR (I, J) Inclusive OR ISHFT (I, SHIFT) Logical shift ISHFTC (I, SHIFT [, SIZE]) Circular shift NOT (I) Logical complement ACHAR (I) It returns the Ith character in the ASCII collating sequence. ADJUSTL (STRING) It adjusts string left by removing any leading blanks and inserting trailing blanks ADJUSTR (STRING) It adjusts string right by removing trailing blanks and inserting leading blanks. CHAR (I [, KIND]) It returns the Ith character in the machine specific collating sequence IACHAR (C) It returns the position of the character in the ASCII collating sequence. ICHAR (C) It returns the position of the character in the machine (processor) specific collating sequence. INDEX (STRING, SUBSTRING [, BACK]) It returns the leftmost (rightmost if BACK is .TRUE.) starting position of SUBSTRING within STRING. LEN (STRING) It returns the length of a string. LEN_TRIM (STRING) It returns the length of a string without trailing blank characters. LGE (STRING_A, STRING_B) Lexically greater than or equal LGT (STRING_A, STRING_B) Lexically greater than LLE (STRING_A, STRING_B) Lexically less than or equal LLT (STRING_A, STRING_B) Lexically less than REPEAT (STRING, NCOPIES) Repeated concatenation SCAN (STRING, SET [, BACK]) It returns the index of the leftmost (rightmost if BACK is .TRUE.) character of STRING that belong to SET, or 0 if none belong. TRIM (STRING) Removes trailing blank characters VERIFY (STRING, SET [, BACK]) Verifies the set of characters in a string KIND (X) It returns the kind type parameter value. SELECTED_INT_KIND (R) It returns kind of type parameter for specified exponent range. SELECTED_REAL_KIND ([P, R]) Real kind type parameter value, given precision and range LOGICAL (L [, KIND]) Convert between objects of type logical with different kind type parameters Print Add Notes Bookmark this page
[ { "code": null, "e": 2356, "s": 2146, "text": "Intrinsic functions are some common and important functions that are provided as a part of the Fortran language. We have already discussed some of these functions in the Arrays, Characters and String chapters." }, { "code": null, "e": 2400, "s": 2356, "text": "Intrinsic functions can be categorised as −" }, { "code": null, "e": 2418, "s": 2400, "text": "Numeric Functions" }, { "code": null, "e": 2441, "s": 2418, "text": "Mathematical Functions" }, { "code": null, "e": 2467, "s": 2441, "text": "Numeric Inquiry Functions" }, { "code": null, "e": 2505, "s": 2467, "text": "Floating-Point Manipulation Functions" }, { "code": null, "e": 2532, "s": 2505, "text": "Bit Manipulation Functions" }, { "code": null, "e": 2552, "s": 2532, "text": "Character Functions" }, { "code": null, "e": 2567, "s": 2552, "text": "Kind Functions" }, { "code": null, "e": 2585, "s": 2567, "text": "Logical Functions" }, { "code": null, "e": 2602, "s": 2585, "text": "Array Functions." }, { "code": null, "e": 2764, "s": 2602, "text": "We have discussed the array functions in the Arrays chapter. In the following section we provide brief descriptions of all these functions from other categories." }, { "code": null, "e": 2793, "s": 2764, "text": "In the function name column," }, { "code": null, "e": 2835, "s": 2793, "text": "A represents any type of numeric variable" }, { "code": null, "e": 2875, "s": 2835, "text": "R represents a real or integer variable" }, { "code": null, "e": 2908, "s": 2875, "text": "X and Y represent real variables" }, { "code": null, "e": 2938, "s": 2908, "text": "Z represents complex variable" }, { "code": null, "e": 2976, "s": 2938, "text": "W represents real or complex variable" }, { "code": null, "e": 2984, "s": 2976, "text": "ABS (A)" }, { "code": null, "e": 3019, "s": 2984, "text": "It returns the absolute value of A" }, { "code": null, "e": 3029, "s": 3019, "text": "AIMAG (Z)" }, { "code": null, "e": 3081, "s": 3029, "text": "It returns the imaginary part of a complex number Z" }, { "code": null, "e": 3100, "s": 3081, "text": "AINT (A [, KIND])" }, { "code": null, "e": 3180, "s": 3100, "text": "It truncates fractional part of A towards zero, returning a real, whole number." }, { "code": null, "e": 3199, "s": 3180, "text": "ANINT (A [, KIND])" }, { "code": null, "e": 3261, "s": 3199, "text": "It returns a real value, the nearest integer or whole number." }, { "code": null, "e": 3283, "s": 3261, "text": "CEILING (A [, KIND])" }, { "code": null, "e": 3347, "s": 3283, "text": "It returns the least integer greater than or equal to number A." }, { "code": null, "e": 3369, "s": 3347, "text": "CMPLX (X [, Y, KIND])" }, { "code": null, "e": 3461, "s": 3369, "text": "It converts the real variables X and Y to a complex number X+iY; if Y is absent, 0 is used." }, { "code": null, "e": 3471, "s": 3461, "text": "CONJG (Z)" }, { "code": null, "e": 3529, "s": 3471, "text": "It returns the complex conjugate of any complex number Z." }, { "code": null, "e": 3538, "s": 3529, "text": "DBLE (A)" }, { "code": null, "e": 3587, "s": 3538, "text": "It converts A to a double precision real number." }, { "code": null, "e": 3598, "s": 3587, "text": "DIM (X, Y)" }, { "code": null, "e": 3645, "s": 3598, "text": "It returns the positive difference of X and Y." }, { "code": null, "e": 3658, "s": 3645, "text": "DPROD (X, Y)" }, { "code": null, "e": 3715, "s": 3658, "text": "It returns the double precision real product of X and Y." }, { "code": null, "e": 3735, "s": 3715, "text": "FLOOR (A [, KIND])" }, { "code": null, "e": 3800, "s": 3735, "text": "It provides the greatest integer less than or equal to number A." }, { "code": null, "e": 3817, "s": 3800, "text": "INT (A [, KIND])" }, { "code": null, "e": 3907, "s": 3817, "text": "It converts a number (real or integer) to integer, truncating the real part towards zero." }, { "code": null, "e": 3931, "s": 3907, "text": "MAX (A1, A2 [, A3,...])" }, { "code": null, "e": 4004, "s": 3931, "text": "It returns the maximum value from the arguments, all being of same type." }, { "code": null, "e": 4028, "s": 4004, "text": "MIN (A1, A2 [, A3,...])" }, { "code": null, "e": 4101, "s": 4028, "text": "It returns the minimum value from the arguments, all being of same type." }, { "code": null, "e": 4112, "s": 4101, "text": "MOD (A, P)" }, { "code": null, "e": 4214, "s": 4112, "text": "It returns the remainder of A on division by P, both arguments being of the same type (A-INT(A/P)*P)" }, { "code": null, "e": 4228, "s": 4214, "text": "MODULO (A, P)" }, { "code": null, "e": 4268, "s": 4228, "text": "It returns A modulo P: (A-FLOOR(A/P)*P)" }, { "code": null, "e": 4286, "s": 4268, "text": "NINT (A [, KIND])" }, { "code": null, "e": 4329, "s": 4286, "text": "It returns the nearest integer of number A" }, { "code": null, "e": 4347, "s": 4329, "text": "REAL (A [, KIND])" }, { "code": null, "e": 4372, "s": 4347, "text": "It Converts to real type" }, { "code": null, "e": 4384, "s": 4372, "text": "SIGN (A, B)" }, { "code": null, "e": 4494, "s": 4384, "text": "It returns the absolute value of A multiplied by the sign of P. Basically it transfers the of sign of B to A." }, { "code": null, "e": 5000, "s": 4494, "text": "program numericFunctions\nimplicit none \n\n ! define constants \n ! define variables\n real :: a, b \n complex :: z\n \n ! values for a, b \n a = 15.2345\n b = -20.7689\n \n write(*,*) 'abs(a): ',abs(a),' abs(b): ',abs(b) \n write(*,*) 'aint(a): ',aint(a),' aint(b): ',aint(b) \n write(*,*) 'ceiling(a): ',ceiling(a),' ceiling(b): ',ceiling(b) \n write(*,*) 'floor(a): ',floor(a),' floor(b): ',floor(b) \n \n z = cmplx(a, b)\n write(*,*) 'z: ',z \n \nend program numericFunctions" }, { "code": null, "e": 5083, "s": 5000, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 5263, "s": 5083, "text": "abs(a): 15.2344999 abs(b): 20.7688999 \naint(a): 15.0000000 aint(b): -20.0000000 \nceiling(a): 16 ceiling(b): -20\nfloor(a): 15 floor(b): -21\nz: (15.2344999, -20.7688999)\n" }, { "code": null, "e": 5272, "s": 5263, "text": "ACOS (X)" }, { "code": null, "e": 5335, "s": 5272, "text": "It returns the inverse cosine in the range (0, π), in radians." }, { "code": null, "e": 5344, "s": 5335, "text": "ASIN (X)" }, { "code": null, "e": 5410, "s": 5344, "text": "It returns the inverse sine in the range (-π/2, π/2), in radians." }, { "code": null, "e": 5419, "s": 5410, "text": "ATAN (X)" }, { "code": null, "e": 5488, "s": 5419, "text": "It returns the inverse tangent in the range (-π/2, π/2), in radians." }, { "code": null, "e": 5501, "s": 5488, "text": "ATAN2 (Y, X)" }, { "code": null, "e": 5566, "s": 5501, "text": "It returns the inverse tangent in the range (-π, π), in radians." }, { "code": null, "e": 5574, "s": 5566, "text": "COS (X)" }, { "code": null, "e": 5620, "s": 5574, "text": "It returns the cosine of argument in radians." }, { "code": null, "e": 5629, "s": 5620, "text": "COSH (X)" }, { "code": null, "e": 5686, "s": 5629, "text": "It returns the hyperbolic cosine of argument in radians." }, { "code": null, "e": 5694, "s": 5686, "text": "EXP (X)" }, { "code": null, "e": 5733, "s": 5694, "text": "It returns the exponential value of X." }, { "code": null, "e": 5741, "s": 5733, "text": "LOG (X)" }, { "code": null, "e": 5788, "s": 5741, "text": "It returns the natural logarithmic value of X." }, { "code": null, "e": 5798, "s": 5788, "text": "LOG10 (X)" }, { "code": null, "e": 5855, "s": 5798, "text": "It returns the common logarithmic (base 10) value of X. " }, { "code": null, "e": 5863, "s": 5855, "text": "SIN (X)" }, { "code": null, "e": 5907, "s": 5863, "text": "It returns the sine of argument in radians." }, { "code": null, "e": 5916, "s": 5907, "text": "SINH (X)" }, { "code": null, "e": 5971, "s": 5916, "text": "It returns the hyperbolic sine of argument in radians." }, { "code": null, "e": 5980, "s": 5971, "text": "SQRT (X)" }, { "code": null, "e": 6009, "s": 5980, "text": "It returns square root of X." }, { "code": null, "e": 6017, "s": 6009, "text": "TAN (X)" }, { "code": null, "e": 6064, "s": 6017, "text": "It returns the tangent of argument in radians." }, { "code": null, "e": 6073, "s": 6064, "text": "TANH (X)" }, { "code": null, "e": 6131, "s": 6073, "text": "It returns the hyperbolic tangent of argument in radians." }, { "code": null, "e": 6254, "s": 6131, "text": "The following program computes the horizontal and vertical position x and y respectively of a projectile after a time, t −" }, { "code": null, "e": 6304, "s": 6254, "text": "Where, x = u t cos a and y = u t sin a - g t2 / 2" }, { "code": null, "e": 6763, "s": 6304, "text": "program projectileMotion \nimplicit none \n\n ! define constants \n real, parameter :: g = 9.8 \n real, parameter :: pi = 3.1415927 \n \n !define variables\n real :: a, t, u, x, y \n \n !values for a, t, and u \n a = 45.0\n t = 20.0\n u = 10.0\n \n ! convert angle to radians \n a = a * pi / 180.0 \n x = u * cos(a) * t \n y = u * sin(a) * t - 0.5 * g * t * t \n \n write(*,*) 'x: ',x,' y: ',y \n \nend program projectileMotion" }, { "code": null, "e": 6846, "s": 6763, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 6879, "s": 6846, "text": "x: 141.421356 y: -1818.57861 \n" }, { "code": null, "e": 7087, "s": 6879, "text": "These functions work with a certain model of integer and floating-point arithmetic. The functions return properties of numbers of the same kind as the variable X, which can be real and in some cases integer." }, { "code": null, "e": 7098, "s": 7087, "text": "DIGITS (X)" }, { "code": null, "e": 7156, "s": 7098, "text": "It returns the number of significant digits of the model." }, { "code": null, "e": 7168, "s": 7156, "text": "EPSILON (X)" }, { "code": null, "e": 7359, "s": 7168, "text": "It returns the number that is almost negligible compared to one. In other words, it returns the smallest value such that REAL( 1.0, KIND(X)) + EPSILON(X) is not equal to REAL( 1.0, KIND(X))." }, { "code": null, "e": 7368, "s": 7359, "text": "HUGE (X)" }, { "code": null, "e": 7411, "s": 7368, "text": "It returns the largest number of the model" }, { "code": null, "e": 7427, "s": 7411, "text": "MAXEXPONENT (X)" }, { "code": null, "e": 7472, "s": 7427, "text": "It returns the maximum exponent of the model" }, { "code": null, "e": 7488, "s": 7472, "text": "MINEXPONENT (X)" }, { "code": null, "e": 7533, "s": 7488, "text": "It returns the minimum exponent of the model" }, { "code": null, "e": 7547, "s": 7533, "text": "PRECISION (X)" }, { "code": null, "e": 7580, "s": 7547, "text": "It returns the decimal precision" }, { "code": null, "e": 7590, "s": 7580, "text": "RADIX (X)" }, { "code": null, "e": 7623, "s": 7590, "text": "It returns the base of the model" }, { "code": null, "e": 7633, "s": 7623, "text": "RANGE (X)" }, { "code": null, "e": 7671, "s": 7633, "text": "It returns the decimal exponent range" }, { "code": null, "e": 7680, "s": 7671, "text": "TINY (X)" }, { "code": null, "e": 7733, "s": 7680, "text": "It returns the smallest positive number of the model" }, { "code": null, "e": 7746, "s": 7733, "text": "EXPONENT (X)" }, { "code": null, "e": 7793, "s": 7746, "text": "It returns the exponent part of a model number" }, { "code": null, "e": 7806, "s": 7793, "text": "FRACTION (X)" }, { "code": null, "e": 7849, "s": 7806, "text": "It returns the fractional part of a number" }, { "code": null, "e": 7864, "s": 7849, "text": "NEAREST (X, S)" }, { "code": null, "e": 7933, "s": 7864, "text": "It returns the nearest different processor number in given direction" }, { "code": null, "e": 7947, "s": 7933, "text": "RRSPACING (X)" }, { "code": null, "e": 8032, "s": 7947, "text": "It returns the reciprocal of the relative spacing of model numbers near given number" }, { "code": null, "e": 8045, "s": 8032, "text": "SCALE (X, I)" }, { "code": null, "e": 8098, "s": 8045, "text": "It multiplies a real by its base to an integer power" }, { "code": null, "e": 8118, "s": 8098, "text": "SET_EXPONENT (X, I)" }, { "code": null, "e": 8159, "s": 8118, "text": "it returns the exponent part of a number" }, { "code": null, "e": 8171, "s": 8159, "text": "SPACING (X)" }, { "code": null, "e": 8238, "s": 8171, "text": "It returns the absolute spacing of model numbers near given number" }, { "code": null, "e": 8251, "s": 8238, "text": "BIT_SIZE (I)" }, { "code": null, "e": 8294, "s": 8251, "text": "It returns the number of bits of the model" }, { "code": null, "e": 8309, "s": 8294, "text": "BTEST (I, POS)" }, { "code": null, "e": 8321, "s": 8309, "text": "Bit testing" }, { "code": null, "e": 8333, "s": 8321, "text": "IAND (I, J)" }, { "code": null, "e": 8345, "s": 8333, "text": "Logical AND" }, { "code": null, "e": 8360, "s": 8345, "text": "IBCLR (I, POS)" }, { "code": null, "e": 8370, "s": 8360, "text": "Clear bit" }, { "code": null, "e": 8390, "s": 8370, "text": "IBITS (I, POS, LEN)" }, { "code": null, "e": 8405, "s": 8390, "text": "Bit extraction" }, { "code": null, "e": 8420, "s": 8405, "text": "IBSET (I, POS)" }, { "code": null, "e": 8428, "s": 8420, "text": "Set bit" }, { "code": null, "e": 8440, "s": 8428, "text": "IEOR (I, J)" }, { "code": null, "e": 8453, "s": 8440, "text": "Exclusive OR" }, { "code": null, "e": 8464, "s": 8453, "text": "IOR (I, J)" }, { "code": null, "e": 8477, "s": 8464, "text": "Inclusive OR" }, { "code": null, "e": 8494, "s": 8477, "text": "ISHFT (I, SHIFT)" }, { "code": null, "e": 8508, "s": 8494, "text": "Logical shift" }, { "code": null, "e": 8535, "s": 8508, "text": "ISHFTC (I, SHIFT [, SIZE])" }, { "code": null, "e": 8550, "s": 8535, "text": "Circular shift" }, { "code": null, "e": 8558, "s": 8550, "text": "NOT (I)" }, { "code": null, "e": 8577, "s": 8558, "text": "Logical complement" }, { "code": null, "e": 8587, "s": 8577, "text": "ACHAR (I)" }, { "code": null, "e": 8649, "s": 8587, "text": "It returns the Ith character in the ASCII collating sequence." }, { "code": null, "e": 8666, "s": 8649, "text": "ADJUSTL (STRING)" }, { "code": null, "e": 8750, "s": 8666, "text": "It adjusts string left by removing any leading blanks and inserting trailing blanks" }, { "code": null, "e": 8767, "s": 8750, "text": "ADJUSTR (STRING)" }, { "code": null, "e": 8849, "s": 8767, "text": "It adjusts string right by removing trailing blanks and inserting leading blanks." }, { "code": null, "e": 8867, "s": 8849, "text": "CHAR (I [, KIND])" }, { "code": null, "e": 8939, "s": 8867, "text": "It returns the Ith character in the machine specific collating sequence" }, { "code": null, "e": 8950, "s": 8939, "text": "IACHAR (C)" }, { "code": null, "e": 9024, "s": 8950, "text": "It returns the position of the character in the ASCII collating sequence." }, { "code": null, "e": 9034, "s": 9024, "text": "ICHAR (C)" }, { "code": null, "e": 9131, "s": 9034, "text": "It returns the position of the character in the machine (processor) specific collating sequence." }, { "code": null, "e": 9166, "s": 9131, "text": "INDEX (STRING, SUBSTRING [, BACK])" }, { "code": null, "e": 9266, "s": 9166, "text": "It returns the leftmost (rightmost if BACK is .TRUE.) starting position of SUBSTRING within STRING." }, { "code": null, "e": 9279, "s": 9266, "text": "LEN (STRING)" }, { "code": null, "e": 9314, "s": 9279, "text": "It returns the length of a string." }, { "code": null, "e": 9332, "s": 9314, "text": "LEN_TRIM (STRING)" }, { "code": null, "e": 9401, "s": 9332, "text": "It returns the length of a string without trailing blank characters." }, { "code": null, "e": 9426, "s": 9401, "text": "LGE (STRING_A, STRING_B)" }, { "code": null, "e": 9458, "s": 9426, "text": "Lexically greater than or equal" }, { "code": null, "e": 9483, "s": 9458, "text": "LGT (STRING_A, STRING_B)" }, { "code": null, "e": 9506, "s": 9483, "text": "Lexically greater than" }, { "code": null, "e": 9531, "s": 9506, "text": "LLE (STRING_A, STRING_B)" }, { "code": null, "e": 9560, "s": 9531, "text": "Lexically less than or equal" }, { "code": null, "e": 9585, "s": 9560, "text": "LLT (STRING_A, STRING_B)" }, { "code": null, "e": 9605, "s": 9585, "text": "Lexically less than" }, { "code": null, "e": 9630, "s": 9605, "text": "REPEAT (STRING, NCOPIES)" }, { "code": null, "e": 9653, "s": 9630, "text": "Repeated concatenation" }, { "code": null, "e": 9681, "s": 9653, "text": "SCAN (STRING, SET [, BACK])" }, { "code": null, "e": 9809, "s": 9681, "text": "It returns the index of the leftmost (rightmost if BACK is .TRUE.) character of STRING that belong to SET, or 0 if none belong." }, { "code": null, "e": 9823, "s": 9809, "text": "TRIM (STRING)" }, { "code": null, "e": 9857, "s": 9823, "text": "Removes trailing blank characters" }, { "code": null, "e": 9887, "s": 9857, "text": "VERIFY (STRING, SET [, BACK])" }, { "code": null, "e": 9930, "s": 9887, "text": "Verifies the set of characters in a string" }, { "code": null, "e": 9939, "s": 9930, "text": "KIND (X)" }, { "code": null, "e": 9981, "s": 9939, "text": "It returns the kind type parameter value." }, { "code": null, "e": 10003, "s": 9981, "text": "SELECTED_INT_KIND (R)" }, { "code": null, "e": 10067, "s": 10003, "text": "It returns kind of type parameter for specified exponent range." }, { "code": null, "e": 10095, "s": 10067, "text": "SELECTED_REAL_KIND ([P, R])" }, { "code": null, "e": 10153, "s": 10095, "text": "Real kind type parameter value, given precision and range" }, { "code": null, "e": 10174, "s": 10153, "text": "LOGICAL (L [, KIND])" }, { "code": null, "e": 10250, "s": 10174, "text": "Convert between objects of type logical with different kind type parameters" }, { "code": null, "e": 10257, "s": 10250, "text": " Print" }, { "code": null, "e": 10268, "s": 10257, "text": " Add Notes" } ]
Pytorch Implementation of Perceptual Losses for Real-Time Style Transfer | by Ceshine Lee | Towards Data Science
In this post I’ll briefly go through my experience of coding and training real-time style transfer models in Pytorch. The work is heavily based on Abhishek Kadian’s implementation, which works perfectly Fine. I’ve made some modification both for fun and to be more familiar with Pytorch. The model uses the method described in Perceptual Losses for Real-Time Style Transfer and Super-Resolution along with Instance Normalization. (Super-Resolution is not implemented) Three major parts I’ve added to the implementation: Use the official pre-trained VGG modelOutput intermediate results during trainingAdd Total Variation Regularization as described in the paper Use the official pre-trained VGG model Output intermediate results during training Add Total Variation Regularization as described in the paper First we need to take a quick look at the model structure. The main contribution of the paper is proposing that feeding forward the generated image to a pre-trained image classification model and extract the output from some intermediate layers to calculate losses would produce similar results of Gatys et al but with significantly less computational resources. So the first part of the structure is a “Image Transform Net” which generate new image from the input image. And the second part is simply a “Loss Network”, which is the feeding forward part.The weight of the loss network is fixed and will not be updated during training. Abhishek’s implementation uses a traditional VGG model with BGR channel order and [-103.939, -116.779, -123.680] offsets to center channel means (it seems to also be what the paper used). The official pytorch pre-trained models use a unified format: All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225] Here’s the code to extract outputs from the official pre-trained model: LossOutput = namedtuple("LossOutput", ["relu1_2", "relu2_2", "relu3_3", "relu4_3"])# https://discuss.pytorch.org/t/how-to-extract-features-of-an-image-from-a-trained-model/119/3class LossNetwork(torch.nn.Module): def __init__(self, vgg_model): super(LossNetwork, self).__init__() self.vgg_layers = vgg_model.features self.layer_name_mapping = { '3': "relu1_2", '8': "relu2_2", '15': "relu3_3", '22': "relu4_3" } def forward(self, x): output = {} for name, module in self.vgg_layers._modules.items(): x = module(x) if name in self.layer_name_mapping: output[self.layer_name_mapping[name]] = x return LossOutput(**output) To initiate: vgg_model = vgg.vgg16(pretrained=True)if torch.cuda.is_available(): vgg_model.cuda()loss_network = LossNetwork(vgg_model)loss_network.eval() There’s no batch normalization in VGG model unless explicitly specified. So the values of activation is on a significant different scale from the previous implementation. Generally you’d need to scale up the style loss (gram matrix) because most activation is less than 1, and taking dot products would make it smaller. This helps a lot when tuning content weight against style weight ratio. You can stop training and re-tune the parameters during training, instead of having to wait 4 hours for the training to complete. The paper mentioned this in the Experiment section, but it seems Abhishek didn’t implement it: The output images are regularized with total variation regularization with a strength of between 1 × 10e-6 and 1 ×10e-4, chosen via cross-validation per style target. It is quite easy to implement: reg_loss = REGULARIZATION * ( torch.sum(torch.abs(y[:, :, :, :-1] - y[:, :, :, 1:])) + torch.sum(torch.abs(y[:, :, :-1, :] - y[:, :, 1:, :]))) Pytorch autograd will handle backward propagation for you. In practice I haven’t found out how to tune the regularization weight properly. So far the weights I used seemed not making much difference in the output images. The model is trained using Microsoft COCO dataset. The image is resized to 256 x 256, and network is trained around 2 epochs with a batch size of 4 (the same as the paper). The training time using a GTX1070 is around 4 to 4.5 hours, on par with what the paper reports. Based on my rough experiment, a lot of computation time is used in normalizing the input images. The training might be faster if we use the original VGG model (not tested). The content weight v.s. style ratio is usually set to 1 : 10e3 ~ 10e5 after some manual tuning. Because the network is fully convolutional, you could feed much bigger or smaller images than 256 x 256 to the network in test time. I write some script to transform animated GIFs and videos using scikit-video and ffmpeg for fun: Original video credit: Backpacking Around New Zealand. The processing speed is around 4 frames per second. I didn’t align the frame rate, so the time in the following videos is slower than the original one. Remember to clip output numpy array to [0, 255] range and cast it to uint8. Otherwise matplot.pyplot.imshow would show weird results. Spent quite some time debugging this in the wrong direction thinking the the model training code has some serious bugs.Remember to use model.train() and model.eval(). It only has effects on models containing dropout or batch normalization layers, but it is a good habit to keep. Especially easy to forget if you’re coming from Keras. Remember to clip output numpy array to [0, 255] range and cast it to uint8. Otherwise matplot.pyplot.imshow would show weird results. Spent quite some time debugging this in the wrong direction thinking the the model training code has some serious bugs. Remember to use model.train() and model.eval(). It only has effects on models containing dropout or batch normalization layers, but it is a good habit to keep. Especially easy to forget if you’re coming from Keras. Sometimes the network generate some weird patches in open areas. Don’t know where it’s from and how to fix it yet.Maybe assigning different weights to relu1_2, relu2_2, relu3_3, relu4_3 outputs for different style image would yield better results.Try using different pre-trained networks as the loss network.Try implement Super-Resolution as wellCompare results from CycleGAN. I tried CycleGAN but the training time is too long and I lost patience at the time. Should try again later.Regularize against variation between consecutive frames when generating videos. This should help reduce flickering during playback. I’ve heard people using this technique, but have no idea how to actually do it yet. Sometimes the network generate some weird patches in open areas. Don’t know where it’s from and how to fix it yet. Maybe assigning different weights to relu1_2, relu2_2, relu3_3, relu4_3 outputs for different style image would yield better results. Try using different pre-trained networks as the loss network. Try implement Super-Resolution as well Compare results from CycleGAN. I tried CycleGAN but the training time is too long and I lost patience at the time. Should try again later. Regularize against variation between consecutive frames when generating videos. This should help reduce flickering during playback. I’ve heard people using this technique, but have no idea how to actually do it yet. The code is located at this Github repo. Since this is basically a personal fun project, the documentation is nonexistent and the main part of the code resides in two Jupyter notebooks: style-transfer.ipynb and Video.ipynb. Sorry about that. (2011/11/30 Update: Fixed links to the notebook above. In the meantime, a newer version of the notebooks is available here: 01-image-style-transfer.ipynb and 03-Video-Creation.ipynb.)
[ { "code": null, "e": 460, "s": 172, "text": "In this post I’ll briefly go through my experience of coding and training real-time style transfer models in Pytorch. The work is heavily based on Abhishek Kadian’s implementation, which works perfectly Fine. I’ve made some modification both for fun and to be more familiar with Pytorch." }, { "code": null, "e": 640, "s": 460, "text": "The model uses the method described in Perceptual Losses for Real-Time Style Transfer and Super-Resolution along with Instance Normalization. (Super-Resolution is not implemented)" }, { "code": null, "e": 692, "s": 640, "text": "Three major parts I’ve added to the implementation:" }, { "code": null, "e": 834, "s": 692, "text": "Use the official pre-trained VGG modelOutput intermediate results during trainingAdd Total Variation Regularization as described in the paper" }, { "code": null, "e": 873, "s": 834, "text": "Use the official pre-trained VGG model" }, { "code": null, "e": 917, "s": 873, "text": "Output intermediate results during training" }, { "code": null, "e": 978, "s": 917, "text": "Add Total Variation Regularization as described in the paper" }, { "code": null, "e": 1613, "s": 978, "text": "First we need to take a quick look at the model structure. The main contribution of the paper is proposing that feeding forward the generated image to a pre-trained image classification model and extract the output from some intermediate layers to calculate losses would produce similar results of Gatys et al but with significantly less computational resources. So the first part of the structure is a “Image Transform Net” which generate new image from the input image. And the second part is simply a “Loss Network”, which is the feeding forward part.The weight of the loss network is fixed and will not be updated during training." }, { "code": null, "e": 1863, "s": 1613, "text": "Abhishek’s implementation uses a traditional VGG model with BGR channel order and [-103.939, -116.779, -123.680] offsets to center channel means (it seems to also be what the paper used). The official pytorch pre-trained models use a unified format:" }, { "code": null, "e": 2185, "s": 1863, "text": "All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225]" }, { "code": null, "e": 2257, "s": 2185, "text": "Here’s the code to extract outputs from the official pre-trained model:" }, { "code": null, "e": 3017, "s": 2257, "text": "LossOutput = namedtuple(\"LossOutput\", [\"relu1_2\", \"relu2_2\", \"relu3_3\", \"relu4_3\"])# https://discuss.pytorch.org/t/how-to-extract-features-of-an-image-from-a-trained-model/119/3class LossNetwork(torch.nn.Module): def __init__(self, vgg_model): super(LossNetwork, self).__init__() self.vgg_layers = vgg_model.features self.layer_name_mapping = { '3': \"relu1_2\", '8': \"relu2_2\", '15': \"relu3_3\", '22': \"relu4_3\" } def forward(self, x): output = {} for name, module in self.vgg_layers._modules.items(): x = module(x) if name in self.layer_name_mapping: output[self.layer_name_mapping[name]] = x return LossOutput(**output)" }, { "code": null, "e": 3030, "s": 3017, "text": "To initiate:" }, { "code": null, "e": 3174, "s": 3030, "text": "vgg_model = vgg.vgg16(pretrained=True)if torch.cuda.is_available(): vgg_model.cuda()loss_network = LossNetwork(vgg_model)loss_network.eval()" }, { "code": null, "e": 3494, "s": 3174, "text": "There’s no batch normalization in VGG model unless explicitly specified. So the values of activation is on a significant different scale from the previous implementation. Generally you’d need to scale up the style loss (gram matrix) because most activation is less than 1, and taking dot products would make it smaller." }, { "code": null, "e": 3696, "s": 3494, "text": "This helps a lot when tuning content weight against style weight ratio. You can stop training and re-tune the parameters during training, instead of having to wait 4 hours for the training to complete." }, { "code": null, "e": 3791, "s": 3696, "text": "The paper mentioned this in the Experiment section, but it seems Abhishek didn’t implement it:" }, { "code": null, "e": 3958, "s": 3791, "text": "The output images are regularized with total variation regularization with a strength of between 1 × 10e-6 and 1 ×10e-4, chosen via cross-validation per style target." }, { "code": null, "e": 3989, "s": 3958, "text": "It is quite easy to implement:" }, { "code": null, "e": 4139, "s": 3989, "text": "reg_loss = REGULARIZATION * ( torch.sum(torch.abs(y[:, :, :, :-1] - y[:, :, :, 1:])) + torch.sum(torch.abs(y[:, :, :-1, :] - y[:, :, 1:, :])))" }, { "code": null, "e": 4360, "s": 4139, "text": "Pytorch autograd will handle backward propagation for you. In practice I haven’t found out how to tune the regularization weight properly. So far the weights I used seemed not making much difference in the output images." }, { "code": null, "e": 4898, "s": 4360, "text": "The model is trained using Microsoft COCO dataset. The image is resized to 256 x 256, and network is trained around 2 epochs with a batch size of 4 (the same as the paper). The training time using a GTX1070 is around 4 to 4.5 hours, on par with what the paper reports. Based on my rough experiment, a lot of computation time is used in normalizing the input images. The training might be faster if we use the original VGG model (not tested). The content weight v.s. style ratio is usually set to 1 : 10e3 ~ 10e5 after some manual tuning." }, { "code": null, "e": 5128, "s": 4898, "text": "Because the network is fully convolutional, you could feed much bigger or smaller images than 256 x 256 to the network in test time. I write some script to transform animated GIFs and videos using scikit-video and ffmpeg for fun:" }, { "code": null, "e": 5335, "s": 5128, "text": "Original video credit: Backpacking Around New Zealand. The processing speed is around 4 frames per second. I didn’t align the frame rate, so the time in the following videos is slower than the original one." }, { "code": null, "e": 5803, "s": 5335, "text": "Remember to clip output numpy array to [0, 255] range and cast it to uint8. Otherwise matplot.pyplot.imshow would show weird results. Spent quite some time debugging this in the wrong direction thinking the the model training code has some serious bugs.Remember to use model.train() and model.eval(). It only has effects on models containing dropout or batch normalization layers, but it is a good habit to keep. Especially easy to forget if you’re coming from Keras." }, { "code": null, "e": 6057, "s": 5803, "text": "Remember to clip output numpy array to [0, 255] range and cast it to uint8. Otherwise matplot.pyplot.imshow would show weird results. Spent quite some time debugging this in the wrong direction thinking the the model training code has some serious bugs." }, { "code": null, "e": 6272, "s": 6057, "text": "Remember to use model.train() and model.eval(). It only has effects on models containing dropout or batch normalization layers, but it is a good habit to keep. Especially easy to forget if you’re coming from Keras." }, { "code": null, "e": 6972, "s": 6272, "text": "Sometimes the network generate some weird patches in open areas. Don’t know where it’s from and how to fix it yet.Maybe assigning different weights to relu1_2, relu2_2, relu3_3, relu4_3 outputs for different style image would yield better results.Try using different pre-trained networks as the loss network.Try implement Super-Resolution as wellCompare results from CycleGAN. I tried CycleGAN but the training time is too long and I lost patience at the time. Should try again later.Regularize against variation between consecutive frames when generating videos. This should help reduce flickering during playback. I’ve heard people using this technique, but have no idea how to actually do it yet." }, { "code": null, "e": 7087, "s": 6972, "text": "Sometimes the network generate some weird patches in open areas. Don’t know where it’s from and how to fix it yet." }, { "code": null, "e": 7221, "s": 7087, "text": "Maybe assigning different weights to relu1_2, relu2_2, relu3_3, relu4_3 outputs for different style image would yield better results." }, { "code": null, "e": 7283, "s": 7221, "text": "Try using different pre-trained networks as the loss network." }, { "code": null, "e": 7322, "s": 7283, "text": "Try implement Super-Resolution as well" }, { "code": null, "e": 7461, "s": 7322, "text": "Compare results from CycleGAN. I tried CycleGAN but the training time is too long and I lost patience at the time. Should try again later." }, { "code": null, "e": 7677, "s": 7461, "text": "Regularize against variation between consecutive frames when generating videos. This should help reduce flickering during playback. I’ve heard people using this technique, but have no idea how to actually do it yet." }, { "code": null, "e": 7919, "s": 7677, "text": "The code is located at this Github repo. Since this is basically a personal fun project, the documentation is nonexistent and the main part of the code resides in two Jupyter notebooks: style-transfer.ipynb and Video.ipynb. Sorry about that." } ]
Embedded or internal Style Sheets in CSS
CSS files can be embedded internally by declaring them in <style> tag. This decreases the load time of the webpage. Although embedded CSS declarations allow dynamic styles, it should be downloaded at every page request as internal CSS can’t be cached. Internal CSS are declared in <style>tag inside <head> tag. The syntax for embedding CSS files is as follows − <style> /*declarations*/ </style> The following examples illustrate how CSS files are embedded − Live Demo <!DOCTYPE html> <html> <head> <style> article { font-size: 1.3em; font-family: cursive; } div { float: left; margin-left: 20px; width: 30px; height: 30px; background-color: lightgreen; box-shadow: 8px 5px 0 2px lightcoral; } </style> </head> <body> <article>Demo text</article> <div></div> <div></div> </body> </html> This gives the following output − Live Demo <!DOCTYPE html> <html> <head> <style> div { float: left; margin-left: 20px; width: 60px; height: 30px; border-top-right-radius: 50px; border-bottom-right-radius: 50px; background-color: lightgreen; box-shadow: inset 5px 0 lightcoral; } div + div { background-color: lightblue; border-top-left-radius: 50px; border-bottom-left-radius: 50px; } </style> </head> <body> <div></div> <div></div> </body> </html> This gives the following output −
[ { "code": null, "e": 1373, "s": 1062, "text": "CSS files can be embedded internally by declaring them in <style> tag. This decreases the load time of the webpage. Although embedded CSS declarations allow dynamic styles, it should be downloaded at every page request as internal CSS can’t be cached. Internal CSS are declared in <style>tag inside <head> tag." }, { "code": null, "e": 1424, "s": 1373, "text": "The syntax for embedding CSS files is as follows −" }, { "code": null, "e": 1461, "s": 1424, "text": "<style>\n /*declarations*/\n</style>" }, { "code": null, "e": 1524, "s": 1461, "text": "The following examples illustrate how CSS files are embedded −" }, { "code": null, "e": 1535, "s": 1524, "text": " Live Demo" }, { "code": null, "e": 1877, "s": 1535, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\narticle {\n font-size: 1.3em;\n font-family: cursive;\n}\ndiv {\n float: left;\n margin-left: 20px;\n width: 30px;\n height: 30px;\n background-color: lightgreen;\n box-shadow: 8px 5px 0 2px lightcoral;\n}\n</style>\n</head>\n<body>\n<article>Demo text</article>\n<div></div>\n<div></div>\n</body>\n</html>" }, { "code": null, "e": 1911, "s": 1877, "text": "This gives the following output −" }, { "code": null, "e": 1922, "s": 1911, "text": " Live Demo" }, { "code": null, "e": 2361, "s": 1922, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n float: left;\n margin-left: 20px;\n width: 60px;\n height: 30px;\n border-top-right-radius: 50px;\n border-bottom-right-radius: 50px;\n background-color: lightgreen;\n box-shadow: inset 5px 0 lightcoral;\n}\ndiv + div {\n background-color: lightblue;\n border-top-left-radius: 50px;\n border-bottom-left-radius: 50px;\n}\n</style>\n</head>\n<body>\n<div></div>\n<div></div>\n</body>\n</html>" }, { "code": null, "e": 2395, "s": 2361, "text": "This gives the following output −" } ]
Connect Nodes at Same Level | Practice | GeeksforGeeks
Given a binary tree, connect the nodes that are at same level. You'll be given an addition nextRight pointer for the same. Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node. 10 10 ------> NULL / \ / \ 3 5 => 3 ------> 5 --------> NULL / \ \ / \ \ 4 1 2 4 --> 1 -----> 2 -------> NULL Example 1: Input: 3 / \ 1 2 Output: 3 1 2 1 3 2 Explanation:The connected tree is 3 ------> NULL / \ 1-----> 2 ------ NULL Example 2: Input: 10 / \ 20 30 / \ 40 60 Output: 10 20 30 40 60 40 20 60 10 30 Explanation:The connected tree is 10 ----------> NULL / \ 20 ------> 30 -------> NULL / \ 40 ----> 60 ----------> NULL Your Task: You don't have to take input. Complete the function connect() that takes root as parameter and connects the nodes at same level. The printing is done by the driver code. First line of the output will be level order traversal and second line will be inorder travsersal Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 ≤ Number of nodes ≤ 105 0 ≤ Data of a node ≤ 105 0 cs20015in 7 hours void connect(Node *root) { queue<Node*>q; q.push(root); while(!q.empty()){ int n = q.size(); for(int i= 0; i<n; i++){ Node*temp = q.front(); q.pop(); if(q.empty()) temp->nextRight=NULL; else{ temp->nextRight = q.front(); } if(temp->left) q.push(temp->left); if(temp->right); q.push(temp->right); } } } }; 0 lokeshdohare1231 day ago JAVA Code: public void connect(Node node) { Queue<Node> q = new LinkedList<>(); q.add(node); int len=0; while(!q.isEmpty()) { ArrayList<Node> temp = new ArrayList<Node>(); len=q.size(); for(int i=0;i<len;i++) { Node curr = q.remove(); temp.add(curr); if(curr.left!=null) q.add(curr.left); if(curr.right!=null) q.add(curr.right); } for(int i=0;i<temp.size();i++) { if(i==(temp.size()-1)) { (temp.get(i)).nextRight=null; } else { (temp.get(i)).nextRight = temp.get(i+1); } } } } 0 rmn51243 days ago class Solution { public: //Function to connect nodes at same level. void connect(Node *p) { queue< Node * > qq; qq.push(p); while(!qq.empty()){ int sz = qq.size(); while(sz > 0){ Node* node = qq.front(); qq.pop(); if(sz > 1){ node->nextRight = qq.front(); }else{ node->nextRight = NULL; } if(node->left != NULL) qq.push(node->left); if(node->right != NULL) qq.push(node->right); sz--; } } } }; 0 dharpranoy22555 days ago Solution LinkedList<Node> que = new LinkedList<>(); que.add(root); while (que.isEmpty()==false){ int n=que.size(); for (int i=0;i<n;i++){ Node cur = que.poll(); if (i==n-1){ cur.nextRight=null; }else{ cur.nextRight=que.get(0); } if (cur.left!=null){ que.add(cur.left); } if (cur.right!=null){ que.add(cur.right); } } } 0 hr061 week ago class Solution { public: //Function to connect nodes at same level. void connect(Node *root) { // Your Code Here if(!root) { return; } // we use queue for level order traversal queue<Node*> q; q.push(root); while(!q.empty()) { int size = q.size(); while(size--) { Node* frontNode = q.front(); q.pop(); if(!size) frontNode->nextRight = NULL; else frontNode->nextRight = q.front(); if(frontNode->left) q.push(frontNode->left); if(frontNode->right) q.push(frontNode->right); } } } }; 0 srujugowda4561 week ago C++ solution using level order traversal class Solution { public: //Function to connect nodes at same level. void connect(Node *root) { queue<Node*> q; q.push(root); while(!q.empty()){ int size=q.size(); for(int i=0;i<size;i++){ Node* temp=q.front(); q.pop(); if(q.empty() || i==size-1){ temp->nextRight=NULL; }else{ temp->nextRight=q.front(); } if(temp->left){ q.push(temp->left); } if(temp->right){ q.push(temp->right); } } } } }; 0 anugrahlko1 week ago class Solution{ //Function to connect nodes at same level. static HashMap<Integer, ArrayList<Node>> map; public void connect(Node root) { int level=0; map = new HashMap<Integer, ArrayList<Node>>(); leveOrderTraversal(root, level, map); int i=0; while(map.containsKey(i)){ ArrayList<Node> a = map.get(i); int j; for( j=0;j<a.size()-1;j++){ a.get(j).nextRight =a.get(j+1); } a.get(j).nextRight = null; i++; } } static void leveOrderTraversal(Node node,int l,HashMap<Integer, ArrayList<Node>> map){ if(node==null)return; if(map.containsKey(l)){ ArrayList<Node> arr= map.get(l); arr.add(node); map.put(l,arr); }else{ ArrayList<Node> arr= new ArrayList<Node>(); arr.add(node); map.put(l,arr); } leveOrderTraversal(node.left, l+1, map); leveOrderTraversal(node.right, l+1, map); }} +1 suhitgupta1112 weeks ago class Solution{ //Function to connect nodes at same level. public void connect(Node root) { // Your code goes here. if(root==null) return; Queue<Node> q = new LinkedList<>(); q.add(root); while(!q.isEmpty()){ int size=q.size(); for(int i=0;i<size;i++){ Node curr=q.poll(); if(curr.left!=null) q.add(curr.left); if(curr.right!=null) q.add(curr.right); if(i!=size-1) curr.nextRight=q.peek(); } } }} 0 amankumar2783 weeks ago Java Solution: using QUEUE class Solution{ //Function to connect nodes at same level. public void connect(Node root) { if(root==null){ return ; } Queue<Node> q=new LinkedList<>(); q.add(root); int curr=1; int next=0; while(curr!=0){ Node temp=q.poll(); if(temp.left!=null){ q.add(temp.left); next++; } if(temp.right!=null){ q.add(temp.right); next++; } if(curr>1){ temp.nextRight=q.peek(); }else{ temp.nextRight=null; } curr--; if(curr==0){ curr=next; next=0; } } }} 0 harshrauth3 weeks ago class Solution{ public: //Function to connect nodes at same level. void connect(Node *root) { // Your Code Here queue<Node*>q; q.push(root); q.push(NULL); while(!q.empty()) { if(q.front()!=NULL) { Node * temp=q.front(); q.pop(); temp->nextRight=q.front(); if(temp->left!=NULL) q.push(temp->left); if(temp->right!=NULL) q.push(temp->right); } else { if(q.size()!=1) q.push(NULL); q.pop(); } } } }; 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": 361, "s": 238, "text": "Given a binary tree, connect the nodes that are at same level. You'll be given an addition nextRight pointer for the same." }, { "code": null, "e": 737, "s": 361, "text": "Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node.\n 10 10 ------> NULL\n / \\ / \\\n 3 5 => 3 ------> 5 --------> NULL\n / \\ \\ / \\ \\\n 4 1 2 4 --> 1 -----> 2 -------> NULL" }, { "code": null, "e": 750, "s": 739, "text": "Example 1:" }, { "code": null, "e": 897, "s": 750, "text": "Input:\n 3\n / \\\n 1 2\nOutput:\n3 1 2\n1 3 2\nExplanation:The connected tree is\n 3 ------> NULL\n / \\\n 1-----> 2 ------ NULL\n" }, { "code": null, "e": 908, "s": 897, "text": "Example 2:" }, { "code": null, "e": 1148, "s": 908, "text": "Input:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput:\n10 20 30 40 60\n40 20 60 10 30\nExplanation:The connected tree is\n 10 ----------> NULL\n / \\\n 20 ------> 30 -------> NULL\n / \\\n 40 ----> 60 ----------> NULL" }, { "code": null, "e": 1427, "s": 1148, "text": "Your Task:\nYou don't have to take input. Complete the function connect() that takes root as parameter and connects the nodes at same level. The printing is done by the driver code. First line of the output will be level order traversal and second line will be inorder travsersal" }, { "code": null, "e": 1491, "s": 1427, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1555, "s": 1491, "text": "Constraints:\n1 ≤ Number of nodes ≤ 105\n0 ≤ Data of a node ≤ 105" }, { "code": null, "e": 1557, "s": 1555, "text": "0" }, { "code": null, "e": 1575, "s": 1557, "text": "cs20015in 7 hours" }, { "code": null, "e": 2137, "s": 1575, "text": " void connect(Node *root) { queue<Node*>q; q.push(root); while(!q.empty()){ int n = q.size(); for(int i= 0; i<n; i++){ Node*temp = q.front(); q.pop(); if(q.empty()) temp->nextRight=NULL; else{ temp->nextRight = q.front(); } if(temp->left) q.push(temp->left); if(temp->right); q.push(temp->right); } } } }; " }, { "code": null, "e": 2141, "s": 2139, "text": "0" }, { "code": null, "e": 2166, "s": 2141, "text": "lokeshdohare1231 day ago" }, { "code": null, "e": 2177, "s": 2166, "text": "JAVA Code:" }, { "code": null, "e": 2984, "s": 2179, "text": "public void connect(Node node) { Queue<Node> q = new LinkedList<>(); q.add(node); int len=0; while(!q.isEmpty()) { ArrayList<Node> temp = new ArrayList<Node>(); len=q.size(); for(int i=0;i<len;i++) { Node curr = q.remove(); temp.add(curr); if(curr.left!=null) q.add(curr.left); if(curr.right!=null) q.add(curr.right); } for(int i=0;i<temp.size();i++) { if(i==(temp.size()-1)) { (temp.get(i)).nextRight=null; } else { (temp.get(i)).nextRight = temp.get(i+1); } } } }" }, { "code": null, "e": 2986, "s": 2984, "text": "0" }, { "code": null, "e": 3004, "s": 2986, "text": "rmn51243 days ago" }, { "code": null, "e": 3614, "s": 3004, "text": "class Solution\n{\n public:\n //Function to connect nodes at same level.\n void connect(Node *p)\n {\n queue< Node * > qq;\n qq.push(p);\n while(!qq.empty()){\n int sz = qq.size();\n while(sz > 0){\n Node* node = qq.front();\n qq.pop();\n \n if(sz > 1){\n node->nextRight = qq.front();\n }else{\n node->nextRight = NULL;\n }\n if(node->left != NULL)\n qq.push(node->left);\n if(node->right != NULL)\n qq.push(node->right);\n sz--;\n }\n }\n }\n \n};" }, { "code": null, "e": 3616, "s": 3614, "text": "0" }, { "code": null, "e": 3641, "s": 3616, "text": "dharpranoy22555 days ago" }, { "code": null, "e": 3650, "s": 3641, "text": "Solution" }, { "code": null, "e": 4192, "s": 3652, "text": "LinkedList<Node> que = new LinkedList<>(); que.add(root); while (que.isEmpty()==false){ int n=que.size(); for (int i=0;i<n;i++){ Node cur = que.poll(); if (i==n-1){ cur.nextRight=null; }else{ cur.nextRight=que.get(0); } if (cur.left!=null){ que.add(cur.left); } if (cur.right!=null){ que.add(cur.right); } } }" }, { "code": null, "e": 4194, "s": 4192, "text": "0" }, { "code": null, "e": 4209, "s": 4194, "text": "hr061 week ago" }, { "code": null, "e": 4997, "s": 4209, "text": "class Solution\n{\n public:\n //Function to connect nodes at same level.\n void connect(Node *root)\n {\n // Your Code Here\n if(!root)\n {\n return;\n }\n \n // we use queue for level order traversal\n queue<Node*> q;\n q.push(root);\n \n while(!q.empty())\n {\n int size = q.size();\n while(size--)\n {\n Node* frontNode = q.front();\n q.pop();\n if(!size) frontNode->nextRight = NULL;\n \n else frontNode->nextRight = q.front();\n \n if(frontNode->left) q.push(frontNode->left);\n \n if(frontNode->right) q.push(frontNode->right);\n \n }\n \n }\n } \n \n};\n" }, { "code": null, "e": 4999, "s": 4997, "text": "0" }, { "code": null, "e": 5023, "s": 4999, "text": "srujugowda4561 week ago" }, { "code": null, "e": 5064, "s": 5023, "text": "C++ solution using level order traversal" }, { "code": null, "e": 5783, "s": 5064, "text": "class Solution\n{\n public:\n //Function to connect nodes at same level.\n void connect(Node *root)\n {\n queue<Node*> q;\n q.push(root);\n \n while(!q.empty()){\n int size=q.size();\n for(int i=0;i<size;i++){\n Node* temp=q.front();\n q.pop();\n if(q.empty() || i==size-1){\n temp->nextRight=NULL;\n }else{\n temp->nextRight=q.front();\n }\n \n if(temp->left){\n q.push(temp->left);\n }\n if(temp->right){\n q.push(temp->right);\n }\n }\n }\n } \n \n};" }, { "code": null, "e": 5785, "s": 5783, "text": "0" }, { "code": null, "e": 5806, "s": 5785, "text": "anugrahlko1 week ago" }, { "code": null, "e": 6808, "s": 5806, "text": "class Solution{ //Function to connect nodes at same level. static HashMap<Integer, ArrayList<Node>> map; public void connect(Node root) { int level=0; map = new HashMap<Integer, ArrayList<Node>>(); leveOrderTraversal(root, level, map); int i=0; while(map.containsKey(i)){ ArrayList<Node> a = map.get(i); int j; for( j=0;j<a.size()-1;j++){ a.get(j).nextRight =a.get(j+1); } a.get(j).nextRight = null; i++; } } static void leveOrderTraversal(Node node,int l,HashMap<Integer, ArrayList<Node>> map){ if(node==null)return; if(map.containsKey(l)){ ArrayList<Node> arr= map.get(l); arr.add(node); map.put(l,arr); }else{ ArrayList<Node> arr= new ArrayList<Node>(); arr.add(node); map.put(l,arr); } leveOrderTraversal(node.left, l+1, map); leveOrderTraversal(node.right, l+1, map); }}" }, { "code": null, "e": 6811, "s": 6808, "text": "+1" }, { "code": null, "e": 6836, "s": 6811, "text": "suhitgupta1112 weeks ago" }, { "code": null, "e": 7365, "s": 6836, "text": "class Solution{ //Function to connect nodes at same level. public void connect(Node root) { // Your code goes here. if(root==null) return; Queue<Node> q = new LinkedList<>(); q.add(root); while(!q.isEmpty()){ int size=q.size(); for(int i=0;i<size;i++){ Node curr=q.poll(); if(curr.left!=null) q.add(curr.left); if(curr.right!=null) q.add(curr.right); if(i!=size-1) curr.nextRight=q.peek(); } } }}" }, { "code": null, "e": 7367, "s": 7365, "text": "0" }, { "code": null, "e": 7391, "s": 7367, "text": "amankumar2783 weeks ago" }, { "code": null, "e": 7418, "s": 7391, "text": "Java Solution: using QUEUE" }, { "code": null, "e": 8167, "s": 7418, "text": "class Solution{ //Function to connect nodes at same level. public void connect(Node root) { if(root==null){ return ; } Queue<Node> q=new LinkedList<>(); q.add(root); int curr=1; int next=0; while(curr!=0){ Node temp=q.poll(); if(temp.left!=null){ q.add(temp.left); next++; } if(temp.right!=null){ q.add(temp.right); next++; } if(curr>1){ temp.nextRight=q.peek(); }else{ temp.nextRight=null; } curr--; if(curr==0){ curr=next; next=0; } } }}" }, { "code": null, "e": 8169, "s": 8167, "text": "0" }, { "code": null, "e": 8191, "s": 8169, "text": "harshrauth3 weeks ago" }, { "code": null, "e": 8855, "s": 8191, "text": "class Solution{ public: //Function to connect nodes at same level. void connect(Node *root) { // Your Code Here queue<Node*>q; q.push(root); q.push(NULL); while(!q.empty()) { if(q.front()!=NULL) { Node * temp=q.front(); q.pop(); temp->nextRight=q.front(); if(temp->left!=NULL) q.push(temp->left); if(temp->right!=NULL) q.push(temp->right); } else { if(q.size()!=1) q.push(NULL); q.pop(); } } } };" }, { "code": null, "e": 9001, "s": 8855, "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": 9037, "s": 9001, "text": " Login to access your submissions. " }, { "code": null, "e": 9047, "s": 9037, "text": "\nProblem\n" }, { "code": null, "e": 9057, "s": 9047, "text": "\nContest\n" }, { "code": null, "e": 9120, "s": 9057, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9268, "s": 9120, "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": 9476, "s": 9268, "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": 9582, "s": 9476, "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 get yesterday’s date in JavaScript?
To get the yesterday date, first of all get the current date and subtract 1 from the current and use the function setDate(). The syntax is as follows − yourCurrentDateVariableName.setDate(yourCurrentDateVariableName.getDate() - 1); At first, get the current date − var currentDate = new Date(); Now, get yesterday’s date with the following code − var currentDate = new Date(); console.log("The current date="+currentDate); var yesterdayDate = currentDate.setDate(currentDate.getDate()- 1); console.log("The yesterday date ="+new Date(yesterdayDate)); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo137.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo137.js The current date=Fri Jul 31 2020 18:57:17 GMT+0530 (India Standard Time) The yesterday date =Thu Jul 30 2020 18:57:17 GMT+0530 (India Standard Time)
[ { "code": null, "e": 1214, "s": 1062, "text": "To get the yesterday date, first of all get the current date and subtract 1 from the current and\nuse the function setDate(). The syntax is as follows −" }, { "code": null, "e": 1294, "s": 1214, "text": "yourCurrentDateVariableName.setDate(yourCurrentDateVariableName.getDate() - 1);" }, { "code": null, "e": 1327, "s": 1294, "text": "At first, get the current date −" }, { "code": null, "e": 1357, "s": 1327, "text": "var currentDate = new Date();" }, { "code": null, "e": 1409, "s": 1357, "text": "Now, get yesterday’s date with the following code −" }, { "code": null, "e": 1613, "s": 1409, "text": "var currentDate = new Date();\nconsole.log(\"The current date=\"+currentDate);\nvar yesterdayDate = currentDate.setDate(currentDate.getDate()- 1);\nconsole.log(\"The yesterday date =\"+new Date(yesterdayDate));" }, { "code": null, "e": 1679, "s": 1613, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1697, "s": 1679, "text": "node fileName.js." }, { "code": null, "e": 1772, "s": 1697, "text": "Here, my file name is demo137.js. This will produce the following output −" }, { "code": null, "e": 1971, "s": 1772, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo137.js\nThe current date=Fri Jul 31 2020 18:57:17 GMT+0530 (India Standard Time)\nThe yesterday date =Thu Jul 30 2020 18:57:17 GMT+0530 (India Standard Time)" } ]
Some issues when building an AWS data lake using Spark and how to deal with these issues | by Tran Nguyen | Towards Data Science
At first, it seemed to be quite easy to write down and run a Spark application. If you are experienced with data frame manipulation using pandas, NumPy and other packages in Python, and/or the SQL language, creating an ETL pipeline for our data using Spark is quite similar, even much easier than I thought. And compared to other databases (such as Postgres, Cassandra, AWS DWH on Redshift), creating a Data Lake database using Spark appears to be a carefree project. But then, when you deployed Spark application on the cloud service AWS with your full dataset, the application started to slow down and fail. Your application ran forever, you even didn’t know if it was running or not when observing the AWS EMR console. You might not know where it was failed: It was difficult to debug. The Spark application behaved differently between the local mode and stand-alone mode, between the test set — a small portion of the dataset — and full dataset. The list of problems went on and on. You felt frustrated. Really, you realized that you knew nothing about Spark. Well, optimistically, then it was indeed a very good opportunity to learn more about Spark. Running into issues is the normal thing in programming anyway. But, how to solve problems quickly? Where to start? After struggling with creating a Data Lake database using Spark, I feel the urge to share what I have encountered and how I solved these issues. I hope it is helpful for some of you. And please, correct me if I am wrong. I am still a newbie in Spark anyway. Now, let’s dive in! Cautions 1. This article assumes that you already have some working knowledge of Spark, especially PySpark, command line environment, Jupyter notebook and AWS. For more about Spark, please read the reference here. 2. This is your responsibility for monitoring usage charges on the AWS account you use. Remember to terminate the cluster and other related resources each time you finish working. The EMR cluster is costly. 3. This is one of the assessing projects for the Data Engineering nanodegree on Udacity. So to respect the Udacity Honor Code, I would not include the full notebook with the workflow to explore and build the ETL pipeline for the project. Part of the Jupyter notebook version of this tutorial, together with other tutorials on Spark and many more data science tutorials could be found on my github. Some of the materials are from the Data Engineering nanodegree program on Udacity. Some ideas and issues were collected from the Knowledge — Udacity Q&A Platform and the Student Hub — Udacity chat platform. Thank you all for your dedication and great contribution to us. Sparkify is a startup company working on a music streaming app. Through the app, Sparkify has collected information about user activity and songs, which is stored as a directory of JSON logs (log-data - user activity) and a directory of JSON metadata files (song_data - song information). These data reside in a public S3 bucket on AWS. In order to improve the business growth, Sparkify wants to move their processes and data onto the data lake on the cloud. This project would be a workflow to explore and build an ETL (Extract — Transform — Load) pipeline that: Extracts data from S3 Processes data into analytics tables using Spark on an AWS cluster Loads the data back into S3 as a set of dimensional and fact tables for the Sparkify analytics team to continue finding insights in what songs their users are listening to. Below is the sample from JSON log file and JSON song file: The dimension and fact tables for this database were designed as followed: Fields in bold: partition keys. (ERD diagram was made using https://dbdiagram.io/) Project Workflow This is my workflow for the project. An experienced data engineer might skip many of these steps, but for me, I would rather go slowly and learn more: Build the ETL process step-by-step using Jupyter notebook on sample data in the local directory; write output to the local directory. Validate the ETL Process using the sub-dataset on AWS S3; write output to AWS S3. Put all the codes together to build the script etl.py and run on Spark local mode, testing both the local data and a subset of data on s3//udacity-den. The output result from the task could be tested using a Jupyter notebook test_data_lake.ipynb. Build and launch an EMR cluster. As what I know, you could submit the project on Udacity without using EMR, but I highly recommend you to run it on the Spark stand-alone mode on AWS to see how it works. You definitely will learn a lot more. Submit a Spark job for etl.py on EMR cluster, using a subset of data on s3//udacity-den. Finally, submit a Spark job for etl.py on EMR cluster, using a full dataset on s3//udacity-den. Try to optimize the Spark performance using various options. Provide example queries and results for song play analysis. This part was described in another Jupyter notebook called sparkifydb_data_lake_demo.ipynb. The validation and demo part could be found on my Github. Other script file etl.py and my detailed sparkifydb_data_lake_etl.ipynb are not available in respect of the Udacity Honor Code. Jupyter notebook is a great environment for exploratory data analysis (EDA), testing things out and promptly validating the results. Since debugging and optimizing the Spark application is quite challenging, it is highly recommended to build the ETL process step by step before putting all the codes together. You will see how the advantage is when we come to other tips. Another important reason for using Jupyter notebook: It is impractical to create etl.py script and then try to debug it since you would have to create a spark session each time you run etl.py file. With the notebook, the spark session is always available. In order to work on the project, first, we need to know the overview of the dataset, such as the number of files, the number of lines in each file, the total size of the dataset, the structure of the file, etc. It is especially crucial if we work on the cloud, where requests could cost so much time and money. To do that, we can use boto3, the Amazon Web Services (AWS) SDK for Python. boto3 allows us to access AWS via an IAM user. The detail on how to create an IAM user can be found here, Step 2: Create an IAM user. Below is the way to set up the client for S3 on Jupyter notebook: The key and access key obtained from an IAM user could be saved to the file credentials.cfg at the local directory as below. Note that you may run into “configure file parsing error” if you put your key and secrete key inside “ ” or ‘ ’, or if the file does not have the header such as [AWS] With this client for S3 created by boto3, we can access the dataset for the project and look at the file structures of log-data and song_data: The outputs of the exploration process are: The dataset is not big, ~3.6MB. However, the song_data has ~15,000 files. It is better to use a subset of song_data, such as ‘song_data/A/A/A/’ or ‘song_data/A/’ for exploring/creating/debugging the ETL pipeline first. My ETL pipeline worked very well on the subset of the data. However, when I run it on the whole dataset, the Spark application kept freezing without any error notice. I had to reduce/increase the sub dataset to actually see the error and fix the problem, for example changing from ‘song_data/A/A/A’ to ‘song_data/A/’ and vice versa. So what is the problem here? It turned out that on this specific data, on the small dataset, my Spark application could automatically figure out the schema. But it could not on a bigger dataset, perhaps due to inconsistency among the files and/or incompatible data types. Moreover, the loading would take less time with a defined schema. How to design a correct schema: You can manually create a schema by looking at the structure of the log_data JSON files and the song_data JSON files. For simple visualization, I generated the view using the pandas data frame as below For me, the trick is letting Spark read and figure out the schema on its own by reading the small subset of files into a data frame, and then use it to create the right schema. With that, we don’t need to guess any kind of datatypes, whether it is STRING or DOUBLE or LONG, etc. The demonstration for this trick is as followed: Although it is the best practice in programming, we sometimes forget to do that. For a big dataset, observing the time for each task is very important for debugging and optimizing the Spark application. Unless you turn off INFO logging in Spark, it is very difficult, if not impossible, to know the progress of the Spark application on the terminal, which is overwhelming with INFO logging. By printing out the task name and recording the time, everything is better: There are at least 2 ways to import and use a function, for example: from pyspark.sql.functions import max or import pyspark.sql.functions as F and then use F.max Either is fine. I prefer the second approach since I don’t need to list all the functions on the top of my script etl.py. Notice that themax function is an exception since it is also a built-in max function in Python. To use max function from the pyspark.sql.functions module, you have to use F.max or using an alias, such asfrom pyspark.sql.functions import max as max_ There could be many problems with it. I got some myself: The difference in the AWS region: Please make sure to use us-west-2 when setting up boto3/EMR cluster/S3 output bucket, etc. since the available dataset is on that AWS region.Didn’t include defined schema when reading files to a data frame: Fix using Tip 3.It takes such a long time to run the ETL pipeline on the whole dataset: The project is quite impractical because reading and writing to S3 from EMR/Spark are extremely slow. When running the ETL pipeline on a small sub dataset, you can see the same pattern of INFO logging repeats again and again on the terminal, such as the one below: The difference in the AWS region: Please make sure to use us-west-2 when setting up boto3/EMR cluster/S3 output bucket, etc. since the available dataset is on that AWS region. Didn’t include defined schema when reading files to a data frame: Fix using Tip 3. It takes such a long time to run the ETL pipeline on the whole dataset: The project is quite impractical because reading and writing to S3 from EMR/Spark are extremely slow. When running the ETL pipeline on a small sub dataset, you can see the same pattern of INFO logging repeats again and again on the terminal, such as the one below: This is on the “INFO ContextCleaner: Cleaned accumulator xxx” where I found my Spark application appeared to be freezing again and again. It’s expected to be a long-running job, which took me ~115 min to write only the songs table into the s3 bucket. So if you are sure that your end-to-end process works perfectly, then be patient for 2 hours to see how it works. The process could be speeded up, check out on Tip 9 below. 4. Checking the running time on AWS EMR console: You can see how long your Spark application ran when choosing the Application user interfaces tab on your cluster on the EMR console. The list of application can be found at the end of the page: My ETL pipeline on the whole dataset took ~2.1 hrs to finished on the EMR cluster (1 Master node and 2 Core nodes of type m5.xlarge). This issue is trivial in other databases: In Postgres, we can use SERIAL to auto-increment a column, such as songplays_id SERIAL PRIMARY KEY. In AWS Redshift, we can use IDENTITY(seed, step). It is not trivial to perform auto-increment for the table using Spark, at least when you try to understand it deeply and in consideration of Spark performance. Here is one of the good references to understand auto-increment in Spark. There are 3 methods for this task: Using row_number() function using SparkSQL Using rdds to create indexes and then convert it back to the data frame using the rdd.zipWithIndex() function Using the monotonically_increasing_id() I prefer the rdd.zipWithIndex() function: Step 1: From the songplays_table dataframe, use the rdd interface to create indexes with zipWithIndex(). The result is a list of rows, each row contains 2 elements: (i) all the columns from the old data frame zipped into a “row”, and (ii) the auto-increment indexes: Step 2: Return it back to dataframe — we need to write a lambda function for it. Below is the time for running the Spark application on AWS EMR cluster, reading from and writing to S3: My EMR cluster had 1 Master node and 2 Core nodes of type m5.xlarge, as shown below: aws emr create-cluster --name test-emr-cluster --use-default-roles --release-label emr-5.28.0 --instance-count 3 --instance-type m5.xlarge --applications Name=JupyterHub Name=Spark Name=Hadoop --ec2-attributes KeyName=emr-cluster --log-uri s3://s3-for-emr-cluster/ We definitely love to optimize the Spark application since reading and writing into S3 take a long time. Here are some optimizations that I have tried: Set spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version to 2 You can read in detail about it here. It can be done simply by adding spark.conf.set("mapreduce.fileoutputcommitter.algorithm.version", "2") into the spark session. With this optimization, the total ETL time reduced dramatically from ~2.1hr to only 30 min. Use HDFS to speed up the process - “On a per-node basis, HDFS can yield 6X higher read throughput than S3”. So we can save the analytics tables to HDFS, then copy from HDFS to S3. We could use s3-dist-cp to copy from HDFS to S3. This ETL pipeline is a long-running job, in which the task of writing the song table took most of the time. The songs table was partitioned by “year” and “artist”, which could produce skew data since some early years (1961 to 199x) don’t contain many songs comparing to the years 200x. The data quality checks to make sure if the ETL pipeline successfully added all the records to the tables, together with some example queries and results for song play analysis could be found in my notebook on Github. Although I have used AWS “quite a lot” and already reached the Free Tier usage limit with this account, whenever I came to the Billing Dashboard, the total amount due is 0. Don’t let AWS Billing Dashboard confuse you. What it shows is the total balance, not your AWS expense. It is the balance which — according to Wikipedia — is “the difference between the sum of debit entries and the sum of credit entries entered into an account during a financial period.” I thought when looking at the AWS Billing Dashboard, I would see the amount I had spent so far, my AWS expense. But no. Even when click on the Bill Details, everything is 0. And so I thought that I didn’t use AWS that much. My promo credit was still safe. Only when one day, I click on the Expand All button and I were in big surprise realizing my promo credit had almost gone!!! So again, what you see on the Dashboard is the balance, not the expense. Be careful when using your EMR and EC clusters. It may cost you more money than you thought. (Well, although I admit that gaining AWS experience is so worth it). Thank you so much for reading this lengthy post. I do aware that people get discouraged easily with long posts, but I want to have a consolidated report for you. Good luck with your project, and I am more than happy for any discussion. The Jupyter notebook version of this post, together with other tutorials on Spark and many more data science tutorials could be found on my Github.
[ { "code": null, "e": 514, "s": 46, "text": "At first, it seemed to be quite easy to write down and run a Spark application. If you are experienced with data frame manipulation using pandas, NumPy and other packages in Python, and/or the SQL language, creating an ETL pipeline for our data using Spark is quite similar, even much easier than I thought. And compared to other databases (such as Postgres, Cassandra, AWS DWH on Redshift), creating a Data Lake database using Spark appears to be a carefree project." }, { "code": null, "e": 1317, "s": 514, "text": "But then, when you deployed Spark application on the cloud service AWS with your full dataset, the application started to slow down and fail. Your application ran forever, you even didn’t know if it was running or not when observing the AWS EMR console. You might not know where it was failed: It was difficult to debug. The Spark application behaved differently between the local mode and stand-alone mode, between the test set — a small portion of the dataset — and full dataset. The list of problems went on and on. You felt frustrated. Really, you realized that you knew nothing about Spark. Well, optimistically, then it was indeed a very good opportunity to learn more about Spark. Running into issues is the normal thing in programming anyway. But, how to solve problems quickly? Where to start?" }, { "code": null, "e": 1595, "s": 1317, "text": "After struggling with creating a Data Lake database using Spark, I feel the urge to share what I have encountered and how I solved these issues. I hope it is helpful for some of you. And please, correct me if I am wrong. I am still a newbie in Spark anyway. Now, let’s dive in!" }, { "code": null, "e": 1604, "s": 1595, "text": "Cautions" }, { "code": null, "e": 1809, "s": 1604, "text": "1. This article assumes that you already have some working knowledge of Spark, especially PySpark, command line environment, Jupyter notebook and AWS. For more about Spark, please read the reference here." }, { "code": null, "e": 2016, "s": 1809, "text": "2. This is your responsibility for monitoring usage charges on the AWS account you use. Remember to terminate the cluster and other related resources each time you finish working. The EMR cluster is costly." }, { "code": null, "e": 2414, "s": 2016, "text": "3. This is one of the assessing projects for the Data Engineering nanodegree on Udacity. So to respect the Udacity Honor Code, I would not include the full notebook with the workflow to explore and build the ETL pipeline for the project. Part of the Jupyter notebook version of this tutorial, together with other tutorials on Spark and many more data science tutorials could be found on my github." }, { "code": null, "e": 2497, "s": 2414, "text": "Some of the materials are from the Data Engineering nanodegree program on Udacity." }, { "code": null, "e": 2685, "s": 2497, "text": "Some ideas and issues were collected from the Knowledge — Udacity Q&A Platform and the Student Hub — Udacity chat platform. Thank you all for your dedication and great contribution to us." }, { "code": null, "e": 3022, "s": 2685, "text": "Sparkify is a startup company working on a music streaming app. Through the app, Sparkify has collected information about user activity and songs, which is stored as a directory of JSON logs (log-data - user activity) and a directory of JSON metadata files (song_data - song information). These data reside in a public S3 bucket on AWS." }, { "code": null, "e": 3144, "s": 3022, "text": "In order to improve the business growth, Sparkify wants to move their processes and data onto the data lake on the cloud." }, { "code": null, "e": 3249, "s": 3144, "text": "This project would be a workflow to explore and build an ETL (Extract — Transform — Load) pipeline that:" }, { "code": null, "e": 3271, "s": 3249, "text": "Extracts data from S3" }, { "code": null, "e": 3338, "s": 3271, "text": "Processes data into analytics tables using Spark on an AWS cluster" }, { "code": null, "e": 3511, "s": 3338, "text": "Loads the data back into S3 as a set of dimensional and fact tables for the Sparkify analytics team to continue finding insights in what songs their users are listening to." }, { "code": null, "e": 3570, "s": 3511, "text": "Below is the sample from JSON log file and JSON song file:" }, { "code": null, "e": 3677, "s": 3570, "text": "The dimension and fact tables for this database were designed as followed: Fields in bold: partition keys." }, { "code": null, "e": 3728, "s": 3677, "text": "(ERD diagram was made using https://dbdiagram.io/)" }, { "code": null, "e": 3745, "s": 3728, "text": "Project Workflow" }, { "code": null, "e": 3896, "s": 3745, "text": "This is my workflow for the project. An experienced data engineer might skip many of these steps, but for me, I would rather go slowly and learn more:" }, { "code": null, "e": 4030, "s": 3896, "text": "Build the ETL process step-by-step using Jupyter notebook on sample data in the local directory; write output to the local directory." }, { "code": null, "e": 4112, "s": 4030, "text": "Validate the ETL Process using the sub-dataset on AWS S3; write output to AWS S3." }, { "code": null, "e": 4359, "s": 4112, "text": "Put all the codes together to build the script etl.py and run on Spark local mode, testing both the local data and a subset of data on s3//udacity-den. The output result from the task could be tested using a Jupyter notebook test_data_lake.ipynb." }, { "code": null, "e": 4600, "s": 4359, "text": "Build and launch an EMR cluster. As what I know, you could submit the project on Udacity without using EMR, but I highly recommend you to run it on the Spark stand-alone mode on AWS to see how it works. You definitely will learn a lot more." }, { "code": null, "e": 4689, "s": 4600, "text": "Submit a Spark job for etl.py on EMR cluster, using a subset of data on s3//udacity-den." }, { "code": null, "e": 4785, "s": 4689, "text": "Finally, submit a Spark job for etl.py on EMR cluster, using a full dataset on s3//udacity-den." }, { "code": null, "e": 4846, "s": 4785, "text": "Try to optimize the Spark performance using various options." }, { "code": null, "e": 4998, "s": 4846, "text": "Provide example queries and results for song play analysis. This part was described in another Jupyter notebook called sparkifydb_data_lake_demo.ipynb." }, { "code": null, "e": 5184, "s": 4998, "text": "The validation and demo part could be found on my Github. Other script file etl.py and my detailed sparkifydb_data_lake_etl.ipynb are not available in respect of the Udacity Honor Code." }, { "code": null, "e": 5556, "s": 5184, "text": "Jupyter notebook is a great environment for exploratory data analysis (EDA), testing things out and promptly validating the results. Since debugging and optimizing the Spark application is quite challenging, it is highly recommended to build the ETL process step by step before putting all the codes together. You will see how the advantage is when we come to other tips." }, { "code": null, "e": 5812, "s": 5556, "text": "Another important reason for using Jupyter notebook: It is impractical to create etl.py script and then try to debug it since you would have to create a spark session each time you run etl.py file. With the notebook, the spark session is always available." }, { "code": null, "e": 6123, "s": 5812, "text": "In order to work on the project, first, we need to know the overview of the dataset, such as the number of files, the number of lines in each file, the total size of the dataset, the structure of the file, etc. It is especially crucial if we work on the cloud, where requests could cost so much time and money." }, { "code": null, "e": 6333, "s": 6123, "text": "To do that, we can use boto3, the Amazon Web Services (AWS) SDK for Python. boto3 allows us to access AWS via an IAM user. The detail on how to create an IAM user can be found here, Step 2: Create an IAM user." }, { "code": null, "e": 6399, "s": 6333, "text": "Below is the way to set up the client for S3 on Jupyter notebook:" }, { "code": null, "e": 6691, "s": 6399, "text": "The key and access key obtained from an IAM user could be saved to the file credentials.cfg at the local directory as below. Note that you may run into “configure file parsing error” if you put your key and secrete key inside “ ” or ‘ ’, or if the file does not have the header such as [AWS]" }, { "code": null, "e": 6834, "s": 6691, "text": "With this client for S3 created by boto3, we can access the dataset for the project and look at the file structures of log-data and song_data:" }, { "code": null, "e": 6878, "s": 6834, "text": "The outputs of the exploration process are:" }, { "code": null, "e": 7097, "s": 6878, "text": "The dataset is not big, ~3.6MB. However, the song_data has ~15,000 files. It is better to use a subset of song_data, such as ‘song_data/A/A/A/’ or ‘song_data/A/’ for exploring/creating/debugging the ETL pipeline first." }, { "code": null, "e": 7459, "s": 7097, "text": "My ETL pipeline worked very well on the subset of the data. However, when I run it on the whole dataset, the Spark application kept freezing without any error notice. I had to reduce/increase the sub dataset to actually see the error and fix the problem, for example changing from ‘song_data/A/A/A’ to ‘song_data/A/’ and vice versa. So what is the problem here?" }, { "code": null, "e": 7702, "s": 7459, "text": "It turned out that on this specific data, on the small dataset, my Spark application could automatically figure out the schema. But it could not on a bigger dataset, perhaps due to inconsistency among the files and/or incompatible data types." }, { "code": null, "e": 7768, "s": 7702, "text": "Moreover, the loading would take less time with a defined schema." }, { "code": null, "e": 7800, "s": 7768, "text": "How to design a correct schema:" }, { "code": null, "e": 8002, "s": 7800, "text": "You can manually create a schema by looking at the structure of the log_data JSON files and the song_data JSON files. For simple visualization, I generated the view using the pandas data frame as below" }, { "code": null, "e": 8330, "s": 8002, "text": "For me, the trick is letting Spark read and figure out the schema on its own by reading the small subset of files into a data frame, and then use it to create the right schema. With that, we don’t need to guess any kind of datatypes, whether it is STRING or DOUBLE or LONG, etc. The demonstration for this trick is as followed:" }, { "code": null, "e": 8533, "s": 8330, "text": "Although it is the best practice in programming, we sometimes forget to do that. For a big dataset, observing the time for each task is very important for debugging and optimizing the Spark application." }, { "code": null, "e": 8797, "s": 8533, "text": "Unless you turn off INFO logging in Spark, it is very difficult, if not impossible, to know the progress of the Spark application on the terminal, which is overwhelming with INFO logging. By printing out the task name and recording the time, everything is better:" }, { "code": null, "e": 8866, "s": 8797, "text": "There are at least 2 ways to import and use a function, for example:" }, { "code": null, "e": 8904, "s": 8866, "text": "from pyspark.sql.functions import max" }, { "code": null, "e": 8960, "s": 8904, "text": "or import pyspark.sql.functions as F and then use F.max" }, { "code": null, "e": 9082, "s": 8960, "text": "Either is fine. I prefer the second approach since I don’t need to list all the functions on the top of my script etl.py." }, { "code": null, "e": 9331, "s": 9082, "text": "Notice that themax function is an exception since it is also a built-in max function in Python. To use max function from the pyspark.sql.functions module, you have to use F.max or using an alias, such asfrom pyspark.sql.functions import max as max_" }, { "code": null, "e": 9388, "s": 9331, "text": "There could be many problems with it. I got some myself:" }, { "code": null, "e": 9982, "s": 9388, "text": "The difference in the AWS region: Please make sure to use us-west-2 when setting up boto3/EMR cluster/S3 output bucket, etc. since the available dataset is on that AWS region.Didn’t include defined schema when reading files to a data frame: Fix using Tip 3.It takes such a long time to run the ETL pipeline on the whole dataset: The project is quite impractical because reading and writing to S3 from EMR/Spark are extremely slow. When running the ETL pipeline on a small sub dataset, you can see the same pattern of INFO logging repeats again and again on the terminal, such as the one below:" }, { "code": null, "e": 10158, "s": 9982, "text": "The difference in the AWS region: Please make sure to use us-west-2 when setting up boto3/EMR cluster/S3 output bucket, etc. since the available dataset is on that AWS region." }, { "code": null, "e": 10241, "s": 10158, "text": "Didn’t include defined schema when reading files to a data frame: Fix using Tip 3." }, { "code": null, "e": 10578, "s": 10241, "text": "It takes such a long time to run the ETL pipeline on the whole dataset: The project is quite impractical because reading and writing to S3 from EMR/Spark are extremely slow. When running the ETL pipeline on a small sub dataset, you can see the same pattern of INFO logging repeats again and again on the terminal, such as the one below:" }, { "code": null, "e": 11002, "s": 10578, "text": "This is on the “INFO ContextCleaner: Cleaned accumulator xxx” where I found my Spark application appeared to be freezing again and again. It’s expected to be a long-running job, which took me ~115 min to write only the songs table into the s3 bucket. So if you are sure that your end-to-end process works perfectly, then be patient for 2 hours to see how it works. The process could be speeded up, check out on Tip 9 below." }, { "code": null, "e": 11246, "s": 11002, "text": "4. Checking the running time on AWS EMR console: You can see how long your Spark application ran when choosing the Application user interfaces tab on your cluster on the EMR console. The list of application can be found at the end of the page:" }, { "code": null, "e": 11380, "s": 11246, "text": "My ETL pipeline on the whole dataset took ~2.1 hrs to finished on the EMR cluster (1 Master node and 2 Core nodes of type m5.xlarge)." }, { "code": null, "e": 11572, "s": 11380, "text": "This issue is trivial in other databases: In Postgres, we can use SERIAL to auto-increment a column, such as songplays_id SERIAL PRIMARY KEY. In AWS Redshift, we can use IDENTITY(seed, step)." }, { "code": null, "e": 11806, "s": 11572, "text": "It is not trivial to perform auto-increment for the table using Spark, at least when you try to understand it deeply and in consideration of Spark performance. Here is one of the good references to understand auto-increment in Spark." }, { "code": null, "e": 11841, "s": 11806, "text": "There are 3 methods for this task:" }, { "code": null, "e": 11884, "s": 11841, "text": "Using row_number() function using SparkSQL" }, { "code": null, "e": 11994, "s": 11884, "text": "Using rdds to create indexes and then convert it back to the data frame using the rdd.zipWithIndex() function" }, { "code": null, "e": 12034, "s": 11994, "text": "Using the monotonically_increasing_id()" }, { "code": null, "e": 12076, "s": 12034, "text": "I prefer the rdd.zipWithIndex() function:" }, { "code": null, "e": 12343, "s": 12076, "text": "Step 1: From the songplays_table dataframe, use the rdd interface to create indexes with zipWithIndex(). The result is a list of rows, each row contains 2 elements: (i) all the columns from the old data frame zipped into a “row”, and (ii) the auto-increment indexes:" }, { "code": null, "e": 12424, "s": 12343, "text": "Step 2: Return it back to dataframe — we need to write a lambda function for it." }, { "code": null, "e": 12528, "s": 12424, "text": "Below is the time for running the Spark application on AWS EMR cluster, reading from and writing to S3:" }, { "code": null, "e": 12613, "s": 12528, "text": "My EMR cluster had 1 Master node and 2 Core nodes of type m5.xlarge, as shown below:" }, { "code": null, "e": 12879, "s": 12613, "text": "aws emr create-cluster --name test-emr-cluster --use-default-roles --release-label emr-5.28.0 --instance-count 3 --instance-type m5.xlarge --applications Name=JupyterHub Name=Spark Name=Hadoop --ec2-attributes KeyName=emr-cluster --log-uri s3://s3-for-emr-cluster/" }, { "code": null, "e": 13031, "s": 12879, "text": "We definitely love to optimize the Spark application since reading and writing into S3 take a long time. Here are some optimizations that I have tried:" }, { "code": null, "e": 13101, "s": 13031, "text": "Set spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version to 2" }, { "code": null, "e": 13266, "s": 13101, "text": "You can read in detail about it here. It can be done simply by adding spark.conf.set(\"mapreduce.fileoutputcommitter.algorithm.version\", \"2\") into the spark session." }, { "code": null, "e": 13358, "s": 13266, "text": "With this optimization, the total ETL time reduced dramatically from ~2.1hr to only 30 min." }, { "code": null, "e": 13391, "s": 13358, "text": "Use HDFS to speed up the process" }, { "code": null, "e": 13587, "s": 13391, "text": "- “On a per-node basis, HDFS can yield 6X higher read throughput than S3”. So we can save the analytics tables to HDFS, then copy from HDFS to S3. We could use s3-dist-cp to copy from HDFS to S3." }, { "code": null, "e": 13873, "s": 13587, "text": "This ETL pipeline is a long-running job, in which the task of writing the song table took most of the time. The songs table was partitioned by “year” and “artist”, which could produce skew data since some early years (1961 to 199x) don’t contain many songs comparing to the years 200x." }, { "code": null, "e": 14091, "s": 13873, "text": "The data quality checks to make sure if the ETL pipeline successfully added all the records to the tables, together with some example queries and results for song play analysis could be found in my notebook on Github." }, { "code": null, "e": 14264, "s": 14091, "text": "Although I have used AWS “quite a lot” and already reached the Free Tier usage limit with this account, whenever I came to the Billing Dashboard, the total amount due is 0." }, { "code": null, "e": 14552, "s": 14264, "text": "Don’t let AWS Billing Dashboard confuse you. What it shows is the total balance, not your AWS expense. It is the balance which — according to Wikipedia — is “the difference between the sum of debit entries and the sum of credit entries entered into an account during a financial period.”" }, { "code": null, "e": 14808, "s": 14552, "text": "I thought when looking at the AWS Billing Dashboard, I would see the amount I had spent so far, my AWS expense. But no. Even when click on the Bill Details, everything is 0. And so I thought that I didn’t use AWS that much. My promo credit was still safe." }, { "code": null, "e": 15167, "s": 14808, "text": "Only when one day, I click on the Expand All button and I were in big surprise realizing my promo credit had almost gone!!! So again, what you see on the Dashboard is the balance, not the expense. Be careful when using your EMR and EC clusters. It may cost you more money than you thought. (Well, although I admit that gaining AWS experience is so worth it)." }, { "code": null, "e": 15403, "s": 15167, "text": "Thank you so much for reading this lengthy post. I do aware that people get discouraged easily with long posts, but I want to have a consolidated report for you. Good luck with your project, and I am more than happy for any discussion." } ]
Null Pointer Exception in C#
NullReferenceException is a C# version of NullPointerException. To handle and catch it in C#, use try-catch. The below example shows that a variable is set to null and when we try to print it, it throws an exception that gets caught in the catch − Try { a = null; Console.WriteLine(a); }catch (NullPointerException ex) { Console.WriteLine("Variable is Null!"); } The above will allow the exception to be caught and use catch for it.
[ { "code": null, "e": 1171, "s": 1062, "text": "NullReferenceException is a C# version of NullPointerException. To handle and catch it in C#, use try-catch." }, { "code": null, "e": 1310, "s": 1171, "text": "The below example shows that a variable is set to null and when we try to print it, it throws an exception that gets caught in the catch −" }, { "code": null, "e": 1434, "s": 1310, "text": "Try {\n a = null;\n Console.WriteLine(a);\n}catch (NullPointerException ex) {\n Console.WriteLine(\"Variable is Null!\");\n}" }, { "code": null, "e": 1504, "s": 1434, "text": "The above will allow the exception to be caught and use catch for it." } ]
Using Google Trends at Scale. How to use Google Trends when your... | by Carrie Fowle | Towards Data Science
Google Trends is a powerful measure of public interest in a topic, in other words, its hype; however, the way it is set up can make it difficult to use outside the simplest of applications. In this article, we dive into exactly what Google Trends is measuring and explore how to use it when your question exceeds the five-topic limit of the public facing tool. Google Trends gives you a normalized measure of search volume for a given search term over a selected period of time. From their FAQs: Each data point is divided by the total searches of the geography and time range it represents to compare relative popularity. Otherwise, places with the most search volume would always be ranked highest. The resulting numbers are then scaled on a range of 0 to 100 based on a topic’s proportion to all searches on all topics. — Google Trends FAQs That is to say, for each word in your search Google finds how much search volume in each region and time period your term had relative to all the searches in that region and time period. It combines all of these measures into a single measure of popularity, and then it scales the values across your topics, so the largest measure is set to 100. In short: Google Trends doesn’t exactly tell you how many searches occurred for your topic, but it does give you a nice proxy. As handy as Google Trends is for quickly taking the pulse of the internet, the structure of the service itself makes larger scale application difficult for two reasons: Currently, the public-facing Google Trends site will not allow a query with more than five terms. This is obviously limiting if you want to explore any real world question. For example, early in the democratic primary you wouldn’t have been able to easily compare the popularity of all the major candidates. The obvious reaction to this limit is, “well, I’ll just use multiple queries”. But as we mentioned earlier, all searches are scaled to the highest volume topic in your query, so two different queries aren’t comparable if they don’t have the same largest topic. The last statement is the key: if they don’t have the same largest topic So long as two queries share the same most popular topic, they will be scaled in the same way, so the trends will be comparable. It follows then that if you want to compare more than five topics in Google Trends, you just need to include a control topic in each search. For example, in a recent project, my team and I wanted to compare the popularity of Netflix’s and Amazon’s content. We went through the list of both platforms’ best content and pulled each title’s Google Trends measure relative to that of the word “France”. Exactly how did we decide to use the word “France”? It’s a bit like a recipe: you want something stable and safely higher than all of the terms you are interested in. Using domain knowledge, I knew which titles would see particularly high search volume, so I looked for a word that was safely more popular than our most popular titles, but not so popular that I’d lose any real information on the less popular titles. For example, “Bitcoin” has such high search volume that many titles were normalized to zero (see what I mean here). Yes. For the streaming content project, I used the Python library pytrends, an unofficial API for Google Trends. Below you can find a quick snippet to get you started: import pytrendskw_list = ##list of topics I wanted to searchtrends = dict()for i in kw_list: ##build out query pytrends.build_payload([i,'France'], cat=0,timeframe='today 5-y') ##save trend to dictionary trends[i] = pytrends.interest_over_time()[i] You should note that if you are trying to do this for more than a handful of queries, you will hit Google’s DoS (Denial of Service) limits relatively quickly, so you will want to pause your loop for a few seconds between each query. Google Trends is a good proxy for public interestTo make multiple queries comparable, include a control term that will be the largest in every searchUse pytrends to automate the process Google Trends is a good proxy for public interest To make multiple queries comparable, include a control term that will be the largest in every search Use pytrends to automate the process With this method, you can now answer big questions like: how popular are my products compared to those of my competitors, did a recent ad campaign impact interest in different product categories differently... In short: the five word limit is no longer yours.
[ { "code": null, "e": 533, "s": 172, "text": "Google Trends is a powerful measure of public interest in a topic, in other words, its hype; however, the way it is set up can make it difficult to use outside the simplest of applications. In this article, we dive into exactly what Google Trends is measuring and explore how to use it when your question exceeds the five-topic limit of the public facing tool." }, { "code": null, "e": 668, "s": 533, "text": "Google Trends gives you a normalized measure of search volume for a given search term over a selected period of time. From their FAQs:" }, { "code": null, "e": 873, "s": 668, "text": "Each data point is divided by the total searches of the geography and time range it represents to compare relative popularity. Otherwise, places with the most search volume would always be ranked highest." }, { "code": null, "e": 1016, "s": 873, "text": "The resulting numbers are then scaled on a range of 0 to 100 based on a topic’s proportion to all searches on all topics. — Google Trends FAQs" }, { "code": null, "e": 1362, "s": 1016, "text": "That is to say, for each word in your search Google finds how much search volume in each region and time period your term had relative to all the searches in that region and time period. It combines all of these measures into a single measure of popularity, and then it scales the values across your topics, so the largest measure is set to 100." }, { "code": null, "e": 1489, "s": 1362, "text": "In short: Google Trends doesn’t exactly tell you how many searches occurred for your topic, but it does give you a nice proxy." }, { "code": null, "e": 1658, "s": 1489, "text": "As handy as Google Trends is for quickly taking the pulse of the internet, the structure of the service itself makes larger scale application difficult for two reasons:" }, { "code": null, "e": 1966, "s": 1658, "text": "Currently, the public-facing Google Trends site will not allow a query with more than five terms. This is obviously limiting if you want to explore any real world question. For example, early in the democratic primary you wouldn’t have been able to easily compare the popularity of all the major candidates." }, { "code": null, "e": 2227, "s": 1966, "text": "The obvious reaction to this limit is, “well, I’ll just use multiple queries”. But as we mentioned earlier, all searches are scaled to the highest volume topic in your query, so two different queries aren’t comparable if they don’t have the same largest topic." }, { "code": null, "e": 2258, "s": 2227, "text": "The last statement is the key:" }, { "code": null, "e": 2300, "s": 2258, "text": "if they don’t have the same largest topic" }, { "code": null, "e": 2570, "s": 2300, "text": "So long as two queries share the same most popular topic, they will be scaled in the same way, so the trends will be comparable. It follows then that if you want to compare more than five topics in Google Trends, you just need to include a control topic in each search." }, { "code": null, "e": 2828, "s": 2570, "text": "For example, in a recent project, my team and I wanted to compare the popularity of Netflix’s and Amazon’s content. We went through the list of both platforms’ best content and pulled each title’s Google Trends measure relative to that of the word “France”." }, { "code": null, "e": 2880, "s": 2828, "text": "Exactly how did we decide to use the word “France”?" }, { "code": null, "e": 2995, "s": 2880, "text": "It’s a bit like a recipe: you want something stable and safely higher than all of the terms you are interested in." }, { "code": null, "e": 3362, "s": 2995, "text": "Using domain knowledge, I knew which titles would see particularly high search volume, so I looked for a word that was safely more popular than our most popular titles, but not so popular that I’d lose any real information on the less popular titles. For example, “Bitcoin” has such high search volume that many titles were normalized to zero (see what I mean here)." }, { "code": null, "e": 3367, "s": 3362, "text": "Yes." }, { "code": null, "e": 3530, "s": 3367, "text": "For the streaming content project, I used the Python library pytrends, an unofficial API for Google Trends. Below you can find a quick snippet to get you started:" }, { "code": null, "e": 3790, "s": 3530, "text": "import pytrendskw_list = ##list of topics I wanted to searchtrends = dict()for i in kw_list: ##build out query pytrends.build_payload([i,'France'], cat=0,timeframe='today 5-y') ##save trend to dictionary trends[i] = pytrends.interest_over_time()[i]" }, { "code": null, "e": 4023, "s": 3790, "text": "You should note that if you are trying to do this for more than a handful of queries, you will hit Google’s DoS (Denial of Service) limits relatively quickly, so you will want to pause your loop for a few seconds between each query." }, { "code": null, "e": 4209, "s": 4023, "text": "Google Trends is a good proxy for public interestTo make multiple queries comparable, include a control term that will be the largest in every searchUse pytrends to automate the process" }, { "code": null, "e": 4259, "s": 4209, "text": "Google Trends is a good proxy for public interest" }, { "code": null, "e": 4360, "s": 4259, "text": "To make multiple queries comparable, include a control term that will be the largest in every search" }, { "code": null, "e": 4397, "s": 4360, "text": "Use pytrends to automate the process" }, { "code": null, "e": 4607, "s": 4397, "text": "With this method, you can now answer big questions like: how popular are my products compared to those of my competitors, did a recent ad campaign impact interest in different product categories differently..." } ]
ls - Unix, Linux Command
ls - list directory contents. ls [OPTION]... [FILE]... ls [OPTION]... [FILE]... ls List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are mandatory for short options too. Example-1: To list all files of current directory: $ ls output: # lsbin dev home lib lost+found mnt proc run srv tmp varboot etc initrd.img lib64 media opt root sbin sys usr vmlinuz Example-2: output: # ls -1binbootdevetchomeinitrd.imgliblib64lost+foundmediamntoptprocrootrunsbinsrvsystmpusrvarvmlinuz Example-3: To display all information about files/directories: $ ls -l output: # ls -ltotal 81drwxr-xr-x 2 root root 4096 Dec 28 05:25 bindrwxr-xr-x 4 root root 1024 Dec 28 05:27 bootdrwxr-xr-x 17 root root 4320 Jan 7 17:57 devdrwxr-xr-x 97 root root 4096 Jan 7 18:18 etcdrwxr-xr-x 4 root root 4096 Jan 6 12:43 homelrwxrwxrwx 1 root root 33 Dec 28 05:08 initrd.img -> boot/initrd.img-3.19.0-25-genericdrwxr-xr-x 23 root root 4096 Dec 28 05:25 libdrwxr-xr-x 2 root root 4096 Dec 28 05:07 lib64drwx------ 2 root root 16384 Dec 28 05:07 lost+founddrwxr-xr-x 3 root root 4096 Dec 28 05:07 mediadrwxr-xr-x 2 root root 4096 Apr 11 2014 mntdrwxr-xr-x 2 root root 4096 Aug 5 2015 optdr-xr-xr-x 167 root root 0 Jan 7 17:57 procdrwx------ 2 root root 4096 Jan 7 18:12 rootdrwxr-xr-x 19 root root 680 Jan 7 20:41 rundrwxr-xr-x 2 root root 12288 Dec 28 05:28 sbindrwxr-xr-x 2 root root 4096 Aug 5 2015 srvdr-xr-xr-x 13 root root 0 Jan 7 17:57 sysdrwxrwxrwt 2 root root 4096 Jan 7 20:17 tmpdrwxr-xr-x 10 root root 4096 Dec 28 05:07 usrdrwxr-xr-x 12 root root 4096 Dec 28 05:25 varlrwxrwxrwx 1 root root 30 Dec 28 05:08 vmlinuz -> boot/vmlinuz-3.19.0-25-generic Example-4: output: # ls -ld /etcdrwxr-xr-x 97 root root 4096 Jan 7 18:18 /etc Example-5: To order files based on last modified time: $ ls -lt output: # ls -lttotal 81dr-xr-xr-x 13 root root 0 Jan 7 20:44 sysdrwxr-xr-x 19 root root 680 Jan 7 20:41 rundrwxrwxrwt 2 root root 4096 Jan 7 20:17 tmpdrwxr-xr-x 97 root root 4096 Jan 7 18:18 etcdrwx------ 2 root root 4096 Jan 7 18:12 rootdrwxr-xr-x 17 root root 4320 Jan 7 17:57 devdr-xr-xr-x 166 root root 0 Jan 7 17:57 procdrwxr-xr-x 4 root root 4096 Jan 6 12:43 homedrwxr-xr-x 2 root root 12288 Dec 28 05:28 sbindrwxr-xr-x 4 root root 1024 Dec 28 05:27 bootdrwxr-xr-x 12 root root 4096 Dec 28 05:25 vardrwxr-xr-x 2 root root 4096 Dec 28 05:25 bindrwxr-xr-x 23 root root 4096 Dec 28 05:25 liblrwxrwxrwx 1 root root 30 Dec 28 05:08 vmlinuz -> boot/vmlinuz-3.19.0-25-genericlrwxrwxrwx 1 root root 33 Dec 28 05:08 initrd.img -> boot/initrd.img-3.19.0-25-genericdrwxr-xr-x 3 root root 4096 Dec 28 05:07 mediadrwxr-xr-x 10 root root 4096 Dec 28 05:07 usrdrwxr-xr-x 2 root root 4096 Dec 28 05:07 lib64drwx------ 2 root root 16384 Dec 28 05:07 lost+founddrwxr-xr-x 2 root root 4096 Aug 5 2015 optdrwxr-xr-x 2 root root 4096 Aug 5 2015 srvdrwxr-xr-x 2 root root 4096 Apr 11 2014 mnt Example-6: To order files based on last modified time(In Reverse Order): $ ls -ltr output: # ls -ltrtotal 81drwxr-xr-x 2 root root 4096 Apr 11 2014 mntdrwxr-xr-x 2 root root 4096 Aug 5 2015 srvdrwxr-xr-x 2 root root 4096 Aug 5 2015 optdrwx------ 2 root root 16384 Dec 28 05:07 lost+founddrwxr-xr-x 2 root root 4096 Dec 28 05:07 lib64drwxr-xr-x 10 root root 4096 Dec 28 05:07 usrdrwxr-xr-x 3 root root 4096 Dec 28 05:07 medialrwxrwxrwx 1 root root 33 Dec 28 05:08 initrd.img -> boot/initrd.img-3.19.0-25-genericlrwxrwxrwx 1 root root 30 Dec 28 05:08 vmlinuz -> boot/vmlinuz-3.19.0-25-genericdrwxr-xr-x 23 root root 4096 Dec 28 05:25 libdrwxr-xr-x 2 root root 4096 Dec 28 05:25 bindrwxr-xr-x 12 root root 4096 Dec 28 05:25 vardrwxr-xr-x 4 root root 1024 Dec 28 05:27 bootdrwxr-xr-x 2 root root 12288 Dec 28 05:28 sbindrwxr-xr-x 4 root root 4096 Jan 6 12:43 homedr-xr-xr-x 166 root root 0 Jan 7 17:57 procdrwxr-xr-x 17 root root 4320 Jan 7 17:57 devdrwx------ 2 root root 4096 Jan 7 18:12 rootdrwxr-xr-x 97 root root 4096 Jan 7 18:18 etcdrwxrwxrwt 2 root root 4096 Jan 7 20:17 tmpdrwxr-xr-x 19 root root 680 Jan 7 20:41 rundr-xr-xr-x 13 root root 0 Jan 7 20:44 sys Example-7: To display hidden files: $ ls -a It will show all the files including the ‘.’ (current directory) and ‘..’ (parent directory). To show the hidden files, but not the ‘.’ (current directory) and ‘..’ (parent directory), use option -A. $ ls -A output: # ls -a. .. .bash_history .bash_logout .bashrc .cache .profile test1.sh test.sh .viminfo # ls -A.bash_history .bash_logout .bashrc .cache .profile test1.sh test.sh .viminfo Example-8: To display files recursively: $ ls -R /etc/network output: # ls -R /etc/network//etc/network/:if-down.d if-post-down.d if-pre-up.d if-up.d interfaces interfaces.d run/etc/network/if-down.d:resolvconf upstart wpasupplicant/etc/network/if-post-down.d:bridge wireless-tools wpasupplicant/etc/network/if-pre-up.d:bridge ethtool wireless-tools wpasupplicant/etc/network/if-up.d:000resolvconf ethtool ntpdate openssh-server upstart wpasupplicant/etc/network/interfaces.d: Example-9: To display file inode number: $ ls -i /etc/wgetrc output: # ls -i /etc/wgetrc526576 /etc/wgetrc Example-10: output: $ ls -n .bash_logout-rw-r--r-- 1 1000 1000 220 Dec 28 05:28 .bash_logout Example-11: Visual Classification of Files With Special Characters: $ ls -F Instead of doing the ‘ls -l’ and then the checking for the first character to determine the type of file. You can use -F which classifies the file with different special character for different kind of files. output: # ls -F /bin/ boot/ dev/ etc/ home/ initrd.img@ lib/ lib64/ lost+found/ media/ mnt/ opt/ proc/ root/ run/ sbin/ srv/ sys/ tmp/ usr/ var/ vmlinuz@ 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10607, "s": 10577, "text": "ls - list directory contents." }, { "code": null, "e": 10634, "s": 10607, "text": "ls [OPTION]... [FILE]... \n" }, { "code": null, "e": 10660, "s": 10634, "text": "ls [OPTION]... [FILE]... " }, { "code": null, "e": 10879, "s": 10660, "text": "ls List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\nMandatory arguments to long options are mandatory for short options too." }, { "code": null, "e": 10890, "s": 10879, "text": "Example-1:" }, { "code": null, "e": 10930, "s": 10890, "text": "To list all files of current directory:" }, { "code": null, "e": 10935, "s": 10930, "text": "$ ls" }, { "code": null, "e": 10943, "s": 10935, "text": "output:" }, { "code": null, "e": 11096, "s": 10943, "text": "# lsbin dev home lib lost+found mnt proc run srv tmp varboot etc initrd.img lib64 media opt root sbin sys usr vmlinuz" }, { "code": null, "e": 11107, "s": 11096, "text": "Example-2:" }, { "code": null, "e": 11115, "s": 11107, "text": "output:" }, { "code": null, "e": 11216, "s": 11115, "text": "# ls -1binbootdevetchomeinitrd.imgliblib64lost+foundmediamntoptprocrootrunsbinsrvsystmpusrvarvmlinuz" }, { "code": null, "e": 11227, "s": 11216, "text": "Example-3:" }, { "code": null, "e": 11279, "s": 11227, "text": "To display all information about files/directories:" }, { "code": null, "e": 11287, "s": 11279, "text": "$ ls -l" }, { "code": null, "e": 11295, "s": 11287, "text": "output:" }, { "code": null, "e": 12443, "s": 11295, "text": "# ls -ltotal 81drwxr-xr-x 2 root root 4096 Dec 28 05:25 bindrwxr-xr-x 4 root root 1024 Dec 28 05:27 bootdrwxr-xr-x 17 root root 4320 Jan 7 17:57 devdrwxr-xr-x 97 root root 4096 Jan 7 18:18 etcdrwxr-xr-x 4 root root 4096 Jan 6 12:43 homelrwxrwxrwx 1 root root 33 Dec 28 05:08 initrd.img -> boot/initrd.img-3.19.0-25-genericdrwxr-xr-x 23 root root 4096 Dec 28 05:25 libdrwxr-xr-x 2 root root 4096 Dec 28 05:07 lib64drwx------ 2 root root 16384 Dec 28 05:07 lost+founddrwxr-xr-x 3 root root 4096 Dec 28 05:07 mediadrwxr-xr-x 2 root root 4096 Apr 11 2014 mntdrwxr-xr-x 2 root root 4096 Aug 5 2015 optdr-xr-xr-x 167 root root 0 Jan 7 17:57 procdrwx------ 2 root root 4096 Jan 7 18:12 rootdrwxr-xr-x 19 root root 680 Jan 7 20:41 rundrwxr-xr-x 2 root root 12288 Dec 28 05:28 sbindrwxr-xr-x 2 root root 4096 Aug 5 2015 srvdr-xr-xr-x 13 root root 0 Jan 7 17:57 sysdrwxrwxrwt 2 root root 4096 Jan 7 20:17 tmpdrwxr-xr-x 10 root root 4096 Dec 28 05:07 usrdrwxr-xr-x 12 root root 4096 Dec 28 05:25 varlrwxrwxrwx 1 root root 30 Dec 28 05:08 vmlinuz -> boot/vmlinuz-3.19.0-25-generic" }, { "code": null, "e": 12454, "s": 12443, "text": "Example-4:" }, { "code": null, "e": 12462, "s": 12454, "text": "output:" }, { "code": null, "e": 12522, "s": 12462, "text": "# ls -ld /etcdrwxr-xr-x 97 root root 4096 Jan 7 18:18 /etc" }, { "code": null, "e": 12533, "s": 12522, "text": "Example-5:" }, { "code": null, "e": 12577, "s": 12533, "text": "To order files based on last modified time:" }, { "code": null, "e": 12586, "s": 12577, "text": "$ ls -lt" }, { "code": null, "e": 12595, "s": 12586, "text": "output: " }, { "code": null, "e": 13744, "s": 12595, "text": "# ls -lttotal 81dr-xr-xr-x 13 root root 0 Jan 7 20:44 sysdrwxr-xr-x 19 root root 680 Jan 7 20:41 rundrwxrwxrwt 2 root root 4096 Jan 7 20:17 tmpdrwxr-xr-x 97 root root 4096 Jan 7 18:18 etcdrwx------ 2 root root 4096 Jan 7 18:12 rootdrwxr-xr-x 17 root root 4320 Jan 7 17:57 devdr-xr-xr-x 166 root root 0 Jan 7 17:57 procdrwxr-xr-x 4 root root 4096 Jan 6 12:43 homedrwxr-xr-x 2 root root 12288 Dec 28 05:28 sbindrwxr-xr-x 4 root root 1024 Dec 28 05:27 bootdrwxr-xr-x 12 root root 4096 Dec 28 05:25 vardrwxr-xr-x 2 root root 4096 Dec 28 05:25 bindrwxr-xr-x 23 root root 4096 Dec 28 05:25 liblrwxrwxrwx 1 root root 30 Dec 28 05:08 vmlinuz -> boot/vmlinuz-3.19.0-25-genericlrwxrwxrwx 1 root root 33 Dec 28 05:08 initrd.img -> boot/initrd.img-3.19.0-25-genericdrwxr-xr-x 3 root root 4096 Dec 28 05:07 mediadrwxr-xr-x 10 root root 4096 Dec 28 05:07 usrdrwxr-xr-x 2 root root 4096 Dec 28 05:07 lib64drwx------ 2 root root 16384 Dec 28 05:07 lost+founddrwxr-xr-x 2 root root 4096 Aug 5 2015 optdrwxr-xr-x 2 root root 4096 Aug 5 2015 srvdrwxr-xr-x 2 root root 4096 Apr 11 2014 mnt" }, { "code": null, "e": 13755, "s": 13744, "text": "Example-6:" }, { "code": null, "e": 13817, "s": 13755, "text": "To order files based on last modified time(In Reverse Order):" }, { "code": null, "e": 13827, "s": 13817, "text": "$ ls -ltr" }, { "code": null, "e": 13835, "s": 13827, "text": "output:" }, { "code": null, "e": 14985, "s": 13835, "text": "# ls -ltrtotal 81drwxr-xr-x 2 root root 4096 Apr 11 2014 mntdrwxr-xr-x 2 root root 4096 Aug 5 2015 srvdrwxr-xr-x 2 root root 4096 Aug 5 2015 optdrwx------ 2 root root 16384 Dec 28 05:07 lost+founddrwxr-xr-x 2 root root 4096 Dec 28 05:07 lib64drwxr-xr-x 10 root root 4096 Dec 28 05:07 usrdrwxr-xr-x 3 root root 4096 Dec 28 05:07 medialrwxrwxrwx 1 root root 33 Dec 28 05:08 initrd.img -> boot/initrd.img-3.19.0-25-genericlrwxrwxrwx 1 root root 30 Dec 28 05:08 vmlinuz -> boot/vmlinuz-3.19.0-25-genericdrwxr-xr-x 23 root root 4096 Dec 28 05:25 libdrwxr-xr-x 2 root root 4096 Dec 28 05:25 bindrwxr-xr-x 12 root root 4096 Dec 28 05:25 vardrwxr-xr-x 4 root root 1024 Dec 28 05:27 bootdrwxr-xr-x 2 root root 12288 Dec 28 05:28 sbindrwxr-xr-x 4 root root 4096 Jan 6 12:43 homedr-xr-xr-x 166 root root 0 Jan 7 17:57 procdrwxr-xr-x 17 root root 4320 Jan 7 17:57 devdrwx------ 2 root root 4096 Jan 7 18:12 rootdrwxr-xr-x 97 root root 4096 Jan 7 18:18 etcdrwxrwxrwt 2 root root 4096 Jan 7 20:17 tmpdrwxr-xr-x 19 root root 680 Jan 7 20:41 rundr-xr-xr-x 13 root root 0 Jan 7 20:44 sys" }, { "code": null, "e": 14996, "s": 14985, "text": "Example-7:" }, { "code": null, "e": 15021, "s": 14996, "text": "To display hidden files:" }, { "code": null, "e": 15029, "s": 15021, "text": "$ ls -a" }, { "code": null, "e": 15103, "s": 15029, "text": "It will show all the files including the ‘.’ (current directory) and ‘..’" }, { "code": null, "e": 15229, "s": 15103, "text": "(parent directory). To show the hidden files, but not the ‘.’ (current directory) and ‘..’ (parent directory), use option -A." }, { "code": null, "e": 15237, "s": 15229, "text": "$ ls -A" }, { "code": null, "e": 15245, "s": 15237, "text": "output:" }, { "code": null, "e": 15343, "s": 15245, "text": "# ls -a. .. .bash_history .bash_logout .bashrc .cache .profile test1.sh test.sh .viminfo" }, { "code": null, "e": 15434, "s": 15343, "text": "# ls -A.bash_history .bash_logout .bashrc .cache .profile test1.sh test.sh .viminfo" }, { "code": null, "e": 15445, "s": 15434, "text": "Example-8:" }, { "code": null, "e": 15475, "s": 15445, "text": "To display files recursively:" }, { "code": null, "e": 15496, "s": 15475, "text": "$ ls -R /etc/network" }, { "code": null, "e": 15504, "s": 15496, "text": "output:" }, { "code": null, "e": 15929, "s": 15504, "text": "# ls -R /etc/network//etc/network/:if-down.d if-post-down.d if-pre-up.d if-up.d interfaces interfaces.d run/etc/network/if-down.d:resolvconf upstart wpasupplicant/etc/network/if-post-down.d:bridge wireless-tools wpasupplicant/etc/network/if-pre-up.d:bridge ethtool wireless-tools wpasupplicant/etc/network/if-up.d:000resolvconf ethtool ntpdate openssh-server upstart wpasupplicant/etc/network/interfaces.d:" }, { "code": null, "e": 15940, "s": 15929, "text": "Example-9:" }, { "code": null, "e": 15970, "s": 15940, "text": "To display file inode number:" }, { "code": null, "e": 15990, "s": 15970, "text": "$ ls -i /etc/wgetrc" }, { "code": null, "e": 15998, "s": 15990, "text": "output:" }, { "code": null, "e": 16036, "s": 15998, "text": "# ls -i /etc/wgetrc526576 /etc/wgetrc" }, { "code": null, "e": 16048, "s": 16036, "text": "Example-10:" }, { "code": null, "e": 16056, "s": 16048, "text": "output:" }, { "code": null, "e": 16129, "s": 16056, "text": "$ ls -n .bash_logout-rw-r--r-- 1 1000 1000 220 Dec 28 05:28 .bash_logout" }, { "code": null, "e": 16141, "s": 16129, "text": "Example-11:" }, { "code": null, "e": 16197, "s": 16141, "text": "Visual Classification of Files With Special Characters:" }, { "code": null, "e": 16205, "s": 16197, "text": "$ ls -F" }, { "code": null, "e": 16417, "s": 16205, "text": "Instead of doing the ‘ls -l’ and then the checking for the first character to \ndetermine the type of file. You can use -F which classifies the file with different \nspecial character for different kind of files.\n" }, { "code": null, "e": 16425, "s": 16417, "text": "output:" }, { "code": null, "e": 16592, "s": 16425, "text": "# ls -F /bin/ boot/ dev/ etc/ home/ initrd.img@ lib/ lib64/ lost+found/ media/ mnt/ opt/ proc/ root/ run/ sbin/ srv/ sys/ tmp/ usr/ var/ vmlinuz@" }, { "code": null, "e": 16627, "s": 16592, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 16655, "s": 16627, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 16689, "s": 16655, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 16706, "s": 16689, "text": " Frahaan Hussain" }, { "code": null, "e": 16739, "s": 16706, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 16750, "s": 16739, "text": " Pradeep D" }, { "code": null, "e": 16785, "s": 16750, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 16801, "s": 16785, "text": " Musab Zayadneh" }, { "code": null, "e": 16834, "s": 16801, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 16846, "s": 16834, "text": " GUHARAJANM" }, { "code": null, "e": 16878, "s": 16846, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 16886, "s": 16878, "text": " Uplatz" }, { "code": null, "e": 16893, "s": 16886, "text": " Print" }, { "code": null, "e": 16904, "s": 16893, "text": " Add Notes" } ]
Console Class in C#
The Console class in C# is used to represent the standard input, output, and error streams for console applications. Let us see some examples of Console class properties in C# − To change the CursorLeft of the Console in C#, use the Console.CursorLeft property. Let us see an example − using System; class Demo { public static void Main (string[] args) { Console.BackgroundColor = ConsoleColor.Blue; Console.WriteLine("Background color changed = "+Console.BackgroundColor); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("\nForeground color changed = "+Console.ForegroundColor); Console.CursorLeft = 30; Console.Write("CursorLeft position: "+Console.CursorLeft); } } This will produce the following output − To change the CursorSize of the Console in C#, use the Console.CursorSize property in C#. Let us see an example − using System; class Demo { public static void Main (string[] args) { Console.BackgroundColor = ConsoleColor.Blue; Console.WriteLine("Background color changed = "+Console.BackgroundColor); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("\nForeground color changed = "+Console.ForegroundColor); Console.CursorSize = 1; Console.WriteLine("\nCursorSize = "+Console.CursorSize); } } This will produce the following output − To change the BufferWidth of the Console, use the Console.BufferWidth property. Let us now see an example − using System; class Demo { public static void Main (string[] args) { Console.BufferHeight = 200; Console.WriteLine("Buffer Height = "+Console.BufferHeight); Console.BufferHeight = 250; Console.WriteLine("Buffer Width = "+Console.BufferWidth); } } This will produce the following output − Buffer Height = 200 Buffer Width = 200
[ { "code": null, "e": 1179, "s": 1062, "text": "The Console class in C# is used to represent the standard input, output, and error streams for console applications." }, { "code": null, "e": 1240, "s": 1179, "text": "Let us see some examples of Console class properties in C# −" }, { "code": null, "e": 1324, "s": 1240, "text": "To change the CursorLeft of the Console in C#, use the Console.CursorLeft property." }, { "code": null, "e": 1348, "s": 1324, "text": "Let us see an example −" }, { "code": null, "e": 1790, "s": 1348, "text": "using System;\nclass Demo {\n public static void Main (string[] args) {\n Console.BackgroundColor = ConsoleColor.Blue;\n Console.WriteLine(\"Background color changed = \"+Console.BackgroundColor);\n Console.ForegroundColor = ConsoleColor.Yellow;\n Console.WriteLine(\"\\nForeground color changed = \"+Console.ForegroundColor);\n Console.CursorLeft = 30;\n Console.Write(\"CursorLeft position: \"+Console.CursorLeft);\n }\n}\n" }, { "code": null, "e": 1831, "s": 1790, "text": "This will produce the following output −" }, { "code": null, "e": 1921, "s": 1831, "text": "To change the CursorSize of the Console in C#, use the Console.CursorSize property in C#." }, { "code": null, "e": 1945, "s": 1921, "text": "Let us see an example −" }, { "code": null, "e": 2384, "s": 1945, "text": "using System;\nclass Demo {\n public static void Main (string[] args) {\n Console.BackgroundColor = ConsoleColor.Blue;\n Console.WriteLine(\"Background color changed = \"+Console.BackgroundColor);\n Console.ForegroundColor = ConsoleColor.Yellow;\n Console.WriteLine(\"\\nForeground color changed = \"+Console.ForegroundColor);\n Console.CursorSize = 1;\n Console.WriteLine(\"\\nCursorSize = \"+Console.CursorSize);\n }\n}\n" }, { "code": null, "e": 2425, "s": 2384, "text": "This will produce the following output −" }, { "code": null, "e": 2505, "s": 2425, "text": "To change the BufferWidth of the Console, use the Console.BufferWidth property." }, { "code": null, "e": 2533, "s": 2505, "text": "Let us now see an example −" }, { "code": null, "e": 2810, "s": 2533, "text": "using System;\nclass Demo {\n public static void Main (string[] args) {\n Console.BufferHeight = 200;\n Console.WriteLine(\"Buffer Height = \"+Console.BufferHeight);\n Console.BufferHeight = 250;\n Console.WriteLine(\"Buffer Width = \"+Console.BufferWidth);\n }\n}" }, { "code": null, "e": 2851, "s": 2810, "text": "This will produce the following output −" }, { "code": null, "e": 2890, "s": 2851, "text": "Buffer Height = 200\nBuffer Width = 200" } ]
How can I subtract a day from a Python date?
You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date. from datetime import datetime from datetime import timedelta today = datetime.today() yesterday = today - timedelta(days=1) print(today) print() print(yesterday) This will give the output − 2017-12-29 12:28:06.531791 2017-12-28 12:28:06.531791
[ { "code": null, "e": 1249, "s": 1062, "text": "You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date. " }, { "code": null, "e": 1411, "s": 1249, "text": "from datetime import datetime\nfrom datetime import timedelta\ntoday = datetime.today()\nyesterday = today - timedelta(days=1)\nprint(today)\nprint()\nprint(yesterday)" }, { "code": null, "e": 1439, "s": 1411, "text": "This will give the output −" }, { "code": null, "e": 1493, "s": 1439, "text": "2017-12-29 12:28:06.531791\n2017-12-28 12:28:06.531791" } ]
Explain Python Matrix with examples
A matrix in Python is a two-dimensional array having a specific number of rows and columns. The data elements in Python matrix can be numbers, strings or symbols etc. Matrix or two-dimensional list is an important data structure. Various operations associated with matrix involve transpose, addition or multiplication of two matrices. We will discuss how to declare a matrix in python with a specific number of rows and columns and then input data items from the user and finally print the matrix. A matrix in Python can be declared as a nested list. The number of rows and columns needs to be specified. Suppose number of rows is 3 and number of columns is 4. We will declare the matrix as follows Matrix=[[0]*4 for i in range(3)] col=4 rows=3 matrix=[[0]*col for i in range(rows)] for i in range(rows): print("Enter","row",i+1,"elements") for j in range(col): matrix[i][j]=int(input()) def rowvise(matrix): for i in range(rows): print(matrix[i]) print("print as nested list") print(matrix) print("print each row in separate line") rowvise(matrix) Enter row 1 elements 1 2 3 4 Enter row 2 elements 5 6 7 8 Enter row 3 elements 1 2 3 4 print as nested list [[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]] print each row in separate line [1, 2, 3, 4] [5, 6, 7, 8] [1, 2, 3, 4] These are the basic operations on matrix, which involve declaring a matrix, assigning data element values and printing a matrix. The other operations such as transpose can be achieved by applying specific logic to the given matrix.
[ { "code": null, "e": 1229, "s": 1062, "text": "A matrix in Python is a two-dimensional array having a specific number of rows and columns. The data elements in Python matrix can be numbers, strings or symbols etc." }, { "code": null, "e": 1397, "s": 1229, "text": "Matrix or two-dimensional list is an important data structure. Various operations associated with matrix involve transpose, addition or multiplication of two matrices." }, { "code": null, "e": 1560, "s": 1397, "text": "We will discuss how to declare a matrix in python with a specific number of rows and columns and then input data items from the user and finally print the matrix." }, { "code": null, "e": 1761, "s": 1560, "text": "A matrix in Python can be declared as a nested list. The number of rows and columns needs to be specified. Suppose number of rows is 3 and number of columns is 4. We will declare the matrix as follows" }, { "code": null, "e": 1794, "s": 1761, "text": "Matrix=[[0]*4 for i in range(3)]" }, { "code": null, "e": 2133, "s": 1794, "text": "col=4\nrows=3\nmatrix=[[0]*col for i in range(rows)]\nfor i in range(rows):\n print(\"Enter\",\"row\",i+1,\"elements\")\n for j in range(col):\n matrix[i][j]=int(input())\n\ndef rowvise(matrix):\n for i in range(rows):\n print(matrix[i])\nprint(\"print as nested list\")\nprint(matrix)\nprint(\"print each row in separate line\")\nrowvise(matrix)" }, { "code": null, "e": 2355, "s": 2133, "text": "Enter row 1 elements\n1\n2\n3\n4\nEnter row 2 elements\n5\n6\n7\n8\nEnter row 3 elements\n1\n2\n3\n4\nprint as nested list\n[[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]\nprint each row in separate line\n[1, 2, 3, 4]\n[5, 6, 7, 8]\n[1, 2, 3, 4]" }, { "code": null, "e": 2587, "s": 2355, "text": "These are the basic operations on matrix, which involve declaring a matrix, assigning data element values and printing a matrix. The other operations such as transpose can be achieved by applying specific logic to the given matrix." } ]
How to validate given date formats like MM-DD-YYYY using regex in java?
The java.util.regex package of java provides various classes to find particular patterns in character sequences. The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely − compile() − This method accepts a string representing a regular expression and returns an object of the Pattern object. compile() − This method accepts a string representing a regular expression and returns an object of the Pattern object. matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object. matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object. Following is the regular expression to match date in dd-MM-yyyy format: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$ Therefore, to validate a date String of the format MM-DD-YYYY − Compile the above mentioned regular expression using the compile() method of the Pattern class and retrieve the Pattern object. Compile the above mentioned regular expression using the compile() method of the Pattern class and retrieve the Pattern object. Using the object obtained above, invoke the matcher() method by passing the required date string as a parameter and retrieve the Matcher object from this method. Using the object obtained above, invoke the matcher() method by passing the required date string as a parameter and retrieve the Matcher object from this method. The matches() of the Matcher class returns true in case of a match else, it returns false. Invoker this method on the matcher object obtained from the previous step. The matches() of the Matcher class returns true in case of a match else, it returns false. Invoker this method on the matcher object obtained from the previous step. import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatchingDate { public static void main(String[] args) { String date = "01/12/2019"; String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(date); boolean bool = matcher.matches(); if(bool) { System.out.println("Date is valid"); } else { System.out.println("Date is not valid"); } } } Date is valid
[ { "code": null, "e": 1175, "s": 1062, "text": "The java.util.regex package of java provides various classes to find particular patterns in character sequences." }, { "code": null, "e": 1348, "s": 1175, "text": "The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely −" }, { "code": null, "e": 1468, "s": 1348, "text": "compile() − This method accepts a string representing a regular expression and returns an object of the Pattern object." }, { "code": null, "e": 1588, "s": 1468, "text": "compile() − This method accepts a string representing a regular expression and returns an object of the Pattern object." }, { "code": null, "e": 1753, "s": 1588, "text": "matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object." }, { "code": null, "e": 1918, "s": 1753, "text": "matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object." }, { "code": null, "e": 1990, "s": 1918, "text": "Following is the regular expression to match date in dd-MM-yyyy format:" }, { "code": null, "e": 2042, "s": 1990, "text": "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$" }, { "code": null, "e": 2106, "s": 2042, "text": "Therefore, to validate a date String of the format MM-DD-YYYY −" }, { "code": null, "e": 2234, "s": 2106, "text": "Compile the above mentioned regular expression using the compile() method of the Pattern class and retrieve the Pattern object." }, { "code": null, "e": 2362, "s": 2234, "text": "Compile the above mentioned regular expression using the compile() method of the Pattern class and retrieve the Pattern object." }, { "code": null, "e": 2524, "s": 2362, "text": "Using the object obtained above, invoke the matcher() method by passing the required date string as a parameter and retrieve the Matcher object from this method." }, { "code": null, "e": 2686, "s": 2524, "text": "Using the object obtained above, invoke the matcher() method by passing the required date string as a parameter and retrieve the Matcher object from this method." }, { "code": null, "e": 2852, "s": 2686, "text": "The matches() of the Matcher class returns true in case of a match else, it returns false. Invoker this method on the matcher object obtained from the previous step." }, { "code": null, "e": 3018, "s": 2852, "text": "The matches() of the Matcher class returns true in case of a match else, it returns false. Invoker this method on the matcher object obtained from the previous step." }, { "code": null, "e": 3628, "s": 3018, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MatchingDate {\n public static void main(String[] args) {\n String date = \"01/12/2019\";\n String regex = \"^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(date);\n boolean bool = matcher.matches();\n if(bool) {\n System.out.println(\"Date is valid\");\n } else {\n System.out.println(\"Date is not valid\");\n }\n }\n}" }, { "code": null, "e": 3642, "s": 3628, "text": "Date is valid" } ]
Walmart Interview Experience - GeeksforGeeks
22 Jun, 2021 Round 1: It was an online round hosted by Walmart on dare2dare. It consisted of 2 coding questions. The coding question goes like this : 1: This question is also asked in the onsite 2nd intuit interview of SDE-1. Exactly one swap Given a string S containing lowercase English alphabet characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap. In one swap,Geek can pick two distinct indexes i and j (i.e 1 < i < j < |S| ) of the string, then swap the characters at the position i and j. Example 1: Input: S = "geek" Output: 6 Explanation: After one swap, there are only 6 distinct strings possible. (i.e "egek","eegk","geek","geke","gkee" and "keeg") 2: This question is also asked in the Hackwithinfy online round. Partition the array Given an array A[] of N integers. The task is to partition the array into four non-empty parts P,Q,R and S. Let W,X,Y and Z be the sum of the elements in P,Q,R and S respectively. The absolute difference of the maximum and the minimum among W,X,Y and Z should be smallest. Find the smallest absolute difference of the maximum and the minimum among W,X,Y and Z. Example 1: Input: N = 5 A[] = [4,2,2,5,1] Output: 4 Explanation: let partition the array P,Q,R,S = [4],[2,2],[5],[1] W = 4, X = 4, Y = 5, Z = 1 Difference = max(W,X,Y,Z) – min(W,X,Y,Z) = 5 – 1 = 4 Marketing Walmart Interview Experiences Walmart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between ANN, CNN and RNN Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (On-Campus) Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Amazon Interview Experience (Off-Campus) 2022 Goldman Sachs Interview Experience (2021-2022) Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 Infosys DSE Interview Experience 2021 How to write an Interview Experience? Infosys DSE Interview Experience 2021
[ { "code": null, "e": 24859, "s": 24831, "text": "\n22 Jun, 2021" }, { "code": null, "e": 24997, "s": 24859, "text": "Round 1: It was an online round hosted by Walmart on dare2dare. It consisted of 2 coding questions. The coding question goes like this : " }, { "code": null, "e": 25091, "s": 24997, "text": "1: This question is also asked in the onsite 2nd intuit interview of SDE-1. Exactly one swap " }, { "code": null, "e": 25271, "s": 25091, "text": "Given a string S containing lowercase English alphabet characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap. " }, { "code": null, "e": 25415, "s": 25271, "text": "In one swap,Geek can pick two distinct indexes i and j (i.e 1 < i < j < |S| ) of the string, then swap the characters at the position i and j. " }, { "code": null, "e": 25581, "s": 25417, "text": "Example 1:\nInput:\nS = \"geek\"\nOutput:\n6\nExplanation:\nAfter one swap, there are only 6 distinct strings possible.\n(i.e \"egek\",\"eegk\",\"geek\",\"geke\",\"gkee\" and \"keeg\")" }, { "code": null, "e": 25649, "s": 25583, "text": "2: This question is also asked in the Hackwithinfy online round. " }, { "code": null, "e": 25670, "s": 25649, "text": "Partition the array " }, { "code": null, "e": 25779, "s": 25670, "text": "Given an array A[] of N integers. The task is to partition the array into four non-empty parts P,Q,R and S. " }, { "code": null, "e": 26033, "s": 25779, "text": "Let W,X,Y and Z be the sum of the elements in P,Q,R and S respectively. The absolute difference of the maximum and the minimum among W,X,Y and Z should be smallest. Find the smallest absolute difference of the maximum and the minimum among W,X,Y and Z. " }, { "code": null, "e": 26232, "s": 26035, "text": "Example 1: Input: N = 5 A[] = [4,2,2,5,1] Output: 4 Explanation: let partition the array P,Q,R,S = [4],[2,2],[5],[1] W = 4, X = 4, Y = 5, Z = 1 Difference = max(W,X,Y,Z) – min(W,X,Y,Z) = 5 – 1 = 4" }, { "code": null, "e": 26246, "s": 26236, "text": "Marketing" }, { "code": null, "e": 26254, "s": 26246, "text": "Walmart" }, { "code": null, "e": 26276, "s": 26254, "text": "Interview Experiences" }, { "code": null, "e": 26284, "s": 26276, "text": "Walmart" }, { "code": null, "e": 26382, "s": 26284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26391, "s": 26382, "text": "Comments" }, { "code": null, "e": 26404, "s": 26391, "text": "Old Comments" }, { "code": null, "e": 26440, "s": 26404, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 26478, "s": 26440, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 26528, "s": 26478, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 26593, "s": 26528, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 26639, "s": 26593, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 26686, "s": 26639, "text": "Goldman Sachs Interview Experience (2021-2022)" }, { "code": null, "e": 26758, "s": 26686, "text": "Infosys Interview Experience for DSE - System Engineer | On-Campus 2022" }, { "code": null, "e": 26796, "s": 26758, "text": "Infosys DSE Interview Experience 2021" }, { "code": null, "e": 26834, "s": 26796, "text": "How to write an Interview Experience?" } ]
ReactJS Semantic UI Search Module - GeeksforGeeks
27 Jul, 2021 Semantic UI is a modern framework used in developing seamless designs for the website. It gives the user a lightweight experience with its components. It uses predefined CSS and JQuery to incorporate them into different frameworks. In this article, we will learn how to use the Search Module in ReactJS Semantic UI. The Search Module helps a user to search for a query and fetch it. Properties: Standard(Custom Render): Custom render is used for custom rendering and it displays the set of results for rendering. Category: Category properties are used to display categories of the remote content. Category(Custom Render): Category custom rendering is helpful for the Search for categories with custom rendering. Syntax: <Search /> Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername cd foldername Step 3: Install semantic UI in your given directory. npm install semantic-ui-react semantic-ui-css npm install semantic-ui-react semantic-ui-css Project Structure: It will look like the following. Step to Run Application: Run the application from the root directory of the project, using the following command. npm start Example 1: This is the basic example which shows how to use a search module. App.js import React from 'react'import { Search } from 'semantic-ui-react' const styleLink = document.createElement("link");styleLink.rel = "stylesheet";styleLink.href = "https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css";document.head.appendChild(styleLink); const btt = () => ( <div id='gfg'> <h1>GeeksforGeeks</h1> <h4>ReactJS semantic UI Search module</h4> <Search/> </div>)export default btt Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: In this example, we are showing the size and loading property in a dropdown. App.js import React from 'react'import { Search } from 'semantic-ui-react' const styleLink = document.createElement("link");styleLink.rel = "stylesheet";styleLink.href = "https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css";document.head.appendChild(styleLink); const btt = () => ( <div id='gfg'> <h1>GeeksforGeeks</h1> <h4>ReactJS semantic UI Search module</h4> <Search loading size='massive'/> </div>)export default btt</div> Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react.semantic-ui.com/modules/search Semantic-UI JavaScript ReactJS Web Technologies 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 How to create a link in JavaScript ? How to Show Images on Click using HTML ? How to remove an HTML element using JavaScript ? Remove elements from a JavaScript Array How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? How to navigate on path by button click in react router ?
[ { "code": null, "e": 24921, "s": 24893, "text": "\n27 Jul, 2021" }, { "code": null, "e": 25153, "s": 24921, "text": "Semantic UI is a modern framework used in developing seamless designs for the website. It gives the user a lightweight experience with its components. It uses predefined CSS and JQuery to incorporate them into different frameworks." }, { "code": null, "e": 25304, "s": 25153, "text": "In this article, we will learn how to use the Search Module in ReactJS Semantic UI. The Search Module helps a user to search for a query and fetch it." }, { "code": null, "e": 25316, "s": 25304, "text": "Properties:" }, { "code": null, "e": 25435, "s": 25316, "text": "Standard(Custom Render): Custom render is used for custom rendering and it displays the set of results for rendering." }, { "code": null, "e": 25519, "s": 25435, "text": "Category: Category properties are used to display categories of the remote content." }, { "code": null, "e": 25634, "s": 25519, "text": "Category(Custom Render): Category custom rendering is helpful for the Search for categories with custom rendering." }, { "code": null, "e": 25642, "s": 25634, "text": "Syntax:" }, { "code": null, "e": 25653, "s": 25642, "text": "<Search />" }, { "code": null, "e": 25705, "s": 25655, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25800, "s": 25705, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 25832, "s": 25800, "text": "npx create-react-app foldername" }, { "code": null, "e": 25945, "s": 25832, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 25959, "s": 25945, "text": "cd foldername" }, { "code": null, "e": 26058, "s": 25959, "text": "Step 3: Install semantic UI in your given directory. npm install semantic-ui-react semantic-ui-css" }, { "code": null, "e": 26105, "s": 26058, "text": " npm install semantic-ui-react semantic-ui-css" }, { "code": null, "e": 26157, "s": 26105, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26272, "s": 26157, "text": "Step to Run Application: Run the application from the root directory of the project, using the following command." }, { "code": null, "e": 26282, "s": 26272, "text": "npm start" }, { "code": null, "e": 26359, "s": 26282, "text": "Example 1: This is the basic example which shows how to use a search module." }, { "code": null, "e": 26366, "s": 26359, "text": "App.js" }, { "code": "import React from 'react'import { Search } from 'semantic-ui-react' const styleLink = document.createElement(\"link\");styleLink.rel = \"stylesheet\";styleLink.href = \"https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css\";document.head.appendChild(styleLink); const btt = () => ( <div id='gfg'> <h1>GeeksforGeeks</h1> <h4>ReactJS semantic UI Search module</h4> <Search/> </div>)export default btt", "e": 26778, "s": 26366, "text": null }, { "code": null, "e": 26877, "s": 26778, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 26965, "s": 26877, "text": "Example 2: In this example, we are showing the size and loading property in a dropdown." }, { "code": null, "e": 26972, "s": 26965, "text": "App.js" }, { "code": "import React from 'react'import { Search } from 'semantic-ui-react' const styleLink = document.createElement(\"link\");styleLink.rel = \"stylesheet\";styleLink.href = \"https://cdn.jsdelivr.net/npm/semantic-ui/dist/semantic.min.css\";document.head.appendChild(styleLink); const btt = () => ( <div id='gfg'> <h1>GeeksforGeeks</h1> <h4>ReactJS semantic UI Search module</h4> <Search loading size='massive'/> </div>)export default btt</div>", "e": 27413, "s": 26972, "text": null }, { "code": null, "e": 27512, "s": 27413, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27568, "s": 27512, "text": "Reference: https://react.semantic-ui.com/modules/search" }, { "code": null, "e": 27580, "s": 27568, "text": "Semantic-UI" }, { "code": null, "e": 27591, "s": 27580, "text": "JavaScript" }, { "code": null, "e": 27599, "s": 27591, "text": "ReactJS" }, { "code": null, "e": 27616, "s": 27599, "text": "Web Technologies" }, { "code": null, "e": 27714, "s": 27616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27723, "s": 27714, "text": "Comments" }, { "code": null, "e": 27736, "s": 27723, "text": "Old Comments" }, { "code": null, "e": 27797, "s": 27736, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27834, "s": 27797, "text": "How to create a link in JavaScript ?" }, { "code": null, "e": 27875, "s": 27834, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 27924, "s": 27875, "text": "How to remove an HTML element using JavaScript ?" }, { "code": null, "e": 27964, "s": 27924, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28007, "s": 27964, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28052, "s": 28007, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 28117, "s": 28052, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28185, "s": 28117, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Elon Musk & Twitter. A frequency and sentiment analysis on... | by Joy Harjanto | Towards Data Science
Twitter is a powerful microblogging tool that has transformed conversation since its inception- for better or worse. There is so much data available because of its millions of globally active users to harvest and utilize. Elon Musk, CEO of Tesla and SpaceX, has been the subject of controversies because of his recent tweets. I thought since he is one of the famous men alive, analyzing his conduct and reputation on Twitter would be interesting. I divided my project into several components: Analysis on Musk’s tweeting frequency, sentiment analysis on Musk’s tweets, sentiment analysis on tweets about Musk, with word clouds as products. I did my project with R and Twitter’s API. Link to set it up API here. The code below established the connection between twitter and R Studios: twitter_token<-create_token(app = "joysentiment1", api_key, api_secret, accessToken, accessTokenSecret, set_renv = TRUE) I went on to extract Elon Musk’s 5,000 tweets afterwards. em_tweets<-get_timeline("ElonMusk",n=5000) Part 1: Tweets Frequency I first looked at Elon Musk’s tweeting habits over the past couple years. He joined Twitter in 2009 but only his tweets since the year 2016 are available. ggplot(data = em_tweets,aes(x=em_tweets$month,group=factor(year(created_at)), color=factor(year(created_at)))) +geom_line(stat="count") +geom_point(stat="count") +labs(x="Month", colour="Year",y="Number of tweets") +theme_classic() Elon Musk notably started tweeting more frequently in the months of May and June. Some of his most memorable tweets this past May include the announcement of his idea to create a Yelp for journalists. I created another visualization of his tweets frequency over the course of 12 months, which unsurprisingly also that he is most active on Twitter when in the months of May, June and July. ggplot(data = em_tweets, aes(x = em_tweets$month)) +geom_bar(aes(fill = ..count..)) +xlab("Month") + ylab("Number of tweets") +theme_classic() This gives rise to an important question: Why has Musk been spending more time tweeting than he has in the past? Part Two: Sentiment analysis on Musk’s tweets Sentiment analysis is the process of quantifying and categorizing words towards a particular emotion/product. I was introduced to the concept in class and became more interested after reading about it here. I went to pursue a sentiment analysis on Elon Musk’s 5,000 tweets and was curious to see how this sentiment changed this past year. I took advantage of the “NRC” lexicon, which categorizes words into sentiments such as “happy”, “sad”, etc. I saw that Elon Musk’s tweets are dominantly rooted in positive, trust and anticipation sentiments in my first visualization. ggplot(data=primaryscores,aes(x=sentiment,y=Score))+geom_bar(aes(fill=sentiment),stat = "identity")+xlab("Sentiments")+ylab("Scores")+ggtitle("Total sentiment based on scores")+theme(legend.position="none")+theme_minimal() I also wanted to see how his sentiment has changed over the past couple months in 2018. ggplot(data=monthly_sentiment,aes(x=month,y=value,group=sentiment))+geom_line(aes(color=factor(sentiment)))+geom_point(aes(color=factor(sentiment)))+labs(x="Month", colour="Sentiment",y="Value")+theme_minimal() The positive sentiments spiked between the months of April and June. But we can see that anger, negative, anticipation and trust sentiments also experienced a similar increase. This finding makes sense, given his many public Twitter quarrels. Elon frequently tweets about his life experiences in a positive manner, especially about his companies: Tesla and SpaceX. Another aspect I wanted to cover is his vocabulary usage. The most effective way to do so was by creating a word cloud, something I realized after I read this guide. This proved to be the most challenging part of this task as I had to create a list of stop words that include and are not limited to: just, like, way, also, actually. Stop words are used to remove words that don’t add value into the analysis. It was difficult to completely remove all the stop words since these words are the backbone of his tweets. wordcloud(em_text_corpus,min.freq=1,max.words=50,scale=c(2.5,1),colors=brewer.pal(8,"Accent"),random.color=T,random.order=F) Elon Musk uses his twitter account to talk about his work in Tesla, The Boring Company, and SpaceX as evident in this word cloud. His pride in his companies and optimistic outlook on the future is reflected in his tweets. Part 3: Sentiment analysis on tweets about Elon Musk The beauty of Twitter is the ability to join in on other people’s conversations. I took advantage of this feature to see how Elon Musk is depicted by most users. I did so by doing another sentiment analysis. I went to mine 1,000 tweets. elon_raw<-searchTwitter("elon",lang="en",n=1000) I performed another sentiment analysis but this time by assigning scores to each word: Positive words have scores of greater than 0 and negative words have scores of less than 0. The distribution of scores of tweets about Elon is as follows: I created another word cloud by implementing the technique I had above to see what the popular words are. wordcloud(elon_text_corpus,min.freq=1,max.words=50,scale=c(2.5,1),colors=brewer.pal(8,"Accent"),random.color=T,random.order=F) It appears that Twitter users don’t recriprocate Elon Musk’s positive sentiments. Most of Twitter users talk about his recent pursuits, scandals, and personal life, instead of his work in his companies. It is the case of the cliche saying, two sides to a coin. The effectiveness of Twitter depends on the user itself. While some argue that Elon Musk must soon change his tweeting habits if he doesn’t want to hurt his companies, this fate is still uncertain. It is evident that in spite of his positive tweets, most people don’t necessarily feel the same way. This project was fun and challenging to do. I’ll upload the extended code on my GitHub. If you want to learn more about it and the code I used for sentiment analysis, I’ve included some references at the bottom of the page. I initially had difficult setting up the API, creating the list of stop words and implementing the code. There are limitations to my findings so feel free to give me feed back if you ike. To conclude, here’s one of Elon Musk’s very best. Important Packages: library(wordcloud)library(httr)library(rtweet)library(twitteR)library(plyr)library(ggplot2)library(devtools)library(tm)library(dplyr)library(stringr)library(tidytext)library(lubridate) Reference: Setting up code for sentiment analysis
[ { "code": null, "e": 494, "s": 272, "text": "Twitter is a powerful microblogging tool that has transformed conversation since its inception- for better or worse. There is so much data available because of its millions of globally active users to harvest and utilize." }, { "code": null, "e": 719, "s": 494, "text": "Elon Musk, CEO of Tesla and SpaceX, has been the subject of controversies because of his recent tweets. I thought since he is one of the famous men alive, analyzing his conduct and reputation on Twitter would be interesting." }, { "code": null, "e": 912, "s": 719, "text": "I divided my project into several components: Analysis on Musk’s tweeting frequency, sentiment analysis on Musk’s tweets, sentiment analysis on tweets about Musk, with word clouds as products." }, { "code": null, "e": 983, "s": 912, "text": "I did my project with R and Twitter’s API. Link to set it up API here." }, { "code": null, "e": 1056, "s": 983, "text": "The code below established the connection between twitter and R Studios:" }, { "code": null, "e": 1177, "s": 1056, "text": "twitter_token<-create_token(app = \"joysentiment1\", api_key, api_secret, accessToken, accessTokenSecret, set_renv = TRUE)" }, { "code": null, "e": 1235, "s": 1177, "text": "I went on to extract Elon Musk’s 5,000 tweets afterwards." }, { "code": null, "e": 1278, "s": 1235, "text": "em_tweets<-get_timeline(\"ElonMusk\",n=5000)" }, { "code": null, "e": 1303, "s": 1278, "text": "Part 1: Tweets Frequency" }, { "code": null, "e": 1458, "s": 1303, "text": "I first looked at Elon Musk’s tweeting habits over the past couple years. He joined Twitter in 2009 but only his tweets since the year 2016 are available." }, { "code": null, "e": 1690, "s": 1458, "text": "ggplot(data = em_tweets,aes(x=em_tweets$month,group=factor(year(created_at)), color=factor(year(created_at)))) +geom_line(stat=\"count\") +geom_point(stat=\"count\") +labs(x=\"Month\", colour=\"Year\",y=\"Number of tweets\") +theme_classic()" }, { "code": null, "e": 1891, "s": 1690, "text": "Elon Musk notably started tweeting more frequently in the months of May and June. Some of his most memorable tweets this past May include the announcement of his idea to create a Yelp for journalists." }, { "code": null, "e": 2079, "s": 1891, "text": "I created another visualization of his tweets frequency over the course of 12 months, which unsurprisingly also that he is most active on Twitter when in the months of May, June and July." }, { "code": null, "e": 2222, "s": 2079, "text": "ggplot(data = em_tweets, aes(x = em_tweets$month)) +geom_bar(aes(fill = ..count..)) +xlab(\"Month\") + ylab(\"Number of tweets\") +theme_classic()" }, { "code": null, "e": 2335, "s": 2222, "text": "This gives rise to an important question: Why has Musk been spending more time tweeting than he has in the past?" }, { "code": null, "e": 2381, "s": 2335, "text": "Part Two: Sentiment analysis on Musk’s tweets" }, { "code": null, "e": 2588, "s": 2381, "text": "Sentiment analysis is the process of quantifying and categorizing words towards a particular emotion/product. I was introduced to the concept in class and became more interested after reading about it here." }, { "code": null, "e": 2828, "s": 2588, "text": "I went to pursue a sentiment analysis on Elon Musk’s 5,000 tweets and was curious to see how this sentiment changed this past year. I took advantage of the “NRC” lexicon, which categorizes words into sentiments such as “happy”, “sad”, etc." }, { "code": null, "e": 2954, "s": 2828, "text": "I saw that Elon Musk’s tweets are dominantly rooted in positive, trust and anticipation sentiments in my first visualization." }, { "code": null, "e": 3177, "s": 2954, "text": "ggplot(data=primaryscores,aes(x=sentiment,y=Score))+geom_bar(aes(fill=sentiment),stat = \"identity\")+xlab(\"Sentiments\")+ylab(\"Scores\")+ggtitle(\"Total sentiment based on scores\")+theme(legend.position=\"none\")+theme_minimal()" }, { "code": null, "e": 3265, "s": 3177, "text": "I also wanted to see how his sentiment has changed over the past couple months in 2018." }, { "code": null, "e": 3476, "s": 3265, "text": "ggplot(data=monthly_sentiment,aes(x=month,y=value,group=sentiment))+geom_line(aes(color=factor(sentiment)))+geom_point(aes(color=factor(sentiment)))+labs(x=\"Month\", colour=\"Sentiment\",y=\"Value\")+theme_minimal()" }, { "code": null, "e": 3719, "s": 3476, "text": "The positive sentiments spiked between the months of April and June. But we can see that anger, negative, anticipation and trust sentiments also experienced a similar increase. This finding makes sense, given his many public Twitter quarrels." }, { "code": null, "e": 3841, "s": 3719, "text": "Elon frequently tweets about his life experiences in a positive manner, especially about his companies: Tesla and SpaceX." }, { "code": null, "e": 4007, "s": 3841, "text": "Another aspect I wanted to cover is his vocabulary usage. The most effective way to do so was by creating a word cloud, something I realized after I read this guide." }, { "code": null, "e": 4174, "s": 4007, "text": "This proved to be the most challenging part of this task as I had to create a list of stop words that include and are not limited to: just, like, way, also, actually." }, { "code": null, "e": 4357, "s": 4174, "text": "Stop words are used to remove words that don’t add value into the analysis. It was difficult to completely remove all the stop words since these words are the backbone of his tweets." }, { "code": null, "e": 4482, "s": 4357, "text": "wordcloud(em_text_corpus,min.freq=1,max.words=50,scale=c(2.5,1),colors=brewer.pal(8,\"Accent\"),random.color=T,random.order=F)" }, { "code": null, "e": 4704, "s": 4482, "text": "Elon Musk uses his twitter account to talk about his work in Tesla, The Boring Company, and SpaceX as evident in this word cloud. His pride in his companies and optimistic outlook on the future is reflected in his tweets." }, { "code": null, "e": 4757, "s": 4704, "text": "Part 3: Sentiment analysis on tweets about Elon Musk" }, { "code": null, "e": 4919, "s": 4757, "text": "The beauty of Twitter is the ability to join in on other people’s conversations. I took advantage of this feature to see how Elon Musk is depicted by most users." }, { "code": null, "e": 4994, "s": 4919, "text": "I did so by doing another sentiment analysis. I went to mine 1,000 tweets." }, { "code": null, "e": 5043, "s": 4994, "text": "elon_raw<-searchTwitter(\"elon\",lang=\"en\",n=1000)" }, { "code": null, "e": 5285, "s": 5043, "text": "I performed another sentiment analysis but this time by assigning scores to each word: Positive words have scores of greater than 0 and negative words have scores of less than 0. The distribution of scores of tweets about Elon is as follows:" }, { "code": null, "e": 5391, "s": 5285, "text": "I created another word cloud by implementing the technique I had above to see what the popular words are." }, { "code": null, "e": 5518, "s": 5391, "text": "wordcloud(elon_text_corpus,min.freq=1,max.words=50,scale=c(2.5,1),colors=brewer.pal(8,\"Accent\"),random.color=T,random.order=F)" }, { "code": null, "e": 5779, "s": 5518, "text": "It appears that Twitter users don’t recriprocate Elon Musk’s positive sentiments. Most of Twitter users talk about his recent pursuits, scandals, and personal life, instead of his work in his companies. It is the case of the cliche saying, two sides to a coin." }, { "code": null, "e": 6078, "s": 5779, "text": "The effectiveness of Twitter depends on the user itself. While some argue that Elon Musk must soon change his tweeting habits if he doesn’t want to hurt his companies, this fate is still uncertain. It is evident that in spite of his positive tweets, most people don’t necessarily feel the same way." }, { "code": null, "e": 6302, "s": 6078, "text": "This project was fun and challenging to do. I’ll upload the extended code on my GitHub. If you want to learn more about it and the code I used for sentiment analysis, I’ve included some references at the bottom of the page." }, { "code": null, "e": 6490, "s": 6302, "text": "I initially had difficult setting up the API, creating the list of stop words and implementing the code. There are limitations to my findings so feel free to give me feed back if you ike." }, { "code": null, "e": 6540, "s": 6490, "text": "To conclude, here’s one of Elon Musk’s very best." }, { "code": null, "e": 6560, "s": 6540, "text": "Important Packages:" }, { "code": null, "e": 6745, "s": 6560, "text": "library(wordcloud)library(httr)library(rtweet)library(twitteR)library(plyr)library(ggplot2)library(devtools)library(tm)library(dplyr)library(stringr)library(tidytext)library(lubridate)" }, { "code": null, "e": 6756, "s": 6745, "text": "Reference:" } ]
yum - Unix, Linux Command
yum is an interactive, rpm based, package manager. It can automatically perform system updates, including dependency analysis and obsolete processing based on "repository" metadata. It can also perform installation of new packages, removal of old packages and perform queries on the installed and/or available packages among many other commands/services (see below). yum is similar to other high level package managers like apt-get and smart. While there are some graphical interfaces directly to the yum code, more recent graphical interface development is happening with PackageKit and the gnome-packagekit application. command is one of: * install package1 [package2] [...] * update [package1] [package2] [...] * check-update * upgrade [package1] [package2] [...] * remove | erase package1 [package2] [...] * list [...] * info [...] * provides | whatprovides feature1 [feature2] [...] * clean [ packages | headers | metadata | dbcache | all ] * makecache * groupinstall group1 [group2] [...] * groupupdate group1 [group2] [...] * grouplist [hidden] [groupwildcard] [...] * groupremove group1 [group2] [...] * groupinfo group1 [...] * search string1 [string2] [...] * shell [filename] * resolvedep dep1 [dep2] [...] * localinstall rpmfile1 [rpmfile2] [...] * localupdate rpmfile1 [rpmfile2] [...] * reinstall package1 [package2] [...] * downgrade package1 [package2] [...] * deplist package1 [package2] [...] * repolist [all|enabled|disabled] * help [command] Unless the --help or -h option is given, one of the above commands must be present. Repository configuration is honored in all operations. If the main obsoletes configure option is true (default) or the --obsoletes flag is present yum will include package obsoletes in its calculations - this makes it better for distro-version changes, for example: upgrading from somelinux 8.0 to somelinux 9. 1. The plugin module file must be installed in the plugin path as just described. 2. The global plugins option in /etc/yum/yum.conf must be set to ‘1’. 3. A configuration file for the plugin must exist in /etc/yum/pluginconf.d/<plugin_name>.conf and the enabled setting in this file must set to ‘1’. The minimal content for such a configuration file is: /etc/yum.conf /etc/yum.repos.d/ /etc/yum/pluginconf.d/ /var/cache/yum/ See the Authors file included with this program. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 11022, "s": 10577, "text": "\nyum is an interactive, rpm based, package manager. It can automatically\nperform system updates, including dependency analysis and obsolete processing\nbased on \"repository\" metadata. It can also perform installation of new\npackages, removal of old packages and perform queries on the installed and/or\navailable packages among many other commands/services (see below). yum\nis similar to other high level package managers like apt-get and smart.\n" }, { "code": null, "e": 11203, "s": 11022, "text": "\nWhile there are some graphical interfaces directly to the yum code, more\nrecent graphical interface development is happening with PackageKit and the\ngnome-packagekit application.\n" }, { "code": null, "e": 12095, "s": 11203, "text": "\ncommand is one of:\n\n * install package1 [package2] [...] \n * update [package1] [package2] [...] \n * check-update \n * upgrade [package1] [package2] [...] \n * remove | erase package1 [package2] [...] \n * list [...] \n * info [...] \n * provides | whatprovides feature1 [feature2] [...] \n * clean [ packages | headers | metadata | dbcache | all ] \n * makecache \n * groupinstall group1 [group2] [...] \n * groupupdate group1 [group2] [...] \n * grouplist [hidden] [groupwildcard] [...] \n * groupremove group1 [group2] [...] \n * groupinfo group1 [...] \n * search string1 [string2] [...] \n * shell [filename] \n * resolvedep dep1 [dep2] [...] \n * localinstall rpmfile1 [rpmfile2] [...] \n * localupdate rpmfile1 [rpmfile2] [...] \n * reinstall package1 [package2] [...] \n * downgrade package1 [package2] [...] \n * deplist package1 [package2] [...] \n * repolist [all|enabled|disabled] \n * help [command] " }, { "code": null, "e": 12181, "s": 12095, "text": "\nUnless the --help or -h option is given, one of the above commands\nmust be present.\n" }, { "code": null, "e": 12238, "s": 12181, "text": "\nRepository configuration is honored in all operations.\n" }, { "code": null, "e": 12498, "s": 12240, "text": "\nIf the main obsoletes configure option is true (default) or the --obsoletes\nflag is present yum will include package\nobsoletes in its calculations - this makes it better for distro-version\nchanges, for example: upgrading from somelinux 8.0 to somelinux 9.\n" }, { "code": null, "e": 12600, "s": 12516, "text": "\n1. The plugin module file must be installed in the plugin path as just\ndescribed.\n" }, { "code": null, "e": 12672, "s": 12600, "text": "\n2. The global plugins option in /etc/yum/yum.conf must be set to ‘1’.\n" }, { "code": null, "e": 12876, "s": 12672, "text": "\n3. A configuration file for the plugin must exist in\n/etc/yum/pluginconf.d/<plugin_name>.conf and the enabled setting in this\nfile must set to ‘1’. The minimal content for such a configuration file is:\n" }, { "code": null, "e": 12952, "s": 12880, "text": "/etc/yum.conf\n/etc/yum.repos.d/\n/etc/yum/pluginconf.d/\n/var/cache/yum/\n" }, { "code": null, "e": 13010, "s": 12960, "text": "See the Authors file included with this program.\n" }, { "code": null, "e": 13031, "s": 13014, "text": "\nAdvertisements\n" }, { "code": null, "e": 13066, "s": 13031, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 13094, "s": 13066, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13128, "s": 13094, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13145, "s": 13128, "text": " Frahaan Hussain" }, { "code": null, "e": 13178, "s": 13145, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 13189, "s": 13178, "text": " Pradeep D" }, { "code": null, "e": 13224, "s": 13189, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13240, "s": 13224, "text": " Musab Zayadneh" }, { "code": null, "e": 13273, "s": 13240, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13285, "s": 13273, "text": " GUHARAJANM" }, { "code": null, "e": 13317, "s": 13285, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13325, "s": 13317, "text": " Uplatz" }, { "code": null, "e": 13332, "s": 13325, "text": " Print" }, { "code": null, "e": 13343, "s": 13332, "text": " Add Notes" } ]
Deploying a React + NodeJS Application with Docker | by Dan Murphy | Towards Data Science
I recently spent time working on a project with Dylan Edwards, and, in the following article, I will outline how we designed, built, containerized, and deployed a React + Node.js web application. The code for this project is available here. For this project, we built a SPA (single-page application) where users could input a link to a tweet and retrieve an in-depth sentiment analysis of the Tweet's contents. The sentiment analysis is broken into two parts: the overall document and each individual sentence. Prior to the development of the application, we spent some time mocking up designs in Figma. This helped us iterate early and often on the design of various components, which ultimately helped us build an enjoyable and intuitive UX. Below is the Figma page that outlines several of the designs we tested prior to beginning development. After landing on a final design (shown at the very bottom of the embedded Figma document), we structured the work into two buckets: frontend and backend. First, we needed to build a backend that retrieved data from the Twitter V2 API, sent it to the Google NLP API, and structured the responses for easy frontend consumption. To accomplish this task, we decided to use an express.js backend with one endpoint that accepts the Tweet ID as a parameter (POST /analyze/:tweet_id). When a user submits a valid tweet URL, the tweet ID is parsed from the URL and sent to the backend, where we then request tweet and user information from the Twitter V2 API, parse the response from Twitter to extract the tweet contents, and send that contents to the Google NLP API for sentiment analysis. After this, pending a successful response from both the Twitter and Google NLP APIs, the data is structured and returned to the frontend, where it is then formatted and passed to various React components. Below is a diagram of this process. For the frontend, we rely heavily on styled-components for designing the UI, redux for passing data to and from different components (this provided us with a more centralized way to manage the state of our application), and Chart.js for building the Bar Charts. Additionally, the EmbeddedTweet component is built purely with styled-components to replicate the look and feel of a tweet. After development was finished, we decided to containerize the app with Docker. To do this, we created Dockerfiles for both the frontend and backend applications and then used docker-compose to aggregate the two Dockerfiles and deploy the containers on the same network. For the frontend, the Dockerfile looks like this: Here is an overview of the commands: FROM: Defines the image we will use as the basis for our container. In this context, we use Node Version 12.18.3. LABEL: Defines the metadata for our Dockerfile, including information about the version, description, and maintainers. WORKDIR: Sets the working directory for the application. If the working directory does not already exist, it is created by Docker. COPY: Copy a file or files into the Docker container. On line 9, we list several files to copy and then specify where to copy them. The final path specified is the location the files are copied to (in this case, the working directory). RUN: Specifies a command that should be run by Docker. I typically use this command to install dependencies, debug, and execute commands in the container. In this context, we run npm install --production to only install production dependencies. EXPOSE: Tells Docker which ports the container should listen on during runtime. In this context, we expose port 3000 since that is the port that React is running on. CMD: Specifies the command that should be executed when the docker container starts. In this context, we run npm start since that is the command that starts the frontend. Similarly, we repeat this process for the backend. Below is the Dockerfile for the backend API: We follow most of the same steps as in the previous Dockerfile, with the exception of the port we expose (5000) and the command we run on startup: node backend.js Finally, after the two Dockerfiles are written we can create the docker-compose.yml file in the root of our project directory. Here is what this file looks like: First, we define the names of the services that make up our application: backend and frontend. Then, within each of these services, we provide the build context, the path to that build context’s Dockerfile, the name for the Docker image, and the necessary port mappings. Additionally, since the backend service depends on a few environment variables, we specify the path to the .env file. Lastly, and most importantly, we use the links key under the frontend service to create an alias by which the frontend service can communicate with the backend. By default, when we run docker-compose up -d both services are created under the same network and one service can communicate with the other via that service's name. By defining links in the YML file, we can now reference the backend service via the proxy defined in client/setupProxy.js at either http://be:5000 or http://backend:5000 (you can also define a proxy in the client/package.json file). You can learn more about networking with docker-compose here. Lastly, to test your application locally, you can run docker-compose up -d and navigate to http://localhost:3000. Alternatively, if you want to run the application on port 80, you must change the port's value in the frontend service of the docker-compose.yml from “3000:3000” to “80:3000”. Furthermore, you can use docker-compose logs to display the log output from the services, which is useful for debugging. Now, since we have designed, developed, and containerized our application, the next step is deployment. For this section, it is assumed that you have a basic working knowledge of AWS EC2. There are many ways to deploy a dockerized application, but for the sake of this tutorial, we will use an AWS EC2 instance. To get started. you’ll need to navigate to https://aws.amazon.com/ec2 and click on Get Started with Amazon EC2. Then, as shown in the below GIF, you can click on Launch Instance, select Ubuntu 18.04, and then Review and Launch. Prior to launching your instance, you will need to open up Port 80 (assuming this is the port you map the frontend service to). If you are mapping the frontend service to a different port, then you must do the same thing but with a different Port Range. To accomplish this, click on Edit security groups and add a new rule. When finished, your inbound rules should look like this: Now, you can click Launch, create a new key pair or use an existing one, and then connect to the EC2 instance in the AWS CloudShell or your own terminal. If you need help connecting, use the steps outlined in the following image (replacing the pem file and the public IPv4 DNS with your own instances). Alternatively, AWS has documentation on connecting to an EC2 instance here. Now, assuming that you successfully SSH’ed into your EC2 instance, you will need to install Docker and update other previously-installed software. This is accomplished with the following commands. $ sudo apt-get update # run updates$ sudo apt-get remove docker docker-engine docker.io containerd runc # remove old versions of Docker if they exist$ sudo apt install docker.io # install docker$ sudo systemctl start docker # start docker$ sudo systemctl enable docker # enable docker After this, you can check that the installation was successful with the following command: $ docker --version Now, we will clone the repository from GitHub, CD into the root directory, and run docker. $ git clone https://github.com/dylane1999/SentimentAnalysisApp.git # clone$ cd SentimentAnalysisApp # change into the directory$ docker-compose up -d # run Docker in detached state$ docker-compose logs # check logs Finally, you can navigate to the Public IPv4 address of your EC2 instance and check out the application. Assuming your Public IPv4 address is 54.175.170.20, the frontend service is mapped to Port 80, Port 80 is open to accept traffic in your inbound security rules, and you have valid Twitter API and Google NLP API Credentials set as environment variables in backend/backend.env, you will be able to open the application at http://54.175.170.20/ and submit tweet URLs for sentiment analysis! Overall, in this article, you learned about the process of designing, developing, containerizing, and deploying a full-stack web application. First, to design the application, we used Figma. During this phase, we mapped out the components of the application, iterated on the design, and created a final version that we could then build with React. After designing, we then turned our mock-ups into a fully-functioning web application. This web app is broken into two ‘buckets’: Frontend: built with React, Chart.js, Styled-Components, and Redux. Backend: built with Node.js, Express.js, and the Twitter V2 and Google NLP APIs. After completing the development of the application, we used Dockerfiles to containerize the frontend and backend and docker-compose to run the frontend and backend containers on our local computer under one network. Finally, to deploy our application, we used AWS EC2. On our EC2 instance, we opened up port 80 for inbound traffic, installed and updated the necessary software, cloned the repository, and ran docker-compose up -d to run the application.
[ { "code": null, "e": 413, "s": 172, "text": "I recently spent time working on a project with Dylan Edwards, and, in the following article, I will outline how we designed, built, containerized, and deployed a React + Node.js web application. The code for this project is available here." }, { "code": null, "e": 1019, "s": 413, "text": "For this project, we built a SPA (single-page application) where users could input a link to a tweet and retrieve an in-depth sentiment analysis of the Tweet's contents. The sentiment analysis is broken into two parts: the overall document and each individual sentence. Prior to the development of the application, we spent some time mocking up designs in Figma. This helped us iterate early and often on the design of various components, which ultimately helped us build an enjoyable and intuitive UX. Below is the Figma page that outlines several of the designs we tested prior to beginning development." }, { "code": null, "e": 2043, "s": 1019, "text": "After landing on a final design (shown at the very bottom of the embedded Figma document), we structured the work into two buckets: frontend and backend. First, we needed to build a backend that retrieved data from the Twitter V2 API, sent it to the Google NLP API, and structured the responses for easy frontend consumption. To accomplish this task, we decided to use an express.js backend with one endpoint that accepts the Tweet ID as a parameter (POST /analyze/:tweet_id). When a user submits a valid tweet URL, the tweet ID is parsed from the URL and sent to the backend, where we then request tweet and user information from the Twitter V2 API, parse the response from Twitter to extract the tweet contents, and send that contents to the Google NLP API for sentiment analysis. After this, pending a successful response from both the Twitter and Google NLP APIs, the data is structured and returned to the frontend, where it is then formatted and passed to various React components. Below is a diagram of this process." }, { "code": null, "e": 2429, "s": 2043, "text": "For the frontend, we rely heavily on styled-components for designing the UI, redux for passing data to and from different components (this provided us with a more centralized way to manage the state of our application), and Chart.js for building the Bar Charts. Additionally, the EmbeddedTweet component is built purely with styled-components to replicate the look and feel of a tweet." }, { "code": null, "e": 2750, "s": 2429, "text": "After development was finished, we decided to containerize the app with Docker. To do this, we created Dockerfiles for both the frontend and backend applications and then used docker-compose to aggregate the two Dockerfiles and deploy the containers on the same network. For the frontend, the Dockerfile looks like this:" }, { "code": null, "e": 2787, "s": 2750, "text": "Here is an overview of the commands:" }, { "code": null, "e": 2901, "s": 2787, "text": "FROM: Defines the image we will use as the basis for our container. In this context, we use Node Version 12.18.3." }, { "code": null, "e": 3020, "s": 2901, "text": "LABEL: Defines the metadata for our Dockerfile, including information about the version, description, and maintainers." }, { "code": null, "e": 3151, "s": 3020, "text": "WORKDIR: Sets the working directory for the application. If the working directory does not already exist, it is created by Docker." }, { "code": null, "e": 3387, "s": 3151, "text": "COPY: Copy a file or files into the Docker container. On line 9, we list several files to copy and then specify where to copy them. The final path specified is the location the files are copied to (in this case, the working directory)." }, { "code": null, "e": 3632, "s": 3387, "text": "RUN: Specifies a command that should be run by Docker. I typically use this command to install dependencies, debug, and execute commands in the container. In this context, we run npm install --production to only install production dependencies." }, { "code": null, "e": 3798, "s": 3632, "text": "EXPOSE: Tells Docker which ports the container should listen on during runtime. In this context, we expose port 3000 since that is the port that React is running on." }, { "code": null, "e": 3969, "s": 3798, "text": "CMD: Specifies the command that should be executed when the docker container starts. In this context, we run npm start since that is the command that starts the frontend." }, { "code": null, "e": 4065, "s": 3969, "text": "Similarly, we repeat this process for the backend. Below is the Dockerfile for the backend API:" }, { "code": null, "e": 4212, "s": 4065, "text": "We follow most of the same steps as in the previous Dockerfile, with the exception of the port we expose (5000) and the command we run on startup:" }, { "code": null, "e": 4228, "s": 4212, "text": "node backend.js" }, { "code": null, "e": 4390, "s": 4228, "text": "Finally, after the two Dockerfiles are written we can create the docker-compose.yml file in the root of our project directory. Here is what this file looks like:" }, { "code": null, "e": 4964, "s": 4390, "text": "First, we define the names of the services that make up our application: backend and frontend. Then, within each of these services, we provide the build context, the path to that build context’s Dockerfile, the name for the Docker image, and the necessary port mappings. Additionally, since the backend service depends on a few environment variables, we specify the path to the .env file. Lastly, and most importantly, we use the links key under the frontend service to create an alias by which the frontend service can communicate with the backend. By default, when we run" }, { "code": null, "e": 4985, "s": 4964, "text": "docker-compose up -d" }, { "code": null, "e": 5401, "s": 4985, "text": "both services are created under the same network and one service can communicate with the other via that service's name. By defining links in the YML file, we can now reference the backend service via the proxy defined in client/setupProxy.js at either http://be:5000 or http://backend:5000 (you can also define a proxy in the client/package.json file). You can learn more about networking with docker-compose here." }, { "code": null, "e": 5455, "s": 5401, "text": "Lastly, to test your application locally, you can run" }, { "code": null, "e": 5476, "s": 5455, "text": "docker-compose up -d" }, { "code": null, "e": 5716, "s": 5476, "text": "and navigate to http://localhost:3000. Alternatively, if you want to run the application on port 80, you must change the port's value in the frontend service of the docker-compose.yml from “3000:3000” to “80:3000”. Furthermore, you can use" }, { "code": null, "e": 5736, "s": 5716, "text": "docker-compose logs" }, { "code": null, "e": 5812, "s": 5736, "text": "to display the log output from the services, which is useful for debugging." }, { "code": null, "e": 6236, "s": 5812, "text": "Now, since we have designed, developed, and containerized our application, the next step is deployment. For this section, it is assumed that you have a basic working knowledge of AWS EC2. There are many ways to deploy a dockerized application, but for the sake of this tutorial, we will use an AWS EC2 instance. To get started. you’ll need to navigate to https://aws.amazon.com/ec2 and click on Get Started with Amazon EC2." }, { "code": null, "e": 6352, "s": 6236, "text": "Then, as shown in the below GIF, you can click on Launch Instance, select Ubuntu 18.04, and then Review and Launch." }, { "code": null, "e": 6733, "s": 6352, "text": "Prior to launching your instance, you will need to open up Port 80 (assuming this is the port you map the frontend service to). If you are mapping the frontend service to a different port, then you must do the same thing but with a different Port Range. To accomplish this, click on Edit security groups and add a new rule. When finished, your inbound rules should look like this:" }, { "code": null, "e": 7112, "s": 6733, "text": "Now, you can click Launch, create a new key pair or use an existing one, and then connect to the EC2 instance in the AWS CloudShell or your own terminal. If you need help connecting, use the steps outlined in the following image (replacing the pem file and the public IPv4 DNS with your own instances). Alternatively, AWS has documentation on connecting to an EC2 instance here." }, { "code": null, "e": 7309, "s": 7112, "text": "Now, assuming that you successfully SSH’ed into your EC2 instance, you will need to install Docker and update other previously-installed software. This is accomplished with the following commands." }, { "code": null, "e": 7594, "s": 7309, "text": "$ sudo apt-get update # run updates$ sudo apt-get remove docker docker-engine docker.io containerd runc # remove old versions of Docker if they exist$ sudo apt install docker.io # install docker$ sudo systemctl start docker # start docker$ sudo systemctl enable docker # enable docker" }, { "code": null, "e": 7685, "s": 7594, "text": "After this, you can check that the installation was successful with the following command:" }, { "code": null, "e": 7704, "s": 7685, "text": "$ docker --version" }, { "code": null, "e": 7795, "s": 7704, "text": "Now, we will clone the repository from GitHub, CD into the root directory, and run docker." }, { "code": null, "e": 8010, "s": 7795, "text": "$ git clone https://github.com/dylane1999/SentimentAnalysisApp.git # clone$ cd SentimentAnalysisApp # change into the directory$ docker-compose up -d # run Docker in detached state$ docker-compose logs # check logs" }, { "code": null, "e": 8503, "s": 8010, "text": "Finally, you can navigate to the Public IPv4 address of your EC2 instance and check out the application. Assuming your Public IPv4 address is 54.175.170.20, the frontend service is mapped to Port 80, Port 80 is open to accept traffic in your inbound security rules, and you have valid Twitter API and Google NLP API Credentials set as environment variables in backend/backend.env, you will be able to open the application at http://54.175.170.20/ and submit tweet URLs for sentiment analysis!" }, { "code": null, "e": 8645, "s": 8503, "text": "Overall, in this article, you learned about the process of designing, developing, containerizing, and deploying a full-stack web application." }, { "code": null, "e": 8851, "s": 8645, "text": "First, to design the application, we used Figma. During this phase, we mapped out the components of the application, iterated on the design, and created a final version that we could then build with React." }, { "code": null, "e": 8981, "s": 8851, "text": "After designing, we then turned our mock-ups into a fully-functioning web application. This web app is broken into two ‘buckets’:" }, { "code": null, "e": 9049, "s": 8981, "text": "Frontend: built with React, Chart.js, Styled-Components, and Redux." }, { "code": null, "e": 9130, "s": 9049, "text": "Backend: built with Node.js, Express.js, and the Twitter V2 and Google NLP APIs." }, { "code": null, "e": 9347, "s": 9130, "text": "After completing the development of the application, we used Dockerfiles to containerize the frontend and backend and docker-compose to run the frontend and backend containers on our local computer under one network." } ]
7 popular activation functions you should know in Deep Learning and how to use them with Keras and TensorFlow 2 | by B. Chen | Towards Data Science
In artificial neural networks (ANNs), the activation function is a mathematical “gate” in between the input feeding the current neuron and its output going to the next layer [1]. The activation functions are at the very core of Deep Learning. They determine the output of a model, its accuracy, and computational efficiency. In some cases, activation functions have a major effect on the model’s ability to converge and the convergence speed. In this article, you’ll learn the following most popular activation functions in Deep Learning and how to use them with Keras and TensorFlow 2. Sigmoid (Logistic)Hyperbolic Tangent (Tanh)Rectified Linear Unit (ReLU)Leaky ReLUParametric Leaky ReLU (PReLU)Exponential Linear Units (ELU)Scaled Exponential Linear Unit (SELU) Sigmoid (Logistic) Hyperbolic Tangent (Tanh) Rectified Linear Unit (ReLU) Leaky ReLU Parametric Leaky ReLU (PReLU) Exponential Linear Units (ELU) Scaled Exponential Linear Unit (SELU) Please check out Notebook for the source code. The Sigmoid function (also known as the Logistic function) is one of the most widely used activation function. The function is defined as: The plot of the function and its derivative. As we can see in the plot above, The function is a common S-shaped curve. The output of the function is centered at 0.5 with a range from 0 to 1. The function is differentiable. That means we can find the slope of the sigmoid curve at any two points. The function is monotonic but the function’s derivative is not. The Sigmoid function was introduced to Artificial Neural Networks (ANN) in the 1990s to replace the Step function [2]. It was a key change to ANN architecture because the Step function doesn’t have any gradient to work with Gradient Descent, while the Sigmoid function has a well-defined nonzero derivative everywhere, allowing Gradient Descent to make some progress at every step during training. The main problems with the Sigmoid function are: Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at 0 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers [2].Computationally expensive: the function has an exponential operation.The output is not zero centered: Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at 0 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers [2]. Computationally expensive: the function has an exponential operation. The output is not zero centered: To use the Sigmoid activation function with Keras and TensorFlow 2, we can simply pass 'sigmoid' to the argument activation : from tensorflow.keras.layers import DenseDense(10, activation='sigmoid') To apply the function for some constant inputs: import tensorflow as tffrom tensorflow.keras.activations import sigmoidz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = sigmoid(z)output.numpy() Another very popular and widely used activation function is the Hyperbolic Tangent, also known as Tanh. It is defined as: The plot of the function and its derivative: We can see that the function is very similar to the Sigmoid function. The function is a common S-shaped curve as well. The difference is that the output of Tanh is zero centered with a range from -1 to 1 (instead of 0 to 1 in the case of the Sigmoid function) The same as the Sigmoid, this function is differentiable The same as the Sigmoid, the function is monotonic, but the function’s derivative is not. Tanh has characteristics similar to Sigmoid that can work with Gradient Descent. One important point to mention is that Tanh tends to make each layer’s output more or less centered around 0 and this often helps speed up convergence [2]. Since Tanh has characteristics similar to Sigmoid, it also faces the following two problems: Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at -1 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers.Computationally expensive: the function has an exponential operation. Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at -1 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers. Computationally expensive: the function has an exponential operation. To use the Tanh, we can simply pass 'tanh' to the argument activation: from tensorflow.keras.layers import DenseDense(10, activation='tanh') To apply the function for some constant inputs: import tensorflow as tffrom tensorflow.keras.activations import tanhz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = tanh(z)output.numpy() The Rectified Linear Unit (ReLU) is the most commonly used activation function in deep learning. The function returns 0 if the input is negative, but for any positive input, it returns that value back. The function is defined as: The plot of the function and its derivative: As we can see that: Graphically, the ReLU function is composed of two linear pieces to account for non-linearities. A function is non-linear if the slope isn’t constant. So, the ReLU function is non-linear around 0, but the slope is always either 0 (for negative inputs) or 1 (for positive inputs). The ReLU function is continuous, but it is not differentiable because its derivative is 0 for any negative input. The output of ReLU does not have a maximum value (It is not saturated) and this helps Gradient Descent The function is very fast to compute (Compare to Sigmoid and Tanh) It’s surprising that such a simple function works very well in deep neural networks. ReLU works great in most applications, but it is not perfect. It suffers from a problem known as the dying ReLU. Dying ReLU During training, some neurons effectively die, meaning they stop outputting anything other than 0. In some cases, you may find that half of your network’s neurons are dead, especially if you used a large learning rate. A neuron dies when its weights get tweaked in such a way that the weighted sum of its inputs are negative for all instances in the training set. When this happens, it just keeps outputting 0s, and gradient descent does not affect it anymore since the gradient of the ReLU function is 0 when its input is negative. Hands-on Machine Learning [2], page 329 To use ReLU with Keras and TensorFlow 2, just set activation='relu' from tensorflow.keras.layers import DenseDense(10, activation='relu') To apply the function for some constant inputs: import tensorflow as tffrom tensorflow.keras.activations import reluz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = relu(z)output.numpy() Leaky ReLU is an improvement over the ReLU activation function. It has all properties of ReLU, plus it will never have dying ReLU problem. Leaky ReLU is defined as: f(x) = max(αx, x) The hyperparameter α defines how much the function leaks. It is the slope of the function for x < 0 and is typically set to 0.01. The small slope ensures that Leaky ReLU never dies. To use the Leaky ReLU activation function, you must create a LeakyReLU instance like below: from tensorflow.keras.layers import LeakyReLU, Denseleaky_relu = LeakyReLU(alpha=0.01)Dense(10, activation=leaky_relu) Parametric leaky ReLU (PReLU) is a variation of Leaky ReLU, where α is authorized to be learned during training (instead of being a hyperparameter, it becomes a parameter that can be modified by backpropagation like any other parameters). This was reported to strongly outperform ReLU on large image datasets, but on smaller datasets it runs the risk of overfitting the training set [2]. To use Parametric leaky ReLU, you must create a PReLU instance like below: from tensorflow.keras.layers import PReLU, Densepara_relu = PReLU()Dense(10, activation=para_relu) Exponential Linear Unit (ELU) is a variation of ReLU with a better output for z < 0. The function is defined as: The hyperparameter α controls the value to which an ELU saturates for negative net inputs. The plot of the function and its derivative: We can see in the plot above, ELU modified the slope of the negative part of the function. Unlike the Leaky ReLU and PReLU functions, instead of a straight line, ELU uses a log curve for the negative values. According to the authors, ELU outperformed all the ReLU variants in their experiments [3]. According to [2, 3], the main drawback of the ELU activation is that it is slower to compute than the ReLU and its variants (due to the use of the exponential function), but during training this is compensated by the faster convergence rate. However, at test time, an ELU network will be slower than a ReLU network. Implementing ELU in TensorFlow 2 is trivial, just specify the activation function when building each layer: Dense(10, activation='elu') To apply the function for some constant inputs: import tensorflow as tffrom tensorflow.keras.activations import eluz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = elu(z, alpha=1)output.numpy() Exponential Linear Unit (SELU) activation function is another variation of ReLU proposed by Günter Klambauer et al. [4] in 2017. The authors showed that if you build a neural network composed exclusively of a stack of dense layers, and if all hidden layers use the SELU activation function, then the network will self-normalize (the output of each layer will tend to preserve mean 0 and standard deviation 1 during training, which resolves the vanishing/exploding gradients problem). This activation function often outperforms other activation functions very significantly. SELU is defined as: f(x) = scale * x , z > 0 = scale * α * (exp(x) - 1) , z <= 0 where α and scale are pre-defined constants (α=1.67326324 and scale=1.05070098). The plot of SELU and its derivative: The main problem with SELU is that there are a few conditions for SELU to work: SELU works only for a neural network composed exclusively of a stack of dense layers. It might not work for convolutional neural networks. Every hidden layer’s weights must also be initialized using LeCun normal initialization. Input features must be standardized with mean 0 and standard deviation. To use SELU with Keras and TensorFlow 2, just set activation='selu' and kernel_initializer='lecun_normal': from tensorflow.keras.layers import DenseDense(10, activation='relu', kernel_initializer='lecun_normal') We have gone through 7 different activation functions in deep learning. When building a model, the selection of activation functions is critical. So which activation function should you use? Here is a general suggestion from the book Hands-on ML Although your mileage will vary, in general SELU > ELU > leaky ReLU (and its variants) > ReLU > tanh > logistic. If the network’s architecture prevents it from self-normalizing, then ELU may perform better than SELU (since SELU is not smooth at z = 0). If you care a lot about runtime latency, then you may prefer leaky ReLU. If you don’t want to tweak yet another hyperparameter, you may just use the default α values used by Keras (e.g., 0.3 for the leaky ReLU). If you have spare time and computing power, you can use cross-validation to evaluate other activation functions, in particular, RReLU if your network is over‐fitting, or PReLU if you have a huge training set. Hands-on ML, page 332 In this article, we have gone through 7 different activation functions in Deep Learning and how to use them with Keras and TensorFlow. I hope this article will help you to save time in building and tuning your own Deep Learning model. I recommend you to check out the Keras documentation for the activation functions and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. Building custom callbacks with Keras and TensorFlow 2 A practical introduction to Keras Callbacks in TensorFlow 2 Learning Rate Schedules in practice The Google’s 7 steps of Machine Learning in practice: a TensorFlow example for structured data 3 ways to create a Machine Learning Model with Keras and TensorFlow 2.0 Batch normalization in practice: an example with Keras and TensorFlow 2.0 Early stopping in Practice: an example with Keras and TensorFlow More can be found from my Github [1] 7 Types of Neural Network activation function [2] Hands-on Machine Learning [3] Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs) [4] Self-Normalizing Neural Networks
[ { "code": null, "e": 350, "s": 171, "text": "In artificial neural networks (ANNs), the activation function is a mathematical “gate” in between the input feeding the current neuron and its output going to the next layer [1]." }, { "code": null, "e": 614, "s": 350, "text": "The activation functions are at the very core of Deep Learning. They determine the output of a model, its accuracy, and computational efficiency. In some cases, activation functions have a major effect on the model’s ability to converge and the convergence speed." }, { "code": null, "e": 758, "s": 614, "text": "In this article, you’ll learn the following most popular activation functions in Deep Learning and how to use them with Keras and TensorFlow 2." }, { "code": null, "e": 936, "s": 758, "text": "Sigmoid (Logistic)Hyperbolic Tangent (Tanh)Rectified Linear Unit (ReLU)Leaky ReLUParametric Leaky ReLU (PReLU)Exponential Linear Units (ELU)Scaled Exponential Linear Unit (SELU)" }, { "code": null, "e": 955, "s": 936, "text": "Sigmoid (Logistic)" }, { "code": null, "e": 981, "s": 955, "text": "Hyperbolic Tangent (Tanh)" }, { "code": null, "e": 1010, "s": 981, "text": "Rectified Linear Unit (ReLU)" }, { "code": null, "e": 1021, "s": 1010, "text": "Leaky ReLU" }, { "code": null, "e": 1051, "s": 1021, "text": "Parametric Leaky ReLU (PReLU)" }, { "code": null, "e": 1082, "s": 1051, "text": "Exponential Linear Units (ELU)" }, { "code": null, "e": 1120, "s": 1082, "text": "Scaled Exponential Linear Unit (SELU)" }, { "code": null, "e": 1167, "s": 1120, "text": "Please check out Notebook for the source code." }, { "code": null, "e": 1306, "s": 1167, "text": "The Sigmoid function (also known as the Logistic function) is one of the most widely used activation function. The function is defined as:" }, { "code": null, "e": 1351, "s": 1306, "text": "The plot of the function and its derivative." }, { "code": null, "e": 1384, "s": 1351, "text": "As we can see in the plot above," }, { "code": null, "e": 1425, "s": 1384, "text": "The function is a common S-shaped curve." }, { "code": null, "e": 1497, "s": 1425, "text": "The output of the function is centered at 0.5 with a range from 0 to 1." }, { "code": null, "e": 1602, "s": 1497, "text": "The function is differentiable. That means we can find the slope of the sigmoid curve at any two points." }, { "code": null, "e": 1666, "s": 1602, "text": "The function is monotonic but the function’s derivative is not." }, { "code": null, "e": 2064, "s": 1666, "text": "The Sigmoid function was introduced to Artificial Neural Networks (ANN) in the 1990s to replace the Step function [2]. It was a key change to ANN architecture because the Step function doesn’t have any gradient to work with Gradient Descent, while the Sigmoid function has a well-defined nonzero derivative everywhere, allowing Gradient Descent to make some progress at every step during training." }, { "code": null, "e": 2113, "s": 2064, "text": "The main problems with the Sigmoid function are:" }, { "code": null, "e": 2514, "s": 2113, "text": "Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at 0 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers [2].Computationally expensive: the function has an exponential operation.The output is not zero centered:" }, { "code": null, "e": 2814, "s": 2514, "text": "Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at 0 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers [2]." }, { "code": null, "e": 2884, "s": 2814, "text": "Computationally expensive: the function has an exponential operation." }, { "code": null, "e": 2917, "s": 2884, "text": "The output is not zero centered:" }, { "code": null, "e": 3043, "s": 2917, "text": "To use the Sigmoid activation function with Keras and TensorFlow 2, we can simply pass 'sigmoid' to the argument activation :" }, { "code": null, "e": 3116, "s": 3043, "text": "from tensorflow.keras.layers import DenseDense(10, activation='sigmoid')" }, { "code": null, "e": 3164, "s": 3116, "text": "To apply the function for some constant inputs:" }, { "code": null, "e": 3321, "s": 3164, "text": "import tensorflow as tffrom tensorflow.keras.activations import sigmoidz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = sigmoid(z)output.numpy()" }, { "code": null, "e": 3443, "s": 3321, "text": "Another very popular and widely used activation function is the Hyperbolic Tangent, also known as Tanh. It is defined as:" }, { "code": null, "e": 3488, "s": 3443, "text": "The plot of the function and its derivative:" }, { "code": null, "e": 3558, "s": 3488, "text": "We can see that the function is very similar to the Sigmoid function." }, { "code": null, "e": 3607, "s": 3558, "text": "The function is a common S-shaped curve as well." }, { "code": null, "e": 3748, "s": 3607, "text": "The difference is that the output of Tanh is zero centered with a range from -1 to 1 (instead of 0 to 1 in the case of the Sigmoid function)" }, { "code": null, "e": 3805, "s": 3748, "text": "The same as the Sigmoid, this function is differentiable" }, { "code": null, "e": 3895, "s": 3805, "text": "The same as the Sigmoid, the function is monotonic, but the function’s derivative is not." }, { "code": null, "e": 4132, "s": 3895, "text": "Tanh has characteristics similar to Sigmoid that can work with Gradient Descent. One important point to mention is that Tanh tends to make each layer’s output more or less centered around 0 and this often helps speed up convergence [2]." }, { "code": null, "e": 4225, "s": 4132, "text": "Since Tanh has characteristics similar to Sigmoid, it also faces the following two problems:" }, { "code": null, "e": 4591, "s": 4225, "text": "Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at -1 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers.Computationally expensive: the function has an exponential operation." }, { "code": null, "e": 4888, "s": 4591, "text": "Vanishing gradient: looking at the function plot, you can see that when inputs become small or large, the function saturates at -1 or 1, with a derivative extremely close to 0. Thus it has almost no gradient to propagate back through the network, so there is almost nothing left for lower layers." }, { "code": null, "e": 4958, "s": 4888, "text": "Computationally expensive: the function has an exponential operation." }, { "code": null, "e": 5029, "s": 4958, "text": "To use the Tanh, we can simply pass 'tanh' to the argument activation:" }, { "code": null, "e": 5099, "s": 5029, "text": "from tensorflow.keras.layers import DenseDense(10, activation='tanh')" }, { "code": null, "e": 5147, "s": 5099, "text": "To apply the function for some constant inputs:" }, { "code": null, "e": 5298, "s": 5147, "text": "import tensorflow as tffrom tensorflow.keras.activations import tanhz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = tanh(z)output.numpy()" }, { "code": null, "e": 5528, "s": 5298, "text": "The Rectified Linear Unit (ReLU) is the most commonly used activation function in deep learning. The function returns 0 if the input is negative, but for any positive input, it returns that value back. The function is defined as:" }, { "code": null, "e": 5573, "s": 5528, "text": "The plot of the function and its derivative:" }, { "code": null, "e": 5593, "s": 5573, "text": "As we can see that:" }, { "code": null, "e": 5872, "s": 5593, "text": "Graphically, the ReLU function is composed of two linear pieces to account for non-linearities. A function is non-linear if the slope isn’t constant. So, the ReLU function is non-linear around 0, but the slope is always either 0 (for negative inputs) or 1 (for positive inputs)." }, { "code": null, "e": 5986, "s": 5872, "text": "The ReLU function is continuous, but it is not differentiable because its derivative is 0 for any negative input." }, { "code": null, "e": 6089, "s": 5986, "text": "The output of ReLU does not have a maximum value (It is not saturated) and this helps Gradient Descent" }, { "code": null, "e": 6156, "s": 6089, "text": "The function is very fast to compute (Compare to Sigmoid and Tanh)" }, { "code": null, "e": 6241, "s": 6156, "text": "It’s surprising that such a simple function works very well in deep neural networks." }, { "code": null, "e": 6354, "s": 6241, "text": "ReLU works great in most applications, but it is not perfect. It suffers from a problem known as the dying ReLU." }, { "code": null, "e": 6365, "s": 6354, "text": "Dying ReLU" }, { "code": null, "e": 6898, "s": 6365, "text": "During training, some neurons effectively die, meaning they stop outputting anything other than 0. In some cases, you may find that half of your network’s neurons are dead, especially if you used a large learning rate. A neuron dies when its weights get tweaked in such a way that the weighted sum of its inputs are negative for all instances in the training set. When this happens, it just keeps outputting 0s, and gradient descent does not affect it anymore since the gradient of the ReLU function is 0 when its input is negative." }, { "code": null, "e": 6938, "s": 6898, "text": "Hands-on Machine Learning [2], page 329" }, { "code": null, "e": 7006, "s": 6938, "text": "To use ReLU with Keras and TensorFlow 2, just set activation='relu'" }, { "code": null, "e": 7076, "s": 7006, "text": "from tensorflow.keras.layers import DenseDense(10, activation='relu')" }, { "code": null, "e": 7124, "s": 7076, "text": "To apply the function for some constant inputs:" }, { "code": null, "e": 7275, "s": 7124, "text": "import tensorflow as tffrom tensorflow.keras.activations import reluz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = relu(z)output.numpy()" }, { "code": null, "e": 7440, "s": 7275, "text": "Leaky ReLU is an improvement over the ReLU activation function. It has all properties of ReLU, plus it will never have dying ReLU problem. Leaky ReLU is defined as:" }, { "code": null, "e": 7458, "s": 7440, "text": "f(x) = max(αx, x)" }, { "code": null, "e": 7640, "s": 7458, "text": "The hyperparameter α defines how much the function leaks. It is the slope of the function for x < 0 and is typically set to 0.01. The small slope ensures that Leaky ReLU never dies." }, { "code": null, "e": 7732, "s": 7640, "text": "To use the Leaky ReLU activation function, you must create a LeakyReLU instance like below:" }, { "code": null, "e": 7851, "s": 7732, "text": "from tensorflow.keras.layers import LeakyReLU, Denseleaky_relu = LeakyReLU(alpha=0.01)Dense(10, activation=leaky_relu)" }, { "code": null, "e": 8239, "s": 7851, "text": "Parametric leaky ReLU (PReLU) is a variation of Leaky ReLU, where α is authorized to be learned during training (instead of being a hyperparameter, it becomes a parameter that can be modified by backpropagation like any other parameters). This was reported to strongly outperform ReLU on large image datasets, but on smaller datasets it runs the risk of overfitting the training set [2]." }, { "code": null, "e": 8314, "s": 8239, "text": "To use Parametric leaky ReLU, you must create a PReLU instance like below:" }, { "code": null, "e": 8413, "s": 8314, "text": "from tensorflow.keras.layers import PReLU, Densepara_relu = PReLU()Dense(10, activation=para_relu)" }, { "code": null, "e": 8526, "s": 8413, "text": "Exponential Linear Unit (ELU) is a variation of ReLU with a better output for z < 0. The function is defined as:" }, { "code": null, "e": 8617, "s": 8526, "text": "The hyperparameter α controls the value to which an ELU saturates for negative net inputs." }, { "code": null, "e": 8662, "s": 8617, "text": "The plot of the function and its derivative:" }, { "code": null, "e": 8692, "s": 8662, "text": "We can see in the plot above," }, { "code": null, "e": 8753, "s": 8692, "text": "ELU modified the slope of the negative part of the function." }, { "code": null, "e": 8870, "s": 8753, "text": "Unlike the Leaky ReLU and PReLU functions, instead of a straight line, ELU uses a log curve for the negative values." }, { "code": null, "e": 8961, "s": 8870, "text": "According to the authors, ELU outperformed all the ReLU variants in their experiments [3]." }, { "code": null, "e": 9277, "s": 8961, "text": "According to [2, 3], the main drawback of the ELU activation is that it is slower to compute than the ReLU and its variants (due to the use of the exponential function), but during training this is compensated by the faster convergence rate. However, at test time, an ELU network will be slower than a ReLU network." }, { "code": null, "e": 9385, "s": 9277, "text": "Implementing ELU in TensorFlow 2 is trivial, just specify the activation function when building each layer:" }, { "code": null, "e": 9413, "s": 9385, "text": "Dense(10, activation='elu')" }, { "code": null, "e": 9461, "s": 9413, "text": "To apply the function for some constant inputs:" }, { "code": null, "e": 9619, "s": 9461, "text": "import tensorflow as tffrom tensorflow.keras.activations import eluz = tf.constant([-20, -1, 0, 1.2], dtype=tf.float32)output = elu(z, alpha=1)output.numpy()" }, { "code": null, "e": 10194, "s": 9619, "text": "Exponential Linear Unit (SELU) activation function is another variation of ReLU proposed by Günter Klambauer et al. [4] in 2017. The authors showed that if you build a neural network composed exclusively of a stack of dense layers, and if all hidden layers use the SELU activation function, then the network will self-normalize (the output of each layer will tend to preserve mean 0 and standard deviation 1 during training, which resolves the vanishing/exploding gradients problem). This activation function often outperforms other activation functions very significantly." }, { "code": null, "e": 10214, "s": 10194, "text": "SELU is defined as:" }, { "code": null, "e": 10297, "s": 10214, "text": "f(x) = scale * x , z > 0 = scale * α * (exp(x) - 1) , z <= 0" }, { "code": null, "e": 10378, "s": 10297, "text": "where α and scale are pre-defined constants (α=1.67326324 and scale=1.05070098)." }, { "code": null, "e": 10415, "s": 10378, "text": "The plot of SELU and its derivative:" }, { "code": null, "e": 10495, "s": 10415, "text": "The main problem with SELU is that there are a few conditions for SELU to work:" }, { "code": null, "e": 10634, "s": 10495, "text": "SELU works only for a neural network composed exclusively of a stack of dense layers. It might not work for convolutional neural networks." }, { "code": null, "e": 10723, "s": 10634, "text": "Every hidden layer’s weights must also be initialized using LeCun normal initialization." }, { "code": null, "e": 10795, "s": 10723, "text": "Input features must be standardized with mean 0 and standard deviation." }, { "code": null, "e": 10902, "s": 10795, "text": "To use SELU with Keras and TensorFlow 2, just set activation='selu' and kernel_initializer='lecun_normal':" }, { "code": null, "e": 11007, "s": 10902, "text": "from tensorflow.keras.layers import DenseDense(10, activation='relu', kernel_initializer='lecun_normal')" }, { "code": null, "e": 11253, "s": 11007, "text": "We have gone through 7 different activation functions in deep learning. When building a model, the selection of activation functions is critical. So which activation function should you use? Here is a general suggestion from the book Hands-on ML" }, { "code": null, "e": 11927, "s": 11253, "text": "Although your mileage will vary, in general SELU > ELU > leaky ReLU (and its variants) > ReLU > tanh > logistic. If the network’s architecture prevents it from self-normalizing, then ELU may perform better than SELU (since SELU is not smooth at z = 0). If you care a lot about runtime latency, then you may prefer leaky ReLU. If you don’t want to tweak yet another hyperparameter, you may just use the default α values used by Keras (e.g., 0.3 for the leaky ReLU). If you have spare time and computing power, you can use cross-validation to evaluate other activation functions, in particular, RReLU if your network is over‐fitting, or PReLU if you have a huge training set." }, { "code": null, "e": 11949, "s": 11927, "text": "Hands-on ML, page 332" }, { "code": null, "e": 12084, "s": 11949, "text": "In this article, we have gone through 7 different activation functions in Deep Learning and how to use them with Keras and TensorFlow." }, { "code": null, "e": 12309, "s": 12084, "text": "I hope this article will help you to save time in building and tuning your own Deep Learning model. I recommend you to check out the Keras documentation for the activation functions and to know about other things you can do." }, { "code": null, "e": 12461, "s": 12309, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 12515, "s": 12461, "text": "Building custom callbacks with Keras and TensorFlow 2" }, { "code": null, "e": 12575, "s": 12515, "text": "A practical introduction to Keras Callbacks in TensorFlow 2" }, { "code": null, "e": 12611, "s": 12575, "text": "Learning Rate Schedules in practice" }, { "code": null, "e": 12706, "s": 12611, "text": "The Google’s 7 steps of Machine Learning in practice: a TensorFlow example for structured data" }, { "code": null, "e": 12778, "s": 12706, "text": "3 ways to create a Machine Learning Model with Keras and TensorFlow 2.0" }, { "code": null, "e": 12852, "s": 12778, "text": "Batch normalization in practice: an example with Keras and TensorFlow 2.0" }, { "code": null, "e": 12917, "s": 12852, "text": "Early stopping in Practice: an example with Keras and TensorFlow" }, { "code": null, "e": 12950, "s": 12917, "text": "More can be found from my Github" }, { "code": null, "e": 13000, "s": 12950, "text": "[1] 7 Types of Neural Network activation function" }, { "code": null, "e": 13030, "s": 13000, "text": "[2] Hands-on Machine Learning" }, { "code": null, "e": 13109, "s": 13030, "text": "[3] Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)" } ]
Python Speed Test: 5 Methods To Remove The ‘$’ From Your Data in Python | by Chaim Gluck | Towards Data Science
In a previous post about a regression project on Iowa liquor sales, I mentioned that it was my first time working with data large enough to worry about writing code to optimize speed. In this post, I’ll walk through a relatively simple example of that process. Here’s a look at the data we’re working with. Notice the ‘state_bottle_retail’ column. Every entry starts with a dollar sign, and to make the values numeric, I’ll need to remove those dollar signs. There are a bunch of different ways to accomplish this in Python. But due to the size of this data set, optimization becomes important. I’ll demonstrate some of the ways, and report how much time they took. One note: I’ll be doing these tests on a small subset of about 10% of the entire data set. So even though the speeds are all very fast, with the slowest at just over 130 milliseconds, when the scale gets larger, it will matter more. This is also intended as a representation of the importance and practice of optimization. This is a relatively simplistic example, but in certain situation, practices like these can save hours or even days. For these tests, I’ll be using the %timeit cell magic in Jupyter Notebooks. This is a convenient tool which runs multiple loops of the operation and reports it’s best performance time. To do it, you simply type %timeit at the beginning of the row with your operation, run the cell, and see the results. First, I’ll show you a picture of all the tests I ran, and then we’ll walk through them one by one. First, I used the str.replace('$','') method on the entire column. This is the most straightforward method, as it simply replaces the ‘$’ with a blank space for each item in the column. This was the slowest option, as you can see, but it still relatively quick like I mentioned above. That means it would only take about a second to do this on the full data set with over 2 million rows. That’s fast. But this article is about getting faster. The next method uses the pandas ‘apply’ method, which is optimized to perform operations over a pandas column. The ‘apply’ method requires a function to run on each value in the column, so I wrote a lambda function to do the same function. In this post, I talk more about using the ‘apply’ method with lambda functions. In this example, it looks like this: %timeit df.state_bottle_retail.apply(lambda x: x.replace('$','')) The .apply method worked just like it’s supposed to, and sped up the operation to 117 ms. Lookin’ good. For the next step, I changed the .replace method to the .strip method. It does one less operation. Instead of replacing the ‘$’ with a blank space, it just takes out the ‘$.’ That looks like this: %timeit df.state_bottle_retail.apply(lambda x: x.strip('$')) That sped it up to just under 100 ms for the whole column. Getting better! Next up was a list comprehension. List comprehensions are a very efficient method of iterating over a lot of objects in Python. So I tried the same .strip method with a list comprehension instead of the .apply method. That looks like this: %timeit [x.strip('$') for x in df.state_bottle_retail] The list comprehension bumped us up to 72.3 ms. Nice! Lastly, I tried another way. Instead of using a function to pull out the ‘$’, I used Python built in [] slicing. It’s often used to slice and select the values you need from a list, but it can slice strings as well. So [1:] slices each string from the second value until the end. Since Python is zero-indexed, which means it starts counting at 0, the number 1 is the second value. The ‘:’ tells it to slice until the end of the string. Here’s the final list comprehension using the string slicing method: %timeit [x[1:] for x in df.state_bottle_retail] That clocks in at a blazing 31.4 ms, which is not only the fastest time, but also the largest increase in speed for any of these tests. This method is far and away the fastest, but there’s one caveat to using it. If any of the values don’t have a ‘$’ in front, this will actually take off the first number in that string. So you have to be careful when using this method. My personal choice would be to use the fourth method, the list comprehension with the .strip method. Even though it isn’t the fastest, it’s less risky. Depending on the size of your data and your confidence in it’s integrity, you’ll have to make the decision. One small note: to make any of these changes actually work, you’d have to assign the changed values back to the column you are changing in your DataFrame. That would look like this: df.state_bottle_retail = [x.strip('$') for x in df.state_bottle_retail] Optimizing your code’s speed is a fun and interesting process. It’s not always necessary to do, but it’s a good idea to get used to thinking in that way, especially if you want to work with big data or deploy code to customers. Have fun! Update: ‘nzdatascientist’ commented with a different method below. I gave it a try on the same data, and it’s lightning quick. It outperforms the other methods by far without the danger of removing other values if the entry doesn’t have a ‘$’. Here it is: np.fromstring(df.state_bottle_retail.values.astype('|S7').tobytes().replace(b'$',b''), dtype='|S6') That clocks in at a blazing 14.3 ms, more than double as quick as the risky string slicing method, and almost 10 times as fast as the slowest demonstrated method. It looks like numpy’s .fromstring method is optimized for this type of process. Also, converting to bytes and replacing those quickens the process as well. Thanks ‘nzdatascientist’!
[ { "code": null, "e": 432, "s": 171, "text": "In a previous post about a regression project on Iowa liquor sales, I mentioned that it was my first time working with data large enough to worry about writing code to optimize speed. In this post, I’ll walk through a relatively simple example of that process." }, { "code": null, "e": 630, "s": 432, "text": "Here’s a look at the data we’re working with. Notice the ‘state_bottle_retail’ column. Every entry starts with a dollar sign, and to make the values numeric, I’ll need to remove those dollar signs." }, { "code": null, "e": 1277, "s": 630, "text": "There are a bunch of different ways to accomplish this in Python. But due to the size of this data set, optimization becomes important. I’ll demonstrate some of the ways, and report how much time they took. One note: I’ll be doing these tests on a small subset of about 10% of the entire data set. So even though the speeds are all very fast, with the slowest at just over 130 milliseconds, when the scale gets larger, it will matter more. This is also intended as a representation of the importance and practice of optimization. This is a relatively simplistic example, but in certain situation, practices like these can save hours or even days." }, { "code": null, "e": 1580, "s": 1277, "text": "For these tests, I’ll be using the %timeit cell magic in Jupyter Notebooks. This is a convenient tool which runs multiple loops of the operation and reports it’s best performance time. To do it, you simply type %timeit at the beginning of the row with your operation, run the cell, and see the results." }, { "code": null, "e": 1680, "s": 1580, "text": "First, I’ll show you a picture of all the tests I ran, and then we’ll walk through them one by one." }, { "code": null, "e": 2123, "s": 1680, "text": "First, I used the str.replace('$','') method on the entire column. This is the most straightforward method, as it simply replaces the ‘$’ with a blank space for each item in the column. This was the slowest option, as you can see, but it still relatively quick like I mentioned above. That means it would only take about a second to do this on the full data set with over 2 million rows. That’s fast. But this article is about getting faster." }, { "code": null, "e": 2480, "s": 2123, "text": "The next method uses the pandas ‘apply’ method, which is optimized to perform operations over a pandas column. The ‘apply’ method requires a function to run on each value in the column, so I wrote a lambda function to do the same function. In this post, I talk more about using the ‘apply’ method with lambda functions. In this example, it looks like this:" }, { "code": null, "e": 2546, "s": 2480, "text": "%timeit df.state_bottle_retail.apply(lambda x: x.replace('$',''))" }, { "code": null, "e": 2650, "s": 2546, "text": "The .apply method worked just like it’s supposed to, and sped up the operation to 117 ms. Lookin’ good." }, { "code": null, "e": 2847, "s": 2650, "text": "For the next step, I changed the .replace method to the .strip method. It does one less operation. Instead of replacing the ‘$’ with a blank space, it just takes out the ‘$.’ That looks like this:" }, { "code": null, "e": 2908, "s": 2847, "text": "%timeit df.state_bottle_retail.apply(lambda x: x.strip('$'))" }, { "code": null, "e": 2983, "s": 2908, "text": "That sped it up to just under 100 ms for the whole column. Getting better!" }, { "code": null, "e": 3223, "s": 2983, "text": "Next up was a list comprehension. List comprehensions are a very efficient method of iterating over a lot of objects in Python. So I tried the same .strip method with a list comprehension instead of the .apply method. That looks like this:" }, { "code": null, "e": 3278, "s": 3223, "text": "%timeit [x.strip('$') for x in df.state_bottle_retail]" }, { "code": null, "e": 3332, "s": 3278, "text": "The list comprehension bumped us up to 72.3 ms. Nice!" }, { "code": null, "e": 3837, "s": 3332, "text": "Lastly, I tried another way. Instead of using a function to pull out the ‘$’, I used Python built in [] slicing. It’s often used to slice and select the values you need from a list, but it can slice strings as well. So [1:] slices each string from the second value until the end. Since Python is zero-indexed, which means it starts counting at 0, the number 1 is the second value. The ‘:’ tells it to slice until the end of the string. Here’s the final list comprehension using the string slicing method:" }, { "code": null, "e": 3885, "s": 3837, "text": "%timeit [x[1:] for x in df.state_bottle_retail]" }, { "code": null, "e": 4517, "s": 3885, "text": "That clocks in at a blazing 31.4 ms, which is not only the fastest time, but also the largest increase in speed for any of these tests. This method is far and away the fastest, but there’s one caveat to using it. If any of the values don’t have a ‘$’ in front, this will actually take off the first number in that string. So you have to be careful when using this method. My personal choice would be to use the fourth method, the list comprehension with the .strip method. Even though it isn’t the fastest, it’s less risky. Depending on the size of your data and your confidence in it’s integrity, you’ll have to make the decision." }, { "code": null, "e": 4699, "s": 4517, "text": "One small note: to make any of these changes actually work, you’d have to assign the changed values back to the column you are changing in your DataFrame. That would look like this:" }, { "code": null, "e": 4771, "s": 4699, "text": "df.state_bottle_retail = [x.strip('$') for x in df.state_bottle_retail]" }, { "code": null, "e": 5009, "s": 4771, "text": "Optimizing your code’s speed is a fun and interesting process. It’s not always necessary to do, but it’s a good idea to get used to thinking in that way, especially if you want to work with big data or deploy code to customers. Have fun!" }, { "code": null, "e": 5265, "s": 5009, "text": "Update: ‘nzdatascientist’ commented with a different method below. I gave it a try on the same data, and it’s lightning quick. It outperforms the other methods by far without the danger of removing other values if the entry doesn’t have a ‘$’. Here it is:" }, { "code": null, "e": 5365, "s": 5265, "text": "np.fromstring(df.state_bottle_retail.values.astype('|S7').tobytes().replace(b'$',b''), dtype='|S6')" } ]
Tackle Uncertainties of Linear Models | by Aurélie Giraud | Towards Data Science
Beyond the sarcasm of this quote, there is a reality: of all the statistical techniques, regression analysis is often referred to as one of the most significant in business analysis. Most companies use regression analysis to explain a particular phenomenon, build forecasting or to make predictions. These new insights can be extremely valuable in understanding what can make a difference in the business. When you work as a Data Scientist, building a linear regression model can sound pretty dull especially when it’s all about AI around you. However, I want to stress that mastering the main assumptions of linear regression models is much more elaborated than it looks and requires some solid foundation in Statistics. Another thing is that linear regression models are part of the same family of algorithms a.k.a Generalised Linear Models (GLM). GLM is an important topic for Data Scientist because they fit a broad variety of real-world phenomenon. Maybe that’s why in November 2017, Jame Le ranked linear regression models in the top 10 of Statistical Techniques Data Scientists Need to Master. Now that it’s clear why we should care about the Linear Regression Model, let’s get our hands on it. You ran a linear regression analysis and the results were significant (or not). You might think that you’re done. No, not yet my friend. After running the regression analysis, you should check if the model performed well for data. Maybe you start with regression results, such as slope coefficients, p-values, or R-squared. These parameters can give you a first glimpse on how well a model represents given data. But that’s not the whole picture though. In this post, I’ll walk you through how to check the main assumptions supporting linear regression models. But wait! First things first... There are four principal assumptions which support using a linear regression model for the purpose of inference or prediction: Linearity: Sounds obvious! We must have a linear relationship between our features and responses. This is required for our estimator and predictions to be unbiased. Linearity: Sounds obvious! We must have a linear relationship between our features and responses. This is required for our estimator and predictions to be unbiased. The next ones are concerning the residual: 2. Normality: Residuals must be Normally distributed (i.e variance tend to 1 and mean tend to zero). This is necessary for a range of statistical tests, such as the t-test. We can relax this assumption in large samples due to the central limit theorem. 3. Homoscedasticity: Means that the residuals have constant variance no matter the level of the dependent variable. 4. Independence:Residuals must be totally free of autocorrelation. For multiple linear regression, you also need to check: 5. the Absence of multicollinearity: Multicollinearity refers to when two predictors (or more) are providing the same information about the response variable. This can be a problem for the model as it generates: Redundancy → leading to unreliable coefficients of the predictors (especially for linear models) High variance of the estimator → tends to overfit meaning that the algorithm tends to model the random noise in the training data, rather than the intended output. An important predictor can become unimportant. To illustrate this article, we are gonna try to predict the sales of a company using 3 predictors: budget invested on Youtube ads, budget invested on Facebook ads and budget invested on Newspaper ads. All variables are expressed in thousands of US dollars. The dataset used can be found in Kaggle. df.head(7) For this article, I choose to use StatsModel over Scikit-learn. Despite the fact that StatsModel doesn’t have the variety of options that Scikit-learn offers, it provides statistics and econometric tools that are top of the line and validated against other statistics software like Stata and R. 🚩 Here you can find an interesting article about these 2 libraries: blog.thedataincubator.com Let’s get started! import statsmodels.formula.api as smfreg = smf.ols(‘sales~youtube+facebook+newspaper’,data=df).fit()print(reg.summary()) ✅ If we check the “basics” parameters, here is what we can see:- R-squared is quite high - Prob (F-statistic) is very low- p-value < alpha risk (5%) except for the predictor newspaper R-squared: In case you forgot or didn’t know, R-squared and Adjusted R-squared are statistics that often accompanies regression output. They are both supposed to assess the model performance with values ranges from 0 to 1. Generally, you choose the models that have higher adjusted and predicted R-squared values. Now, I have this question for you: Who is checking the goodness of fit of the model with R- squared? Content Unavailable Sorry, this content is not available in your location. I do. Or at least, I did. Until I read a few articles on the topic, showing that R-squared does NOT measure the goodness of fit because it can be:- Arbitrarily low even when the model is correct, - Dangerously close to 1 even when the model is wrong. I’m not gonna develop further into this article how come it’s possible but you can find some very good info here: statisticsbyjim.com data.library.virginia.edu So, based on the 3 parameters above, you could think that your regression model is quite good to predict the sales based on the advertising budget. Then you might want to remove the newspaper predictor as it seems not significant for the model. Of course, it would be terribly wrong to stop our analysis here. First and foremost, because you shouldn't follow blindly what R-squared says. Then, because we don’t know if the 5 key assumptions are verified. So we basically don’t know if we are in the spectrum where this model is performing well. It is time for me, to walk you through each assumption and how to verify them. If you try to fit a linear model to data which are nonlinearly or nonadditive, your predictions are likely to be seriously in error, especially when you extrapolate beyond the range of the sample data. To confirm the linearity, we can for example: Apply the Harvey-Collier multiplier test. import statsmodels.stats.api as smssms.linear_harvey_collier(reg_multi)>> Ttest_1sampResult(statistic=-1.565945529686271, pvalue=0.1192542929871369) ✅ Small p-value shows that there is a violation of linearity. Here the p-value is higher than the alpha risk (5%) meaning that the linearity condition is verified. Observed vs Predicted values # Plot Predicted values VS Real valuesdf['Predicted_sales'] = reg_multi.predict()X_plot = [df['sales'].min(), df['sales'].max()]ax = sns.scatterplot(x="sales", y="Predicted_sales", data=df)ax.set(xlabel='sales', ylabel='Predicted_sales')plt.plot(X_plot, X_plot, color='r')plt.show() ✅ If the linearity condition is verified, the points should be symmetrically distributed around a diagonal line with a roughly constant variance. Studentized residuals vs Fitted values Studentized residuals are more effective in detecting outliers, checking the linearity and in assessing the equal variance assumption than the standardized residuals. # Get the Studentized Residualstudent_residuals = pd.Series(np.abs(reg.get_influence().resid_studentized_internal))# Plot the Studentized Residualfig, ax = plt.subplots()ax.scatter(fitted, student_residuals, edgecolors = ‘k’)ax.set_ylabel(‘Studentized Residuals’)ax.set_xlabel(‘Fitted Values’)ax.set_title(‘Scale-Location’)plt.show() ✅ Ideally, all residuals should be small and unstructured (i.e not forming any clusters). It would mean that the regression analysis has been successful in explaining the essential part of the variation of the dependent variable. However, if residuals exhibit a structure or present any special aspect that does not seem random, it sheds a “bad light” on the regression. You can start your analysis of the residuals by verifying whether or not the residuals are normally distributed. Strictly speaking, non-normality of the residuals is an indication of an inadequate model. It means that the errors the model makes are not consistent across variables and observations (i.e. the errors are not random). There are many ways to execute that step, I’m personally a big fan of data visualization so I always start with these 2 plots to check the Normality assumption: # Plot residual Q-Q plotimport scipy as spfig, ax = plt.subplots(figsize=(6,2.5))_, (__, ___, r) = sp.stats.probplot(residuals, plot=ax, fit=True) Histogram of residuals distribution # Get Residualsresiduals = reg_multi.resid# Plot Histogram of the residualsplt.hist(residuals, density=True)plt.xlabel('Residuals')plt.title('Residuals Histogram')plt.show() ✅ If the residuals are normally distributed, we should see a bell-shaped histogram centred on 0 and with a variance of 1. Others parameters can be used to go deeper into the understanding: Omnibus is a test of the skewness and kurtosis of the residual. A high value indicates a skewed distribution whereas a low value (close to zero) would indicate a normal distribution The Prob (Omnibus) performs a statistical test indicating the probability that the residuals are normally distributed. We hope to see something close to 1. Omnibus 59Prob(Omnibus): 0.000 🚩 Here, the Prob(Omnibus) value = 0, indicating that the residuals are not normally distributed and Omnibus is high, indicating a skewness already detected visually on the histogram. These observations might be due to the influence of outliers. The Jarque-Bera statistic indicates whether or not the residuals are normally distributed. The null hypothesis for this test is that the residuals are normally distributed. When the p-value (probability) for this test is low (< 5%), the residuals are not normally distributed, indicating potentially model misspecification (i.e a key variable is missing from the model). Prob(JB): 1.47e-38 🚩 The JB statistic indicates that the residuals are not normally distributed. Again, it might be due to the influence of outliers. The skewness coefficient reflects the data symmetry which can indicate normalcy. We want to see something close to zero, indicating that the residual distribution is normal. Negative skew refers to a longer or fatter tail on the left side of the distribution, while positive skew refers to a longer or fatter tail on the right. Skew: -1.411 🚩 We can see clearly the skewness already detected in the histogram on the left side. A very skewed distribution is likely to have outliers in the direction of the skew. There are also a variety of statistical tests for normality, including the Kolmogorov-Smirnov test, the Shapiro-Wilk test and the Anderson-Darling test. All of these tests are relatively “picky”. Real data rarely has errors that are perfectly normally distributed, and it may not be possible to fit your data with a model whose errors do not violate the normality assumption at the 5% level of significance. It is usually better to focus more on violations of the other assumptions and/or the influence of outliers which may be mainly responsible for violations of normality anyway. The assumption of homoscedasticity is that the residuals are equals for all predicted dependent variables scores. In other words, it means that the variance around the regression line is the same for all values of the predictor variable (X). Violation of the homoscedasticity assumption results in heteroscedasticity when values of the dependent variable seem to increase or decrease as a function of the independent variables. Typically, homoscedasticity violations occur when one or more of the variables under investigation are not normally distributed. To check the homoscedasticity you can start with: Studentized residuals vs Fitted values We already use this plot before, in this case, we want to see the residual distributed symmetrically on a horizontal line. Breush-Pagan test This test measures how errors increase across the explanatory variable. import statsmodels.stats.api as smsfrom statsmodels.compat import lzipname = ['Lagrange multiplier statistic', 'p-value', 'f-value', 'f p-value']test = sms.het_breuschpagan(reg_multi.resid, reg_multi.model.exog)lzip(name, test)>> [('Lagrange multiplier statistic', 4.231064027368323), ('p-value', 0.12056912806125976), ('f-value', 2.131148563286781), ('f p-value', 0.12189895632865029)] ✅ If the test statistic has a p-value below the alpha risk (e.g. 0.05) then the null hypothesis of homoskedasticity is rejected and heteroskedasticity is assumed. In our case, we validate the assumption of homoscedasticity. There are many other ways to test the condition of heteroscedasticity, among the long list, I’d like to mention the White test, which is especially indicated for large dataset. Independence of residual is commonly referred to as the total absence of autocorrelation. Even though uncorrelated data does not necessarily imply independence, one can check if random variables are independent if their mutual information tends to 0. This assumption is especially dangerous in time-series models or longitudinal dataset, where serial correlation in the residuals implies that there is room for improvement in the model. This assumption is also important in the case of non-time-series models or cross-sectional dataset. If residuals always have the same sign under particular conditions, it means that the model systematically underpredicts/overpredicts what happens. To verify that condition, we can use ACF (autocorrelation function) plots and Durbin-Watson test. ACF plot We want to see if the value of ACF is significant for any lag. In our case, we are using non-time-series data so we can use the row number instead. In such cases, rows should be sorted in a way that (only) depends on the values of the feature(s). import statsmodels.tsa.api as smtacf = smt.graphics.plot_acf(reg_multi.resid, alpha=0.05) Durbin-Watson The test will output values between 0 and 4. Here are how to interpret the results of the test: — value = 2 means that there is no autocorrelation in the sample, — values < 2 indicate positive autocorrelation, — values > 2 negative autocorrelation. import statsmodels.stats.stattools as stst.durbin_watson(residuals, axis=0)>> 2.0772952352565546 ✅ We can reasonably consider the independence of the residuals. Last but not least, for multiple linear regression it’s a good idea to check for multicollinearity. Multicollinearity occurs when your model includes multiple factors that are correlated not just to your response variable, but also to each other. In other words, it results when you have factors that are a bit redundant. And you remember, a good model is a simple model. You can think of multicollinearity in terms of football games: If one player tackles the opposing quarterback, it’s easy to give credit for the sack where credit’s due. But if three players are tackling the quarterback simultaneously, it’s much more difficult to determine which of the three makes the biggest contribution to the sack. Multicollinearity makes some variables statistically insignificant when they should be significant. You can check the existence of collinearity between two or more variables with the Variance Inflation Factor (VIF). It’s a measure of colinearity among predictor variables within a multiple regression. We generally consider that a VIF of 5 or 10 and above (depends on the business problem) indicates a multicollinearity problem. from statsmodels.stats.outliers_influence import variance_inflation_factorfrom statsmodels.tools.tools import add_constant# For each X, calculate VIF and save in dataframedf.drop(['sales'],axis=1,inplace=True)X = add_constant(df)vif = pd.DataFrame()vif["VIF Factor"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]vif["features"] = X.columnsvif.round(1) #inspect results ✅ Here, we can see that we don’t have a multicollinearity problem. Apart from this, the correlation matrix of predictors may indicate the presence of multicollinearity. If not always, correlation matrix can be a good indicator of multicollinearity and highlight the need for further investigation. plt.subplots(figsize=(15,7))sns.heatmap(df.corr(), annot = True, cmap='coolwarm') sns.pairplot(data = df) Once you have run your linear regression model and get some significant results, you should check if the assumptions supporting the validity of the model are verified: The relationship between X (explanatory variable) and Y (the dependent variable) is linear. The residuals are normally distributed. The residuals have constant variance (i.e homoscedasticity) The residuals are independent. There is no multicollinearity. In this article, we use a dataset to predict sales based on advertising budgets. We consider that the conditions are fulfilled but (of course!) the model can be improved. In fact, we could work now on: - Assessing the impact of outliers and remove the biggest influencers;- Adding relevant explanatory variables- Transforming the explanatory variables (fx. with log): which can be relevant in our case as the relationship between X and Y looks pretty close to polynomial regression. This will be developed in my next article 😉 Finally, if you are facing a dataset where the conditions are not verified, here you can find some good tips on how to fix it: people.duke.edu Thanks for reading! If you like this article, make sure to hold the button clap to support my writing. You can also follow my work on Twitter and Linkedin.
[ { "code": null, "e": 577, "s": 171, "text": "Beyond the sarcasm of this quote, there is a reality: of all the statistical techniques, regression analysis is often referred to as one of the most significant in business analysis. Most companies use regression analysis to explain a particular phenomenon, build forecasting or to make predictions. These new insights can be extremely valuable in understanding what can make a difference in the business." }, { "code": null, "e": 1125, "s": 577, "text": "When you work as a Data Scientist, building a linear regression model can sound pretty dull especially when it’s all about AI around you. However, I want to stress that mastering the main assumptions of linear regression models is much more elaborated than it looks and requires some solid foundation in Statistics. Another thing is that linear regression models are part of the same family of algorithms a.k.a Generalised Linear Models (GLM). GLM is an important topic for Data Scientist because they fit a broad variety of real-world phenomenon." }, { "code": null, "e": 1272, "s": 1125, "text": "Maybe that’s why in November 2017, Jame Le ranked linear regression models in the top 10 of Statistical Techniques Data Scientists Need to Master." }, { "code": null, "e": 1373, "s": 1272, "text": "Now that it’s clear why we should care about the Linear Regression Model, let’s get our hands on it." }, { "code": null, "e": 1510, "s": 1373, "text": "You ran a linear regression analysis and the results were significant (or not). You might think that you’re done. No, not yet my friend." }, { "code": null, "e": 1827, "s": 1510, "text": "After running the regression analysis, you should check if the model performed well for data. Maybe you start with regression results, such as slope coefficients, p-values, or R-squared. These parameters can give you a first glimpse on how well a model represents given data. But that’s not the whole picture though." }, { "code": null, "e": 1934, "s": 1827, "text": "In this post, I’ll walk you through how to check the main assumptions supporting linear regression models." }, { "code": null, "e": 1966, "s": 1934, "text": "But wait! First things first..." }, { "code": null, "e": 2093, "s": 1966, "text": "There are four principal assumptions which support using a linear regression model for the purpose of inference or prediction:" }, { "code": null, "e": 2258, "s": 2093, "text": "Linearity: Sounds obvious! We must have a linear relationship between our features and responses. This is required for our estimator and predictions to be unbiased." }, { "code": null, "e": 2423, "s": 2258, "text": "Linearity: Sounds obvious! We must have a linear relationship between our features and responses. This is required for our estimator and predictions to be unbiased." }, { "code": null, "e": 2466, "s": 2423, "text": "The next ones are concerning the residual:" }, { "code": null, "e": 2719, "s": 2466, "text": "2. Normality: Residuals must be Normally distributed (i.e variance tend to 1 and mean tend to zero). This is necessary for a range of statistical tests, such as the t-test. We can relax this assumption in large samples due to the central limit theorem." }, { "code": null, "e": 2835, "s": 2719, "text": "3. Homoscedasticity: Means that the residuals have constant variance no matter the level of the dependent variable." }, { "code": null, "e": 2902, "s": 2835, "text": "4. Independence:Residuals must be totally free of autocorrelation." }, { "code": null, "e": 2958, "s": 2902, "text": "For multiple linear regression, you also need to check:" }, { "code": null, "e": 3170, "s": 2958, "text": "5. the Absence of multicollinearity: Multicollinearity refers to when two predictors (or more) are providing the same information about the response variable. This can be a problem for the model as it generates:" }, { "code": null, "e": 3267, "s": 3170, "text": "Redundancy → leading to unreliable coefficients of the predictors (especially for linear models)" }, { "code": null, "e": 3431, "s": 3267, "text": "High variance of the estimator → tends to overfit meaning that the algorithm tends to model the random noise in the training data, rather than the intended output." }, { "code": null, "e": 3478, "s": 3431, "text": "An important predictor can become unimportant." }, { "code": null, "e": 3776, "s": 3478, "text": "To illustrate this article, we are gonna try to predict the sales of a company using 3 predictors: budget invested on Youtube ads, budget invested on Facebook ads and budget invested on Newspaper ads. All variables are expressed in thousands of US dollars. The dataset used can be found in Kaggle." }, { "code": null, "e": 3787, "s": 3776, "text": "df.head(7)" }, { "code": null, "e": 4082, "s": 3787, "text": "For this article, I choose to use StatsModel over Scikit-learn. Despite the fact that StatsModel doesn’t have the variety of options that Scikit-learn offers, it provides statistics and econometric tools that are top of the line and validated against other statistics software like Stata and R." }, { "code": null, "e": 4150, "s": 4082, "text": "🚩 Here you can find an interesting article about these 2 libraries:" }, { "code": null, "e": 4176, "s": 4150, "text": "blog.thedataincubator.com" }, { "code": null, "e": 4195, "s": 4176, "text": "Let’s get started!" }, { "code": null, "e": 4316, "s": 4195, "text": "import statsmodels.formula.api as smfreg = smf.ols(‘sales~youtube+facebook+newspaper’,data=df).fit()print(reg.summary())" }, { "code": null, "e": 4500, "s": 4316, "text": "✅ If we check the “basics” parameters, here is what we can see:- R-squared is quite high - Prob (F-statistic) is very low- p-value < alpha risk (5%) except for the predictor newspaper" }, { "code": null, "e": 4723, "s": 4500, "text": "R-squared: In case you forgot or didn’t know, R-squared and Adjusted R-squared are statistics that often accompanies regression output. They are both supposed to assess the model performance with values ranges from 0 to 1." }, { "code": null, "e": 4814, "s": 4723, "text": "Generally, you choose the models that have higher adjusted and predicted R-squared values." }, { "code": null, "e": 4915, "s": 4814, "text": "Now, I have this question for you: Who is checking the goodness of fit of the model with R- squared?" }, { "code": null, "e": 4935, "s": 4915, "text": "Content Unavailable" }, { "code": null, "e": 4990, "s": 4935, "text": "Sorry, this content is not available in your location." }, { "code": null, "e": 5016, "s": 4990, "text": "I do. Or at least, I did." }, { "code": null, "e": 5241, "s": 5016, "text": "Until I read a few articles on the topic, showing that R-squared does NOT measure the goodness of fit because it can be:- Arbitrarily low even when the model is correct, - Dangerously close to 1 even when the model is wrong." }, { "code": null, "e": 5355, "s": 5241, "text": "I’m not gonna develop further into this article how come it’s possible but you can find some very good info here:" }, { "code": null, "e": 5375, "s": 5355, "text": "statisticsbyjim.com" }, { "code": null, "e": 5401, "s": 5375, "text": "data.library.virginia.edu" }, { "code": null, "e": 5646, "s": 5401, "text": "So, based on the 3 parameters above, you could think that your regression model is quite good to predict the sales based on the advertising budget. Then you might want to remove the newspaper predictor as it seems not significant for the model." }, { "code": null, "e": 5711, "s": 5646, "text": "Of course, it would be terribly wrong to stop our analysis here." }, { "code": null, "e": 5946, "s": 5711, "text": "First and foremost, because you shouldn't follow blindly what R-squared says. Then, because we don’t know if the 5 key assumptions are verified. So we basically don’t know if we are in the spectrum where this model is performing well." }, { "code": null, "e": 6025, "s": 5946, "text": "It is time for me, to walk you through each assumption and how to verify them." }, { "code": null, "e": 6273, "s": 6025, "text": "If you try to fit a linear model to data which are nonlinearly or nonadditive, your predictions are likely to be seriously in error, especially when you extrapolate beyond the range of the sample data. To confirm the linearity, we can for example:" }, { "code": null, "e": 6315, "s": 6273, "text": "Apply the Harvey-Collier multiplier test." }, { "code": null, "e": 6464, "s": 6315, "text": "import statsmodels.stats.api as smssms.linear_harvey_collier(reg_multi)>> Ttest_1sampResult(statistic=-1.565945529686271, pvalue=0.1192542929871369)" }, { "code": null, "e": 6628, "s": 6464, "text": "✅ Small p-value shows that there is a violation of linearity. Here the p-value is higher than the alpha risk (5%) meaning that the linearity condition is verified." }, { "code": null, "e": 6657, "s": 6628, "text": "Observed vs Predicted values" }, { "code": null, "e": 6940, "s": 6657, "text": "# Plot Predicted values VS Real valuesdf['Predicted_sales'] = reg_multi.predict()X_plot = [df['sales'].min(), df['sales'].max()]ax = sns.scatterplot(x=\"sales\", y=\"Predicted_sales\", data=df)ax.set(xlabel='sales', ylabel='Predicted_sales')plt.plot(X_plot, X_plot, color='r')plt.show()" }, { "code": null, "e": 7086, "s": 6940, "text": "✅ If the linearity condition is verified, the points should be symmetrically distributed around a diagonal line with a roughly constant variance." }, { "code": null, "e": 7125, "s": 7086, "text": "Studentized residuals vs Fitted values" }, { "code": null, "e": 7292, "s": 7125, "text": "Studentized residuals are more effective in detecting outliers, checking the linearity and in assessing the equal variance assumption than the standardized residuals." }, { "code": null, "e": 7626, "s": 7292, "text": "# Get the Studentized Residualstudent_residuals = pd.Series(np.abs(reg.get_influence().resid_studentized_internal))# Plot the Studentized Residualfig, ax = plt.subplots()ax.scatter(fitted, student_residuals, edgecolors = ‘k’)ax.set_ylabel(‘Studentized Residuals’)ax.set_xlabel(‘Fitted Values’)ax.set_title(‘Scale-Location’)plt.show()" }, { "code": null, "e": 7997, "s": 7626, "text": "✅ Ideally, all residuals should be small and unstructured (i.e not forming any clusters). It would mean that the regression analysis has been successful in explaining the essential part of the variation of the dependent variable. However, if residuals exhibit a structure or present any special aspect that does not seem random, it sheds a “bad light” on the regression." }, { "code": null, "e": 8329, "s": 7997, "text": "You can start your analysis of the residuals by verifying whether or not the residuals are normally distributed. Strictly speaking, non-normality of the residuals is an indication of an inadequate model. It means that the errors the model makes are not consistent across variables and observations (i.e. the errors are not random)." }, { "code": null, "e": 8490, "s": 8329, "text": "There are many ways to execute that step, I’m personally a big fan of data visualization so I always start with these 2 plots to check the Normality assumption:" }, { "code": null, "e": 8637, "s": 8490, "text": "# Plot residual Q-Q plotimport scipy as spfig, ax = plt.subplots(figsize=(6,2.5))_, (__, ___, r) = sp.stats.probplot(residuals, plot=ax, fit=True)" }, { "code": null, "e": 8673, "s": 8637, "text": "Histogram of residuals distribution" }, { "code": null, "e": 8847, "s": 8673, "text": "# Get Residualsresiduals = reg_multi.resid# Plot Histogram of the residualsplt.hist(residuals, density=True)plt.xlabel('Residuals')plt.title('Residuals Histogram')plt.show()" }, { "code": null, "e": 8969, "s": 8847, "text": "✅ If the residuals are normally distributed, we should see a bell-shaped histogram centred on 0 and with a variance of 1." }, { "code": null, "e": 9036, "s": 8969, "text": "Others parameters can be used to go deeper into the understanding:" }, { "code": null, "e": 9218, "s": 9036, "text": "Omnibus is a test of the skewness and kurtosis of the residual. A high value indicates a skewed distribution whereas a low value (close to zero) would indicate a normal distribution" }, { "code": null, "e": 9374, "s": 9218, "text": "The Prob (Omnibus) performs a statistical test indicating the probability that the residuals are normally distributed. We hope to see something close to 1." }, { "code": null, "e": 9446, "s": 9374, "text": "Omnibus 59Prob(Omnibus): 0.000" }, { "code": null, "e": 9691, "s": 9446, "text": "🚩 Here, the Prob(Omnibus) value = 0, indicating that the residuals are not normally distributed and Omnibus is high, indicating a skewness already detected visually on the histogram. These observations might be due to the influence of outliers." }, { "code": null, "e": 10062, "s": 9691, "text": "The Jarque-Bera statistic indicates whether or not the residuals are normally distributed. The null hypothesis for this test is that the residuals are normally distributed. When the p-value (probability) for this test is low (< 5%), the residuals are not normally distributed, indicating potentially model misspecification (i.e a key variable is missing from the model)." }, { "code": null, "e": 10101, "s": 10062, "text": "Prob(JB): 1.47e-38" }, { "code": null, "e": 10232, "s": 10101, "text": "🚩 The JB statistic indicates that the residuals are not normally distributed. Again, it might be due to the influence of outliers." }, { "code": null, "e": 10560, "s": 10232, "text": "The skewness coefficient reflects the data symmetry which can indicate normalcy. We want to see something close to zero, indicating that the residual distribution is normal. Negative skew refers to a longer or fatter tail on the left side of the distribution, while positive skew refers to a longer or fatter tail on the right." }, { "code": null, "e": 10598, "s": 10560, "text": "Skew: -1.411" }, { "code": null, "e": 10768, "s": 10598, "text": "🚩 We can see clearly the skewness already detected in the histogram on the left side. A very skewed distribution is likely to have outliers in the direction of the skew." }, { "code": null, "e": 11176, "s": 10768, "text": "There are also a variety of statistical tests for normality, including the Kolmogorov-Smirnov test, the Shapiro-Wilk test and the Anderson-Darling test. All of these tests are relatively “picky”. Real data rarely has errors that are perfectly normally distributed, and it may not be possible to fit your data with a model whose errors do not violate the normality assumption at the 5% level of significance." }, { "code": null, "e": 11351, "s": 11176, "text": "It is usually better to focus more on violations of the other assumptions and/or the influence of outliers which may be mainly responsible for violations of normality anyway." }, { "code": null, "e": 11593, "s": 11351, "text": "The assumption of homoscedasticity is that the residuals are equals for all predicted dependent variables scores. In other words, it means that the variance around the regression line is the same for all values of the predictor variable (X)." }, { "code": null, "e": 11779, "s": 11593, "text": "Violation of the homoscedasticity assumption results in heteroscedasticity when values of the dependent variable seem to increase or decrease as a function of the independent variables." }, { "code": null, "e": 11958, "s": 11779, "text": "Typically, homoscedasticity violations occur when one or more of the variables under investigation are not normally distributed. To check the homoscedasticity you can start with:" }, { "code": null, "e": 11997, "s": 11958, "text": "Studentized residuals vs Fitted values" }, { "code": null, "e": 12120, "s": 11997, "text": "We already use this plot before, in this case, we want to see the residual distributed symmetrically on a horizontal line." }, { "code": null, "e": 12138, "s": 12120, "text": "Breush-Pagan test" }, { "code": null, "e": 12210, "s": 12138, "text": "This test measures how errors increase across the explanatory variable." }, { "code": null, "e": 12604, "s": 12210, "text": "import statsmodels.stats.api as smsfrom statsmodels.compat import lzipname = ['Lagrange multiplier statistic', 'p-value', 'f-value', 'f p-value']test = sms.het_breuschpagan(reg_multi.resid, reg_multi.model.exog)lzip(name, test)>> [('Lagrange multiplier statistic', 4.231064027368323), ('p-value', 0.12056912806125976), ('f-value', 2.131148563286781), ('f p-value', 0.12189895632865029)]" }, { "code": null, "e": 12828, "s": 12604, "text": "✅ If the test statistic has a p-value below the alpha risk (e.g. 0.05) then the null hypothesis of homoskedasticity is rejected and heteroskedasticity is assumed. In our case, we validate the assumption of homoscedasticity." }, { "code": null, "e": 13005, "s": 12828, "text": "There are many other ways to test the condition of heteroscedasticity, among the long list, I’d like to mention the White test, which is especially indicated for large dataset." }, { "code": null, "e": 13256, "s": 13005, "text": "Independence of residual is commonly referred to as the total absence of autocorrelation. Even though uncorrelated data does not necessarily imply independence, one can check if random variables are independent if their mutual information tends to 0." }, { "code": null, "e": 13442, "s": 13256, "text": "This assumption is especially dangerous in time-series models or longitudinal dataset, where serial correlation in the residuals implies that there is room for improvement in the model." }, { "code": null, "e": 13690, "s": 13442, "text": "This assumption is also important in the case of non-time-series models or cross-sectional dataset. If residuals always have the same sign under particular conditions, it means that the model systematically underpredicts/overpredicts what happens." }, { "code": null, "e": 13788, "s": 13690, "text": "To verify that condition, we can use ACF (autocorrelation function) plots and Durbin-Watson test." }, { "code": null, "e": 13797, "s": 13788, "text": "ACF plot" }, { "code": null, "e": 14044, "s": 13797, "text": "We want to see if the value of ACF is significant for any lag. In our case, we are using non-time-series data so we can use the row number instead. In such cases, rows should be sorted in a way that (only) depends on the values of the feature(s)." }, { "code": null, "e": 14134, "s": 14044, "text": "import statsmodels.tsa.api as smtacf = smt.graphics.plot_acf(reg_multi.resid, alpha=0.05)" }, { "code": null, "e": 14148, "s": 14134, "text": "Durbin-Watson" }, { "code": null, "e": 14398, "s": 14148, "text": "The test will output values between 0 and 4. Here are how to interpret the results of the test: — value = 2 means that there is no autocorrelation in the sample, — values < 2 indicate positive autocorrelation, — values > 2 negative autocorrelation." }, { "code": null, "e": 14495, "s": 14398, "text": "import statsmodels.stats.stattools as stst.durbin_watson(residuals, axis=0)>> 2.0772952352565546" }, { "code": null, "e": 14559, "s": 14495, "text": "✅ We can reasonably consider the independence of the residuals." }, { "code": null, "e": 14881, "s": 14559, "text": "Last but not least, for multiple linear regression it’s a good idea to check for multicollinearity. Multicollinearity occurs when your model includes multiple factors that are correlated not just to your response variable, but also to each other. In other words, it results when you have factors that are a bit redundant." }, { "code": null, "e": 14931, "s": 14881, "text": "And you remember, a good model is a simple model." }, { "code": null, "e": 14994, "s": 14931, "text": "You can think of multicollinearity in terms of football games:" }, { "code": null, "e": 15267, "s": 14994, "text": "If one player tackles the opposing quarterback, it’s easy to give credit for the sack where credit’s due. But if three players are tackling the quarterback simultaneously, it’s much more difficult to determine which of the three makes the biggest contribution to the sack." }, { "code": null, "e": 15367, "s": 15267, "text": "Multicollinearity makes some variables statistically insignificant when they should be significant." }, { "code": null, "e": 15569, "s": 15367, "text": "You can check the existence of collinearity between two or more variables with the Variance Inflation Factor (VIF). It’s a measure of colinearity among predictor variables within a multiple regression." }, { "code": null, "e": 15696, "s": 15569, "text": "We generally consider that a VIF of 5 or 10 and above (depends on the business problem) indicates a multicollinearity problem." }, { "code": null, "e": 16089, "s": 15696, "text": "from statsmodels.stats.outliers_influence import variance_inflation_factorfrom statsmodels.tools.tools import add_constant# For each X, calculate VIF and save in dataframedf.drop(['sales'],axis=1,inplace=True)X = add_constant(df)vif = pd.DataFrame()vif[\"VIF Factor\"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]vif[\"features\"] = X.columnsvif.round(1) #inspect results" }, { "code": null, "e": 16156, "s": 16089, "text": "✅ Here, we can see that we don’t have a multicollinearity problem." }, { "code": null, "e": 16387, "s": 16156, "text": "Apart from this, the correlation matrix of predictors may indicate the presence of multicollinearity. If not always, correlation matrix can be a good indicator of multicollinearity and highlight the need for further investigation." }, { "code": null, "e": 16469, "s": 16387, "text": "plt.subplots(figsize=(15,7))sns.heatmap(df.corr(), annot = True, cmap='coolwarm')" }, { "code": null, "e": 16493, "s": 16469, "text": "sns.pairplot(data = df)" }, { "code": null, "e": 16661, "s": 16493, "text": "Once you have run your linear regression model and get some significant results, you should check if the assumptions supporting the validity of the model are verified:" }, { "code": null, "e": 16753, "s": 16661, "text": "The relationship between X (explanatory variable) and Y (the dependent variable) is linear." }, { "code": null, "e": 16793, "s": 16753, "text": "The residuals are normally distributed." }, { "code": null, "e": 16853, "s": 16793, "text": "The residuals have constant variance (i.e homoscedasticity)" }, { "code": null, "e": 16884, "s": 16853, "text": "The residuals are independent." }, { "code": null, "e": 16915, "s": 16884, "text": "There is no multicollinearity." }, { "code": null, "e": 17086, "s": 16915, "text": "In this article, we use a dataset to predict sales based on advertising budgets. We consider that the conditions are fulfilled but (of course!) the model can be improved." }, { "code": null, "e": 17398, "s": 17086, "text": "In fact, we could work now on: - Assessing the impact of outliers and remove the biggest influencers;- Adding relevant explanatory variables- Transforming the explanatory variables (fx. with log): which can be relevant in our case as the relationship between X and Y looks pretty close to polynomial regression." }, { "code": null, "e": 17442, "s": 17398, "text": "This will be developed in my next article 😉" }, { "code": null, "e": 17569, "s": 17442, "text": "Finally, if you are facing a dataset where the conditions are not verified, here you can find some good tips on how to fix it:" }, { "code": null, "e": 17585, "s": 17569, "text": "people.duke.edu" } ]
Difference between singleton and prototype bean scope.
Spring framework supports five types of bean scope − Singleton Singleton Prototype Prototype Request Request Session Session Global Session Global Session As per the spring documentation − Singleton − It returns a single bean instance per Spring IoC container. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object. Spring singleton is different than Java singleton. In java, one instance of the bean is created per JVM whereas in spring, one instance of the bean is created per application context. Proptype − As per the spring documentation − Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. <bean id="xyzService" class="com.xyz.XyzService" scope="singleton"/> <bean id="xyzService" class="com.xyz.XyzService" scope="prototype"/>
[ { "code": null, "e": 1115, "s": 1062, "text": "Spring framework supports five types of bean scope −" }, { "code": null, "e": 1125, "s": 1115, "text": "Singleton" }, { "code": null, "e": 1135, "s": 1125, "text": "Singleton" }, { "code": null, "e": 1145, "s": 1135, "text": "Prototype" }, { "code": null, "e": 1155, "s": 1145, "text": "Prototype" }, { "code": null, "e": 1163, "s": 1155, "text": "Request" }, { "code": null, "e": 1171, "s": 1163, "text": "Request" }, { "code": null, "e": 1179, "s": 1171, "text": "Session" }, { "code": null, "e": 1187, "s": 1179, "text": "Session" }, { "code": null, "e": 1202, "s": 1187, "text": "Global Session" }, { "code": null, "e": 1217, "s": 1202, "text": "Global Session" }, { "code": null, "e": 1251, "s": 1217, "text": "As per the spring documentation −" }, { "code": null, "e": 1479, "s": 1251, "text": "Singleton − It returns a single bean instance per Spring IoC container. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object." }, { "code": null, "e": 1663, "s": 1479, "text": "Spring singleton is different than Java singleton. In java, one instance of the bean is created per JVM whereas in spring, one instance of the bean is created per application context." }, { "code": null, "e": 1674, "s": 1663, "text": "Proptype −" }, { "code": null, "e": 1708, "s": 1674, "text": "As per the spring documentation −" }, { "code": null, "e": 2255, "s": 1708, "text": "Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding." }, { "code": null, "e": 2394, "s": 2255, "text": "<bean id=\"xyzService\" class=\"com.xyz.XyzService\" scope=\"singleton\"/>\n\n<bean id=\"xyzService\" class=\"com.xyz.XyzService\" scope=\"prototype\"/>" } ]
HTML | DOM Input Checkbox value Property - GeeksforGeeks
11 Mar, 2019 The Input Checkbox Value property in HTML DOM is used to set or return the value of the value attribute of an input checkbox field, however the contents of the value attribute does not shown to user. When the form is submitted by the user, the value and the other information sent to the server. But when the checkbox is an unchecked state, therefore, no information will be sent. Syntax: It returns the Input Checkbox value property.checkboxObject.value checkboxObject.value It is used to set the Input Checkbox value property.checkboxObject.value = text checkboxObject.value = text Property Values: It contains single value text which is used to specify the value associated with the input checkbox field. Return Value: It returns a string value which represent the value of the value attribute of a input checkbox field. Example 1: This example returns the Input Checkbox value property. <!DOCTYPE html><html> <head> <title> DOM Input Checkbox value Property </title> </head> <body style = "text-align: center;"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2>DOM Input Checkbox value Property</h2> <form > <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" checked>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form> <br> <button onclick="myGeeks()"> Submit </button> <p id="sudo" style="color:green;font-size:30px;"></p> <!-- script to return Input Checkbox value Property --> <script> function myGeeks() { var g = document.getElementById("GFG").value; document.getElementById("sudo").innerHTML = g; } </script> </body> </html> Output:Before clicking on the Button:After clicking on the Button: Example 2: This example sets the Input Checkbox value property. <!DOCTYPE html> <html> <head> <title> DOM Input Checkbox value Property </title> </head> <body style = "text-align: center;"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2>DOM Input Checkbox value Property</h2> <form > <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" checked>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form> <br> <button onclick="myGeeks()"> Submit </button> <p id="sudo" style="color:green;font-size:20px;"></p> <!-- Script to set Input Checkbox value Property --> <script> function myGeeks() { var g = document.getElementById("GFG").value ="Geeks"; document.getElementById("sudo").innerHTML = "The value of the value attribute" + " was change to " + g; } </script> </body> </html> Output:Before clicking on the Button:After clicking on the Button: Supported Browsers: The browser supported by DOM Input Checkbox value property are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? Form validation using HTML and JavaScript Types of CSS (Cascading Style Sheet) HTML Introduction REST API (Introduction) Express.js express.Router() Function Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React
[ { "code": null, "e": 24438, "s": 24410, "text": "\n11 Mar, 2019" }, { "code": null, "e": 24819, "s": 24438, "text": "The Input Checkbox Value property in HTML DOM is used to set or return the value of the value attribute of an input checkbox field, however the contents of the value attribute does not shown to user. When the form is submitted by the user, the value and the other information sent to the server. But when the checkbox is an unchecked state, therefore, no information will be sent." }, { "code": null, "e": 24827, "s": 24819, "text": "Syntax:" }, { "code": null, "e": 24893, "s": 24827, "text": "It returns the Input Checkbox value property.checkboxObject.value" }, { "code": null, "e": 24914, "s": 24893, "text": "checkboxObject.value" }, { "code": null, "e": 24994, "s": 24914, "text": "It is used to set the Input Checkbox value property.checkboxObject.value = text" }, { "code": null, "e": 25022, "s": 24994, "text": "checkboxObject.value = text" }, { "code": null, "e": 25146, "s": 25022, "text": "Property Values: It contains single value text which is used to specify the value associated with the input checkbox field." }, { "code": null, "e": 25262, "s": 25146, "text": "Return Value: It returns a string value which represent the value of the value attribute of a input checkbox field." }, { "code": null, "e": 25329, "s": 25262, "text": "Example 1: This example returns the Input Checkbox value property." }, { "code": "<!DOCTYPE html><html> <head> <title> DOM Input Checkbox value Property </title> </head> <body style = \"text-align: center;\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2>DOM Input Checkbox value Property</h2> <form > <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" checked>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form> <br> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"sudo\" style=\"color:green;font-size:30px;\"></p> <!-- script to return Input Checkbox value Property --> <script> function myGeeks() { var g = document.getElementById(\"GFG\").value; document.getElementById(\"sudo\").innerHTML = g; } </script> </body> </html> ", "e": 26462, "s": 25329, "text": null }, { "code": null, "e": 26529, "s": 26462, "text": "Output:Before clicking on the Button:After clicking on the Button:" }, { "code": null, "e": 26593, "s": 26529, "text": "Example 2: This example sets the Input Checkbox value property." }, { "code": "<!DOCTYPE html> <html> <head> <title> DOM Input Checkbox value Property </title> </head> <body style = \"text-align: center;\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2>DOM Input Checkbox value Property</h2> <form > <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" checked>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form> <br> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"sudo\" style=\"color:green;font-size:20px;\"></p> <!-- Script to set Input Checkbox value Property --> <script> function myGeeks() { var g = document.getElementById(\"GFG\").value =\"Geeks\"; document.getElementById(\"sudo\").innerHTML = \"The value of the value attribute\" + \" was change to \" + g; } </script> </body> </html> ", "e": 27910, "s": 26593, "text": null }, { "code": null, "e": 27977, "s": 27910, "text": "Output:Before clicking on the Button:After clicking on the Button:" }, { "code": null, "e": 28074, "s": 27977, "text": "Supported Browsers: The browser supported by DOM Input Checkbox value property are listed below:" }, { "code": null, "e": 28088, "s": 28074, "text": "Google Chrome" }, { "code": null, "e": 28106, "s": 28088, "text": "Internet Explorer" }, { "code": null, "e": 28114, "s": 28106, "text": "Firefox" }, { "code": null, "e": 28120, "s": 28114, "text": "Opera" }, { "code": null, "e": 28127, "s": 28120, "text": "Safari" }, { "code": null, "e": 28264, "s": 28127, "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": 28273, "s": 28264, "text": "HTML-DOM" }, { "code": null, "e": 28278, "s": 28273, "text": "HTML" }, { "code": null, "e": 28295, "s": 28278, "text": "Web Technologies" }, { "code": null, "e": 28300, "s": 28295, "text": "HTML" }, { "code": null, "e": 28398, "s": 28300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28407, "s": 28398, "text": "Comments" }, { "code": null, "e": 28420, "s": 28407, "text": "Old Comments" }, { "code": null, "e": 28470, "s": 28420, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28512, "s": 28470, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 28549, "s": 28512, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28567, "s": 28549, "text": "HTML Introduction" }, { "code": null, "e": 28591, "s": 28567, "text": "REST API (Introduction)" }, { "code": null, "e": 28628, "s": 28591, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28661, "s": 28628, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28704, "s": 28661, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28765, "s": 28704, "text": "Difference between var, let and const keywords in JavaScript" } ]
Dimensionality Reduction using t-Distributed Stochastic Neighbor Embedding (t-SNE) on the MNIST Dataset | by Dehao Zhang | Towards Data Science
It is easy for us to visualize two or three dimensional data, but once it goes beyond three dimensions, it becomes much harder to see what high dimensional data looks like. Today we are often in a situation that we need to analyze and find patterns on datasets with thousands or even millions of dimensions, which makes visualization a bit of a challenge. However, a tool that can definitely help us better understand the data is dimensionality reduction. In this post, I will discuss t-SNE, a popular non-linear dimensionality reduction technique and how to implement it in Python using sklearn. The dataset I have chosen here is the popular MNIST dataset. What is t-SNE and how does it work?How is t-SNE different with PCA?How can we improve upon t-SNE?What are the limitations?What can we do next? What is t-SNE and how does it work? How is t-SNE different with PCA? How can we improve upon t-SNE? What are the limitations? What can we do next? T-Distributed Stochastic Neighbor Embedding, or t-SNE, is a machine learning algorithm and it is often used to embedding high dimensional data in a low dimensional space [1]. In simple terms, the approach of t-SNE can be broken down into two steps. The first step is to represent the high dimensional data by constructing a probability distribution P, where the probability of similar points being picked is high, whereas the probability of dissimilar points being picked is low. The second step is to create a low dimensional space with another probability distribution Q that preserves the property of P as close as possible. In step 1, we compute the similarity between two data points using a conditional probability p. For example, the conditional probability of j given i represents that x_j would be picked by x_i as its neighbor assuming neighbors are picked in proportion to their probability density under a Gaussian distribution centered at x_i [1]. In step 2, we let y_i and y_j to be the low dimensional counterparts of x_i and x_j, respectively. Then we consider q to be a similar conditional probability for y_j being picked by y_i and we employ a student t-distribution in the low dimension map. The locations of the low dimensional data points are determined by minimizing the Kullback–Leibler divergence of probability distribution P from Q. For more technical details of t-SNE, check out this paper. I have chosen the MNIST dataset from Kaggle (link) as the example here because it is a simple computer vision dataset, with 28x28 pixel images of handwritten digits (0–9). We can think of each instance as a data point embedded in a 784-dimensional space. To see the full Python code, check out my Kaggle kernel. Without further ado, let’s get to the details! Note that in the original Kaggle competition, the goal is to build a ML model using the training images with true labels that can accurately predict the labels on the test set. For our purposes here we will only use the training set. As usual, we check its shape first: train.shape--------------------------------------------------------------------(42000, 785) There are 42K training instances. The 785 columns are the 784 pixel values, as well as the ‘label’ column. We can check the label distribution as well: label = train["label"]label.value_counts()--------------------------------------------------------------------1 46847 44013 43519 41882 41776 41370 41324 40728 40635 3795Name: label, dtype: int64 Principal Component Analysis (PCA) Before we implement t-SNE, let’s try PCA, a popular linear method for dimensionality reduction. After we standardize the data, we can transform our data using PCA (specify ‘n_components’ to be 2): from sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAtrain = StandardScaler().fit_transform(train)pca = PCA(n_components=2)pca_res = pca.fit_transform(train) Let’s make a scatter plot to visualize the result: sns.scatterplot(x = pca_res[:,0], y = pca_res[:,1], hue = label, palette = sns.hls_palette(10), legend = 'full'); As shown in the scatter plot, PCA with two components does not sufficiently provide meaningful insights and patterns about the different labels. We know one drawback of PCA is that the linear projection can’t capture non-linear dependencies. Let’s try t-SNE now. T-SNE with sklearn We will implement t-SNE using sklearn.manifold (documentation): from sklearn.manifold import TSNEtsne = TSNE(n_components = 2, random_state=0)tsne_res = tsne.fit_transform(train)sns.scatterplot(x = tsne_res[:,0], y = tsne_res[:,1], hue = label, palette = sns.hls_palette(10), legend = 'full'); Now we can see that the different clusters are more separable compared with the result from PCA. Here are a few observations on this plot: The “5” data points seem to be more spread out compared with the other clusters such as “2” and “4”.There are a few “5” and “8” data points that are similar to “3”s.There are two clusters of “7” and “9” where they are next to each other. The “5” data points seem to be more spread out compared with the other clusters such as “2” and “4”. There are a few “5” and “8” data points that are similar to “3”s. There are two clusters of “7” and “9” where they are next to each other. An Approach that Combines Both It is generally recommended to use PCA or TruncatedSVD to reduce the number of dimension to a reasonable amount (e.g. 50) before applying t-SNE [2]. Doing so can reduce the level of noise as well as speed up the computations. Let’s try PCA (50 components) first and then apply t-SNE. Here is the scatter plot: Compared with the previous scatter plot, wecan now separate out the 10 clusters better. here are a few observations: Most of the “5” data points are not as spread out as before, despite a few that still look like “3”.There is one cluster of “7” and one cluster of “9” now. Most of the “5” data points are not as spread out as before, despite a few that still look like “3”. There is one cluster of “7” and one cluster of “9” now. Besides, the runtime in this approach decreased by over 60%. For more interactive 3D scatter plots, check out this post. Here are a few limitations of t-SNE: Unlike PCA, the cost function of t-SNE is non-convex, meaning there is a possibility that we would be stuck in a local minima.Similar to other dimensionality reduction techniques, the meaning of the compressed dimensions as well as the transformed features becomes less interpretable. Unlike PCA, the cost function of t-SNE is non-convex, meaning there is a possibility that we would be stuck in a local minima. Similar to other dimensionality reduction techniques, the meaning of the compressed dimensions as well as the transformed features becomes less interpretable. Here are a few things that we can try as next steps: Hyperparameter tuning — Try tune ‘perplexity’ and see its effect on the visualized output.Try some of the other non-linear techniques such as Uniform Manifold Approximation and Projection (UMAP), which is the generalization of t-SNE and it is based on Riemannian geometry.Train ML models on the transformed data and compare its performance with those from models without dimensionality reduction. Hyperparameter tuning — Try tune ‘perplexity’ and see its effect on the visualized output. Try some of the other non-linear techniques such as Uniform Manifold Approximation and Projection (UMAP), which is the generalization of t-SNE and it is based on Riemannian geometry. Train ML models on the transformed data and compare its performance with those from models without dimensionality reduction. Let’s quickly recap. We implemented t-SNE using sklearn on the MNIST dataset. We compared the visualized output with that from using PCA, and lastly, we tried a mixed approach which applies PCA first and then t-SNE. I hope you enjoyed this blog post and please share any thoughts that you may have :) Check out my other post on Chi-square test for independence: towardsdatascience.com [1] https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding[2] https://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html
[ { "code": null, "e": 345, "s": 172, "text": "It is easy for us to visualize two or three dimensional data, but once it goes beyond three dimensions, it becomes much harder to see what high dimensional data looks like." }, { "code": null, "e": 628, "s": 345, "text": "Today we are often in a situation that we need to analyze and find patterns on datasets with thousands or even millions of dimensions, which makes visualization a bit of a challenge. However, a tool that can definitely help us better understand the data is dimensionality reduction." }, { "code": null, "e": 830, "s": 628, "text": "In this post, I will discuss t-SNE, a popular non-linear dimensionality reduction technique and how to implement it in Python using sklearn. The dataset I have chosen here is the popular MNIST dataset." }, { "code": null, "e": 973, "s": 830, "text": "What is t-SNE and how does it work?How is t-SNE different with PCA?How can we improve upon t-SNE?What are the limitations?What can we do next?" }, { "code": null, "e": 1009, "s": 973, "text": "What is t-SNE and how does it work?" }, { "code": null, "e": 1042, "s": 1009, "text": "How is t-SNE different with PCA?" }, { "code": null, "e": 1073, "s": 1042, "text": "How can we improve upon t-SNE?" }, { "code": null, "e": 1099, "s": 1073, "text": "What are the limitations?" }, { "code": null, "e": 1120, "s": 1099, "text": "What can we do next?" }, { "code": null, "e": 1295, "s": 1120, "text": "T-Distributed Stochastic Neighbor Embedding, or t-SNE, is a machine learning algorithm and it is often used to embedding high dimensional data in a low dimensional space [1]." }, { "code": null, "e": 1748, "s": 1295, "text": "In simple terms, the approach of t-SNE can be broken down into two steps. The first step is to represent the high dimensional data by constructing a probability distribution P, where the probability of similar points being picked is high, whereas the probability of dissimilar points being picked is low. The second step is to create a low dimensional space with another probability distribution Q that preserves the property of P as close as possible." }, { "code": null, "e": 2480, "s": 1748, "text": "In step 1, we compute the similarity between two data points using a conditional probability p. For example, the conditional probability of j given i represents that x_j would be picked by x_i as its neighbor assuming neighbors are picked in proportion to their probability density under a Gaussian distribution centered at x_i [1]. In step 2, we let y_i and y_j to be the low dimensional counterparts of x_i and x_j, respectively. Then we consider q to be a similar conditional probability for y_j being picked by y_i and we employ a student t-distribution in the low dimension map. The locations of the low dimensional data points are determined by minimizing the Kullback–Leibler divergence of probability distribution P from Q." }, { "code": null, "e": 2539, "s": 2480, "text": "For more technical details of t-SNE, check out this paper." }, { "code": null, "e": 2794, "s": 2539, "text": "I have chosen the MNIST dataset from Kaggle (link) as the example here because it is a simple computer vision dataset, with 28x28 pixel images of handwritten digits (0–9). We can think of each instance as a data point embedded in a 784-dimensional space." }, { "code": null, "e": 2851, "s": 2794, "text": "To see the full Python code, check out my Kaggle kernel." }, { "code": null, "e": 2898, "s": 2851, "text": "Without further ado, let’s get to the details!" }, { "code": null, "e": 3132, "s": 2898, "text": "Note that in the original Kaggle competition, the goal is to build a ML model using the training images with true labels that can accurately predict the labels on the test set. For our purposes here we will only use the training set." }, { "code": null, "e": 3168, "s": 3132, "text": "As usual, we check its shape first:" }, { "code": null, "e": 3260, "s": 3168, "text": "train.shape--------------------------------------------------------------------(42000, 785)" }, { "code": null, "e": 3367, "s": 3260, "text": "There are 42K training instances. The 785 columns are the 784 pixel values, as well as the ‘label’ column." }, { "code": null, "e": 3412, "s": 3367, "text": "We can check the label distribution as well:" }, { "code": null, "e": 3638, "s": 3412, "text": "label = train[\"label\"]label.value_counts()--------------------------------------------------------------------1 46847 44013 43519 41882 41776 41370 41324 40728 40635 3795Name: label, dtype: int64" }, { "code": null, "e": 3673, "s": 3638, "text": "Principal Component Analysis (PCA)" }, { "code": null, "e": 3769, "s": 3673, "text": "Before we implement t-SNE, let’s try PCA, a popular linear method for dimensionality reduction." }, { "code": null, "e": 3870, "s": 3769, "text": "After we standardize the data, we can transform our data using PCA (specify ‘n_components’ to be 2):" }, { "code": null, "e": 4060, "s": 3870, "text": "from sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAtrain = StandardScaler().fit_transform(train)pca = PCA(n_components=2)pca_res = pca.fit_transform(train)" }, { "code": null, "e": 4111, "s": 4060, "text": "Let’s make a scatter plot to visualize the result:" }, { "code": null, "e": 4225, "s": 4111, "text": "sns.scatterplot(x = pca_res[:,0], y = pca_res[:,1], hue = label, palette = sns.hls_palette(10), legend = 'full');" }, { "code": null, "e": 4488, "s": 4225, "text": "As shown in the scatter plot, PCA with two components does not sufficiently provide meaningful insights and patterns about the different labels. We know one drawback of PCA is that the linear projection can’t capture non-linear dependencies. Let’s try t-SNE now." }, { "code": null, "e": 4507, "s": 4488, "text": "T-SNE with sklearn" }, { "code": null, "e": 4571, "s": 4507, "text": "We will implement t-SNE using sklearn.manifold (documentation):" }, { "code": null, "e": 4801, "s": 4571, "text": "from sklearn.manifold import TSNEtsne = TSNE(n_components = 2, random_state=0)tsne_res = tsne.fit_transform(train)sns.scatterplot(x = tsne_res[:,0], y = tsne_res[:,1], hue = label, palette = sns.hls_palette(10), legend = 'full');" }, { "code": null, "e": 4940, "s": 4801, "text": "Now we can see that the different clusters are more separable compared with the result from PCA. Here are a few observations on this plot:" }, { "code": null, "e": 5178, "s": 4940, "text": "The “5” data points seem to be more spread out compared with the other clusters such as “2” and “4”.There are a few “5” and “8” data points that are similar to “3”s.There are two clusters of “7” and “9” where they are next to each other." }, { "code": null, "e": 5279, "s": 5178, "text": "The “5” data points seem to be more spread out compared with the other clusters such as “2” and “4”." }, { "code": null, "e": 5345, "s": 5279, "text": "There are a few “5” and “8” data points that are similar to “3”s." }, { "code": null, "e": 5418, "s": 5345, "text": "There are two clusters of “7” and “9” where they are next to each other." }, { "code": null, "e": 5449, "s": 5418, "text": "An Approach that Combines Both" }, { "code": null, "e": 5598, "s": 5449, "text": "It is generally recommended to use PCA or TruncatedSVD to reduce the number of dimension to a reasonable amount (e.g. 50) before applying t-SNE [2]." }, { "code": null, "e": 5675, "s": 5598, "text": "Doing so can reduce the level of noise as well as speed up the computations." }, { "code": null, "e": 5759, "s": 5675, "text": "Let’s try PCA (50 components) first and then apply t-SNE. Here is the scatter plot:" }, { "code": null, "e": 5876, "s": 5759, "text": "Compared with the previous scatter plot, wecan now separate out the 10 clusters better. here are a few observations:" }, { "code": null, "e": 6032, "s": 5876, "text": "Most of the “5” data points are not as spread out as before, despite a few that still look like “3”.There is one cluster of “7” and one cluster of “9” now." }, { "code": null, "e": 6133, "s": 6032, "text": "Most of the “5” data points are not as spread out as before, despite a few that still look like “3”." }, { "code": null, "e": 6189, "s": 6133, "text": "There is one cluster of “7” and one cluster of “9” now." }, { "code": null, "e": 6250, "s": 6189, "text": "Besides, the runtime in this approach decreased by over 60%." }, { "code": null, "e": 6310, "s": 6250, "text": "For more interactive 3D scatter plots, check out this post." }, { "code": null, "e": 6347, "s": 6310, "text": "Here are a few limitations of t-SNE:" }, { "code": null, "e": 6632, "s": 6347, "text": "Unlike PCA, the cost function of t-SNE is non-convex, meaning there is a possibility that we would be stuck in a local minima.Similar to other dimensionality reduction techniques, the meaning of the compressed dimensions as well as the transformed features becomes less interpretable." }, { "code": null, "e": 6759, "s": 6632, "text": "Unlike PCA, the cost function of t-SNE is non-convex, meaning there is a possibility that we would be stuck in a local minima." }, { "code": null, "e": 6918, "s": 6759, "text": "Similar to other dimensionality reduction techniques, the meaning of the compressed dimensions as well as the transformed features becomes less interpretable." }, { "code": null, "e": 6971, "s": 6918, "text": "Here are a few things that we can try as next steps:" }, { "code": null, "e": 7368, "s": 6971, "text": "Hyperparameter tuning — Try tune ‘perplexity’ and see its effect on the visualized output.Try some of the other non-linear techniques such as Uniform Manifold Approximation and Projection (UMAP), which is the generalization of t-SNE and it is based on Riemannian geometry.Train ML models on the transformed data and compare its performance with those from models without dimensionality reduction." }, { "code": null, "e": 7459, "s": 7368, "text": "Hyperparameter tuning — Try tune ‘perplexity’ and see its effect on the visualized output." }, { "code": null, "e": 7642, "s": 7459, "text": "Try some of the other non-linear techniques such as Uniform Manifold Approximation and Projection (UMAP), which is the generalization of t-SNE and it is based on Riemannian geometry." }, { "code": null, "e": 7767, "s": 7642, "text": "Train ML models on the transformed data and compare its performance with those from models without dimensionality reduction." }, { "code": null, "e": 7788, "s": 7767, "text": "Let’s quickly recap." }, { "code": null, "e": 7983, "s": 7788, "text": "We implemented t-SNE using sklearn on the MNIST dataset. We compared the visualized output with that from using PCA, and lastly, we tried a mixed approach which applies PCA first and then t-SNE." }, { "code": null, "e": 8068, "s": 7983, "text": "I hope you enjoyed this blog post and please share any thoughts that you may have :)" }, { "code": null, "e": 8129, "s": 8068, "text": "Check out my other post on Chi-square test for independence:" }, { "code": null, "e": 8152, "s": 8129, "text": "towardsdatascience.com" } ]
How to get the POST values from serializeArray in PHP?
To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with. Let’s say we have the PHP content in serialize.php file: <?php if( $_REQUEST["name"] ) { $name = $_REQUEST['name']; echo "Welcome ". $name; $age = $_REQUEST['age']; echo "<br />Your age : ". $age; $sex = $_REQUEST['sex']; echo "<br />Your gender : ". $sex; } ?> The following is an example showing the usage of this method: Live Demo <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#driver").click(function(event){ $.post( "/jquery/serialize.php", $("#testform").serializeArray(), function(data) { $('#stage1').html(data); } ); var fields = $("#testform").serializeArray(); $("#stage2").empty(); jQuery.each(fields, function(i, field){ $("#stage2").append(field.value + " "); }); }); }); </script> </head> <body> <p>Click on the button to load result.html file:</p> <div id = "stage1" style = "background-color:maroon;color:white;"> STAGE - 1 </div> <br /> <div id = "stage2" style = "background-color:maroon;color:white;"> STAGE - 2 </div> <form id = "testform"> <table> <tr> <td><p>Name:</p></td> <td><input type = "text" name = "name" size = "40" /></td> </tr> <tr> <td><p>Age:</p></td> <td><input type = "text" name = "age" size = "40" /></td> </tr> <tr> <td><p>Sex:</p></td> <td> <select name = "sex"> <option value = "Male" selected>Male</option> <option value = "Female" selected>Female</option> </select></td> </tr> <tr> <td colspan = "2"> <input type = "button" id = "driver" value = "Load Data" /> </td> </tr> </table> </form> </body> </html>
[ { "code": null, "e": 1299, "s": 1062, "text": "To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with." }, { "code": null, "e": 1356, "s": 1299, "text": "Let’s say we have the PHP content in serialize.php file:" }, { "code": null, "e": 1580, "s": 1356, "text": "<?php\nif( $_REQUEST[\"name\"] ) {\n\n $name = $_REQUEST['name'];\n echo \"Welcome \". $name;\n $age = $_REQUEST['age'];\n echo \"<br />Your age : \". $age;\n $sex = $_REQUEST['sex'];\n echo \"<br />Your gender : \". $sex;\n}\n?>" }, { "code": null, "e": 1642, "s": 1580, "text": "The following is an example showing the usage of this method:" }, { "code": null, "e": 1652, "s": 1642, "text": "Live Demo" }, { "code": null, "e": 3816, "s": 1652, "text": "<html>\n\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n $(\"#driver\").click(function(event){\n \n $.post(\n \"/jquery/serialize.php\",\n $(\"#testform\").serializeArray(),\n function(data) {\n $('#stage1').html(data);\n }\n );\n \n var fields = $(\"#testform\").serializeArray();\n $(\"#stage2\").empty();\n \n jQuery.each(fields, function(i, field){\n $(\"#stage2\").append(field.value + \" \");\n });\n \n });\n \n });\n </script>\n </head>\n \n <body>\n \n <p>Click on the button to load result.html file:</p>\n \n <div id = \"stage1\" style = \"background-color:maroon;color:white;\">\n STAGE - 1\n </div>\n \n <br />\n \n <div id = \"stage2\" style = \"background-color:maroon;color:white;\">\n STAGE - 2\n </div>\n \n <form id = \"testform\">\n \n <table>\n \n <tr>\n <td><p>Name:</p></td>\n <td><input type = \"text\" name = \"name\" size = \"40\" /></td>\n </tr>\n \n <tr>\n <td><p>Age:</p></td>\n <td><input type = \"text\" name = \"age\" size = \"40\" /></td>\n </tr>\n \n <tr>\n <td><p>Sex:</p></td>\n <td> <select name = \"sex\">\n <option value = \"Male\" selected>Male</option>\n <option value = \"Female\" selected>Female</option>\n </select></td>\n </tr>\n \n <tr>\n <td colspan = \"2\">\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </td>\n </tr> \n \n </table>\n \n </form>\n \n </body>\n \n</html>" } ]
C++ Program to Add Two Matrix Using Multi-dimensional Arrays
A matrix is a rectangular array of numbers that is arranged in the form of rows and columns. An example of a matrix is as follows. A 4*3 matrix has 4 rows and 3 columns as shown below − 3 5 1 7 1 9 3 9 4 1 6 7 A program that adds two matrices using multidimensional arrays is as follows. Live Demo #include <iostream> using namespace std; int main() { int r=2, c=4, sum[2][4], i, j; int a[2][4] = {{1,5,9,4} , {3,2,8,3}}; int b[2][4] = {{6,3,8,2} , {1,5,2,9}}; cout<<"The first matrix is: "<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; cout<<"The second matrix is: "<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<b[i][j]<<" "; cout<<endl; } cout<<endl; for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j]; cout<<"Sum of the two matrices is:"<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<sum[i][j]<<" "; cout<<endl; } return 0; } The first matrix is: 1 5 9 4 3 2 8 3 The second matrix is: 6 3 8 2 1 5 2 9 Sum of the two matrices is: 7 8 17 6 4 7 10 12 In the above program, first the two matrices a and b are defined. This is shown as follows. int a[2][4] = {{1,5,9,4} , {3,2,8,3}}; int b[2][4] = {{6,3,8,2} , {1,5,2,9}}; cout<<"The first matrix is: "<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; cout<<"The second matrix is: "<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<b[i][j]<<" "; cout<<endl; } The two matrices are added using a nested for loop and the result is stored in matrix sum[][]. This is shown in the following code snippet. for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j]; After the sum of the two matrices is obtained, it is printed on screen. This is done as follows − cout<<"Sum of the two matrices is:"<<endl; for(i=0; i<r; ++i) { for(j=0; j<c; ++j) cout<<sum[i][j]<<" "; cout<<endl; }
[ { "code": null, "e": 1155, "s": 1062, "text": "A matrix is a rectangular array of numbers that is arranged in the form of rows and columns." }, { "code": null, "e": 1193, "s": 1155, "text": "An example of a matrix is as follows." }, { "code": null, "e": 1248, "s": 1193, "text": "A 4*3 matrix has 4 rows and 3 columns as shown below −" }, { "code": null, "e": 1272, "s": 1248, "text": "3 5 1\n7 1 9\n3 9 4\n1 6 7" }, { "code": null, "e": 1350, "s": 1272, "text": "A program that adds two matrices using multidimensional arrays is as follows." }, { "code": null, "e": 1361, "s": 1350, "text": " Live Demo" }, { "code": null, "e": 2071, "s": 1361, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int r=2, c=4, sum[2][4], i, j;\n int a[2][4] = {{1,5,9,4} , {3,2,8,3}};\n int b[2][4] = {{6,3,8,2} , {1,5,2,9}};\n cout<<\"The first matrix is: \"<<endl;\n for(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n cout<<\"The second matrix is: \"<<endl;\n for(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<b[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n for(i=0;i<r;++i)\n for(j=0;j<c;++j)\n sum[i][j]=a[i][j]+b[i][j];\n cout<<\"Sum of the two matrices is:\"<<endl;\n for(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<sum[i][j]<<\" \";\n cout<<endl;\n }\n return 0;\n}" }, { "code": null, "e": 2195, "s": 2071, "text": "The first matrix is:\n1 5 9 4\n3 2 8 3\n\nThe second matrix is:\n6 3 8 2\n1 5 2 9\n\nSum of the two matrices is:\n7 8 17 6\n4 7 10 12" }, { "code": null, "e": 2287, "s": 2195, "text": "In the above program, first the two matrices a and b are defined. This is shown as follows." }, { "code": null, "e": 2618, "s": 2287, "text": "int a[2][4] = {{1,5,9,4} , {3,2,8,3}};\nint b[2][4] = {{6,3,8,2} , {1,5,2,9}};\ncout<<\"The first matrix is: \"<<endl;\nfor(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n}\ncout<<endl;\ncout<<\"The second matrix is: \"<<endl;\nfor(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<b[i][j]<<\" \";\n cout<<endl;\n}" }, { "code": null, "e": 2758, "s": 2618, "text": "The two matrices are added using a nested for loop and the result is stored in matrix sum[][]. This is shown in the following code snippet." }, { "code": null, "e": 2819, "s": 2758, "text": "for(i=0;i<r;++i)\nfor(j=0;j<c;++j)\nsum[i][j]=a[i][j]+b[i][j];" }, { "code": null, "e": 2917, "s": 2819, "text": "After the sum of the two matrices is obtained, it is printed on screen. This is done as follows −" }, { "code": null, "e": 3045, "s": 2917, "text": "cout<<\"Sum of the two matrices is:\"<<endl;\nfor(i=0; i<r; ++i) {\n for(j=0; j<c; ++j)\n cout<<sum[i][j]<<\" \";\n cout<<endl;\n}" } ]
Substring check in JavaScript - GeeksforGeeks
14 Mar, 2019 The includes() method can be used to check whether a string contains a specified substring. It returns true if substring is present. This method is case sensitive. Syntax: string.includes(searchvalue, start) Parameters: This method requires 2 parameters :- searchvalue: Required. It specifies the substring that needs to be searched. start: Optional. It specifies the index from where the searching is performed. By default it is 0. Return Value: True if the specified substring is present in string else returns false. Example: <!DOCTYPE html><html> <body> <h1>Welcome to GeeksforGeeks</h1> <p>Click the button to check whether <b>Geeks</b> is present in the below string. </p> Hello there! Welcome to GeeksforGeeks.<br><br> <button onclick="myFunction()">Try it</button> <p id="display"></p> <!--script to check string contains the specified substring.--> <script> function myFunction() { var str = "Hello there! Welcome to GeeksforGeeks."; var flag = str.includes("Geeks"); document.getElementById("display").innerHTML = flag; } </script> </body></html> Output:Before clicking try it button:After clicking try it button:Supported Browsers: The browser supported by includes() Method are listed below: Google Chrome 41 Apple Safari 9 Firefox 40 Opera 28 Edge 12.0 javascript-string Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to filter object array based on attributes? How to remove duplicate elements from JavaScript Array ? Lodash _.debounce() Method Angular File Upload How to get selected value in dropdown list using JavaScript ?
[ { "code": null, "e": 26543, "s": 26515, "text": "\n14 Mar, 2019" }, { "code": null, "e": 26707, "s": 26543, "text": "The includes() method can be used to check whether a string contains a specified substring. It returns true if substring is present. This method is case sensitive." }, { "code": null, "e": 26715, "s": 26707, "text": "Syntax:" }, { "code": null, "e": 26752, "s": 26715, "text": "string.includes(searchvalue, start)\n" }, { "code": null, "e": 26801, "s": 26752, "text": "Parameters: This method requires 2 parameters :-" }, { "code": null, "e": 26878, "s": 26801, "text": "searchvalue: Required. It specifies the substring that needs to be searched." }, { "code": null, "e": 26977, "s": 26878, "text": "start: Optional. It specifies the index from where the searching is performed. By default it is 0." }, { "code": null, "e": 27064, "s": 26977, "text": "Return Value: True if the specified substring is present in string else returns false." }, { "code": null, "e": 27073, "s": 27064, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <body> <h1>Welcome to GeeksforGeeks</h1> <p>Click the button to check whether <b>Geeks</b> is present in the below string. </p> Hello there! Welcome to GeeksforGeeks.<br><br> <button onclick=\"myFunction()\">Try it</button> <p id=\"display\"></p> <!--script to check string contains the specified substring.--> <script> function myFunction() { var str = \"Hello there! Welcome to GeeksforGeeks.\"; var flag = str.includes(\"Geeks\"); document.getElementById(\"display\").innerHTML = flag; } </script> </body></html>", "e": 27762, "s": 27073, "text": null }, { "code": null, "e": 27909, "s": 27762, "text": "Output:Before clicking try it button:After clicking try it button:Supported Browsers: The browser supported by includes() Method are listed below:" }, { "code": null, "e": 27926, "s": 27909, "text": "Google Chrome 41" }, { "code": null, "e": 27941, "s": 27926, "text": "Apple Safari 9" }, { "code": null, "e": 27952, "s": 27941, "text": "Firefox 40" }, { "code": null, "e": 27961, "s": 27952, "text": "Opera 28" }, { "code": null, "e": 27971, "s": 27961, "text": "Edge 12.0" }, { "code": null, "e": 27989, "s": 27971, "text": "javascript-string" }, { "code": null, "e": 27996, "s": 27989, "text": "Picked" }, { "code": null, "e": 28007, "s": 27996, "text": "JavaScript" }, { "code": null, "e": 28105, "s": 28007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28145, "s": 28105, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28206, "s": 28145, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28247, "s": 28206, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28269, "s": 28247, "text": "JavaScript | Promises" }, { "code": null, "e": 28323, "s": 28269, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28371, "s": 28323, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28428, "s": 28371, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 28455, "s": 28428, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 28475, "s": 28455, "text": "Angular File Upload" } ]
Python | Extract Combination Mapping in two lists - GeeksforGeeks
05 Sep, 2019 Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let’s discuss certain way in which this problem can be solved. Method : Using zip() + product()With these functions this problem can be solved and would require two steps to perform it. In the 1st step, we find all the combinations of elements using product() and as a part of 2nd step, we perform the possible pairing with the result of step 1 using zip() and output the desired result. # Python3 code to demonstrate working of# Extract Combination Mapping in two lists# using zip() + product()from itertools import product # initialize liststest_list1 = [3, 4, 5]test_list2 = ['x', 'y'] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Extract Combination Mapping in two lists# using zip() + product()res = list(list(zip(test_list1, ele)) for ele in product(test_list2, repeat = len(test_list1))) # printing resultprint("Mapped Combination result : " + str(res)) The original list 1 is : [3, 4, 5]The original list 2 is : [‘x’, ‘y’]Mapped Combination result : [[(3, ‘x’), (4, ‘x’), (5, ‘x’)], [(3, ‘x’), (4, ‘x’), (5, ‘y’)], [(3, ‘x’), (4, ‘y’), (5, ‘x’)], [(3, ‘x’), (4, ‘y’), (5, ‘y’)], [(3, ‘y’), (4, ‘x’), (5, ‘x’)], [(3, ‘y’), (4, ‘x’), (5, ‘y’)], [(3, ‘y’), (4, ‘y’), (5, ‘x’)], [(3, ‘y’), (4, ‘y’), (5, ‘y’)]] Python list-programs 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? 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": 25537, "s": 25509, "text": "\n05 Sep, 2019" }, { "code": null, "e": 25830, "s": 25537, "text": "Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let’s discuss certain way in which this problem can be solved." }, { "code": null, "e": 26155, "s": 25830, "text": "Method : Using zip() + product()With these functions this problem can be solved and would require two steps to perform it. In the 1st step, we find all the combinations of elements using product() and as a part of 2nd step, we perform the possible pairing with the result of step 1 using zip() and output the desired result." }, { "code": "# Python3 code to demonstrate working of# Extract Combination Mapping in two lists# using zip() + product()from itertools import product # initialize liststest_list1 = [3, 4, 5]test_list2 = ['x', 'y'] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Extract Combination Mapping in two lists# using zip() + product()res = list(list(zip(test_list1, ele)) for ele in product(test_list2, repeat = len(test_list1))) # printing resultprint(\"Mapped Combination result : \" + str(res))", "e": 26719, "s": 26155, "text": null }, { "code": null, "e": 27073, "s": 26719, "text": "The original list 1 is : [3, 4, 5]The original list 2 is : [‘x’, ‘y’]Mapped Combination result : [[(3, ‘x’), (4, ‘x’), (5, ‘x’)], [(3, ‘x’), (4, ‘x’), (5, ‘y’)], [(3, ‘x’), (4, ‘y’), (5, ‘x’)], [(3, ‘x’), (4, ‘y’), (5, ‘y’)], [(3, ‘y’), (4, ‘x’), (5, ‘x’)], [(3, ‘y’), (4, ‘x’), (5, ‘y’)], [(3, ‘y’), (4, ‘y’), (5, ‘x’)], [(3, ‘y’), (4, ‘y’), (5, ‘y’)]]" }, { "code": null, "e": 27094, "s": 27073, "text": "Python list-programs" }, { "code": null, "e": 27101, "s": 27094, "text": "Python" }, { "code": null, "e": 27199, "s": 27101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27231, "s": 27199, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27273, "s": 27231, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27315, "s": 27273, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27342, "s": 27315, "text": "Python Classes and Objects" }, { "code": null, "e": 27398, "s": 27342, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27420, "s": 27398, "text": "Defaultdict in Python" }, { "code": null, "e": 27459, "s": 27420, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27490, "s": 27459, "text": "Python | os.path.join() method" }, { "code": null, "e": 27519, "s": 27490, "text": "Create a directory in Python" } ]
HTML | DOM Input Password placeholder Property - GeeksforGeeks
08 Mar, 2019 The DOM Input Password Placeholder Property is used to set or return the value of the Placeholder attribute of a Password Field. The placeholder attribute specifies a short hint that describes the expected value of an input field . The short hint is displayed in the field before the user enters a value. Syntax: It is used to return the placeholder property.passwordObject.placeholder passwordObject.placeholder It is used to set the placeholder property.passwordObject.placeholder = text passwordObject.placeholder = text Property Value: text: It defines a short hint that describe a expected value of the Password Field. Return Value: It returns a String value which represented a short hint that describes the expected value of the Password Field. Example-1: This Example illustrates how to return the property. <!DOCTYPE html> <html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Input Password placeholder Property</h2> <form id="myGeeks"> Password: <input type="password" id="myPsw" name="Geeks" placeholder="password"> </form> <br><br> <button onclick="myFunction()"> Click Here! </button> <p id="demo" style="color:green;font-size:25px;"></p> <script> function myFunction() { var x = document.getElementById( "myPsw").placeholder; document.getElementById( "demo").innerHTML = x; } </script> </body> </html> Output: Before clicking on the button:After clicking on the button: Example-2: This example illustrates that how to set the property. <!DOCTYPE html> <html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Input Password placeholder Property</h2> <form id="myGeeks"> Password: <input type="password" id="myPsw" name="Geeks" placeholder="password"> </form> <br><br> <button onclick="myFunction()"> Click Here! </button> <p id="demo" style="color:green;font-size:25px;"></p> <script> function myFunction() { var x = document.getElementById( "myPsw").placeholder ="Enter Your Password"; document.getElementById( "demo").innerHTML = x; } </script> </body> </html> Output:Before clicking on the button:After clicking on the button: Supported Browsers: The browser supported by DOM input Password placeholder Property are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM 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": "\n08 Mar, 2019" }, { "code": null, "e": 26444, "s": 26139, "text": "The DOM Input Password Placeholder Property is used to set or return the value of the Placeholder attribute of a Password Field. The placeholder attribute specifies a short hint that describes the expected value of an input field . The short hint is displayed in the field before the user enters a value." }, { "code": null, "e": 26452, "s": 26444, "text": "Syntax:" }, { "code": null, "e": 26525, "s": 26452, "text": "It is used to return the placeholder property.passwordObject.placeholder" }, { "code": null, "e": 26552, "s": 26525, "text": "passwordObject.placeholder" }, { "code": null, "e": 26629, "s": 26552, "text": "It is used to set the placeholder property.passwordObject.placeholder = text" }, { "code": null, "e": 26663, "s": 26629, "text": "passwordObject.placeholder = text" }, { "code": null, "e": 26679, "s": 26663, "text": "Property Value:" }, { "code": null, "e": 26763, "s": 26679, "text": "text: It defines a short hint that describe a expected value of the Password Field." }, { "code": null, "e": 26891, "s": 26763, "text": "Return Value: It returns a String value which represented a short hint that describes the expected value of the Password Field." }, { "code": null, "e": 26955, "s": 26891, "text": "Example-1: This Example illustrates how to return the property." }, { "code": "<!DOCTYPE html> <html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Input Password placeholder Property</h2> <form id=\"myGeeks\"> Password: <input type=\"password\" id=\"myPsw\" name=\"Geeks\" placeholder=\"password\"> </form> <br><br> <button onclick=\"myFunction()\"> Click Here! </button> <p id=\"demo\" style=\"color:green;font-size:25px;\"></p> <script> function myFunction() { var x = document.getElementById( \"myPsw\").placeholder; document.getElementById( \"demo\").innerHTML = x; } </script> </body> </html> ", "e": 27706, "s": 26955, "text": null }, { "code": null, "e": 27714, "s": 27706, "text": "Output:" }, { "code": null, "e": 27774, "s": 27714, "text": "Before clicking on the button:After clicking on the button:" }, { "code": null, "e": 27840, "s": 27774, "text": "Example-2: This example illustrates that how to set the property." }, { "code": "<!DOCTYPE html> <html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Input Password placeholder Property</h2> <form id=\"myGeeks\"> Password: <input type=\"password\" id=\"myPsw\" name=\"Geeks\" placeholder=\"password\"> </form> <br><br> <button onclick=\"myFunction()\"> Click Here! </button> <p id=\"demo\" style=\"color:green;font-size:25px;\"></p> <script> function myFunction() { var x = document.getElementById( \"myPsw\").placeholder =\"Enter Your Password\"; document.getElementById( \"demo\").innerHTML = x; } </script> </body> </html> ", "e": 28614, "s": 27840, "text": null }, { "code": null, "e": 28681, "s": 28614, "text": "Output:Before clicking on the button:After clicking on the button:" }, { "code": null, "e": 28784, "s": 28681, "text": "Supported Browsers: The browser supported by DOM input Password placeholder Property are listed below:" }, { "code": null, "e": 28798, "s": 28784, "text": "Google Chrome" }, { "code": null, "e": 28816, "s": 28798, "text": "Internet Explorer" }, { "code": null, "e": 28824, "s": 28816, "text": "Firefox" }, { "code": null, "e": 28830, "s": 28824, "text": "Opera" }, { "code": null, "e": 28837, "s": 28830, "text": "Safari" }, { "code": null, "e": 28974, "s": 28837, "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": 28983, "s": 28974, "text": "HTML-DOM" }, { "code": null, "e": 28988, "s": 28983, "text": "HTML" }, { "code": null, "e": 29005, "s": 28988, "text": "Web Technologies" }, { "code": null, "e": 29010, "s": 29005, "text": "HTML" }, { "code": null, "e": 29108, "s": 29010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29132, "s": 29108, "text": "REST API (Introduction)" }, { "code": null, "e": 29173, "s": 29132, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 29210, "s": 29173, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29239, "s": 29210, "text": "Form validation using jQuery" }, { "code": null, "e": 29259, "s": 29239, "text": "Angular File Upload" }, { "code": null, "e": 29299, "s": 29259, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29332, "s": 29299, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29377, "s": 29332, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29420, "s": 29377, "text": "How to fetch data from an API in ReactJS ?" } ]
Iterator Invalidation in C++ - GeeksforGeeks
23 Dec, 2021 When the container to which an Iterator points changes shape internally, i.e. when elements are moved from one position to another, and the initial iterator still points to the old invalid location, then it is called Iterator invalidation. One should be careful while using iterators in C++. When we iterate over our container using iterators then it may happen that the iterator gets invalidated. This may be due to change in the shape and size of the container while iterating. For example, Iterator invalidation in a vector whenever either, at any point in the vector, an element is inserted or an element from the vector is removed. Let us take an example to understand this, CPP // CPP program to demonstrate iterator// invalidations#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Creating a sample vector vector<int> v = { 1, 5, 10, 15, 20 }; // Changing vector while iterating over it // (This causes iterator invalidation) for (auto it = v.begin(); it != v.end(); it++) if ((*it) == 5) v.push_back(-1); for (auto it = v.begin(); it != v.end(); it++) cout << (*it) << " "; return 0;} 1 5 10 15 20 -1 -1 In the above example code, it may happen that when we add an element -1 while iterating the vector, the size of the vector can get more than the maximum size due to which a new memory is allocated to the vector and all elements are copied there. But, our iterator still points to the previous old memory address. So, now we can say that iterator gets invalidated. This is one example of invalidation. Given below are some rules for iterator invalidation. 1. Insertion 2. Erasure 3. Resizing Note: Invalidation of iterator does not always mean that dereferencing such an iterator causes a program to crash. It also includes the possibility that iterator does not point to an element which it is supposed to point. This article is contributed by Ashish Sharma. 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. abhirishi0805 anshikajain26 STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Inline Functions in C++ Queue in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25369, "s": 25341, "text": "\n23 Dec, 2021" }, { "code": null, "e": 25850, "s": 25369, "text": "When the container to which an Iterator points changes shape internally, i.e. when elements are moved from one position to another, and the initial iterator still points to the old invalid location, then it is called Iterator invalidation. One should be careful while using iterators in C++. When we iterate over our container using iterators then it may happen that the iterator gets invalidated. This may be due to change in the shape and size of the container while iterating. " }, { "code": null, "e": 26050, "s": 25850, "text": "For example, Iterator invalidation in a vector whenever either, at any point in the vector, an element is inserted or an element from the vector is removed. Let us take an example to understand this," }, { "code": null, "e": 26054, "s": 26050, "text": "CPP" }, { "code": "// CPP program to demonstrate iterator// invalidations#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Creating a sample vector vector<int> v = { 1, 5, 10, 15, 20 }; // Changing vector while iterating over it // (This causes iterator invalidation) for (auto it = v.begin(); it != v.end(); it++) if ((*it) == 5) v.push_back(-1); for (auto it = v.begin(); it != v.end(); it++) cout << (*it) << \" \"; return 0;}", "e": 26537, "s": 26054, "text": null }, { "code": null, "e": 26557, "s": 26537, "text": "1 5 10 15 20 -1 -1 " }, { "code": null, "e": 27012, "s": 26557, "text": "In the above example code, it may happen that when we add an element -1 while iterating the vector, the size of the vector can get more than the maximum size due to which a new memory is allocated to the vector and all elements are copied there. But, our iterator still points to the previous old memory address. So, now we can say that iterator gets invalidated. This is one example of invalidation. Given below are some rules for iterator invalidation." }, { "code": null, "e": 27025, "s": 27012, "text": "1. Insertion" }, { "code": null, "e": 27037, "s": 27025, "text": "2. Erasure " }, { "code": null, "e": 27050, "s": 27037, "text": "3. Resizing " }, { "code": null, "e": 27272, "s": 27050, "text": "Note: Invalidation of iterator does not always mean that dereferencing such an iterator causes a program to crash. It also includes the possibility that iterator does not point to an element which it is supposed to point." }, { "code": null, "e": 27695, "s": 27272, "text": "This article is contributed by Ashish Sharma. 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": 27709, "s": 27695, "text": "abhirishi0805" }, { "code": null, "e": 27723, "s": 27709, "text": "anshikajain26" }, { "code": null, "e": 27727, "s": 27723, "text": "STL" }, { "code": null, "e": 27731, "s": 27727, "text": "C++" }, { "code": null, "e": 27735, "s": 27731, "text": "STL" }, { "code": null, "e": 27739, "s": 27735, "text": "CPP" }, { "code": null, "e": 27837, "s": 27739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27865, "s": 27837, "text": "Operator Overloading in C++" }, { "code": null, "e": 27885, "s": 27865, "text": "Polymorphism in C++" }, { "code": null, "e": 27918, "s": 27885, "text": "Friend class and function in C++" }, { "code": null, "e": 27942, "s": 27918, "text": "Sorting a vector in C++" }, { "code": null, "e": 27967, "s": 27942, "text": "std::string class in C++" }, { "code": null, "e": 28011, "s": 27967, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 28035, "s": 28011, "text": "Inline Functions in C++" }, { "code": null, "e": 28080, "s": 28035, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 28133, "s": 28080, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
Python | Initializing multiple lists - GeeksforGeeks
30 Dec, 2018 In real applications, we often have to work with multiple lists and to initialize them with empty lists hampers the readability of code. Hence a one-liner is required to perform this task in short so as to give a clear idea of type and number of lists declared to be used. Method #1 : Using * operatorWe can enlist all the required list comma separated and then initialize them with an empty list and multiply that empty list using the * operator by the number of lists specified. # Python3 code to demonstrate # to initialize multiple lists# using * operator # using * operator# to initialize multiple listslist1, list2, list3, list4 = ([], ) * 4 # printing listsprint ("The initialized lists are : ")print ("List 1 : " + str(list1))print ("List 2 : " + str(list2))print ("List 3 : " + str(list3))print ("List 4 : " + str(list4)) The initialized lists are : List 1 : [] List 2 : [] List 3 : [] List 4 : [] Method #2 : Using loopThis method is similar to the method explained above but the only difference is that we use loop instead of * operator to perform the task of multiple assignments. # Python3 code to demonstrate # to initialize multiple lists# using loop # using loop# to initialize multiple listslist1, list2, list3, list4 = ([] for i in range(4)) # printing listsprint ("The initialized lists are : ")print ("List 1 : " + str(list1))print ("List 2 : " + str(list2))print ("List 3 : " + str(list3))print ("List 4 : " + str(list4)) The initialized lists are : List 1 : [] List 2 : [] List 3 : [] List 4 : [] Method #3 : Using defaultdict()This is a method different and also performs a slightly different utility than the above two methods discussed. This creates a dictionary with a specific name and we have option to make any number of keys and perform the append operations straight away as they get initialized by the list. # Python3 code to demonstrate # to initialize multiple lists# using defaultdict()import collections # using defaultdict()# to initialize multiple lists# no need to initialize with empty listsmul_list_dict = collections.defaultdict(list)mul_list_dict['list1'].append(1)mul_list_dict['list2'].append(2)mul_list_dict['list3'].append(3)mul_list_dict['list4'].append(4) # printing listsprint ("The initialized lists are : ")print ("List 1 : " + str(mul_list_dict['list1']))print ("List 2 : " + str(mul_list_dict['list2']))print ("List 3 : " + str(mul_list_dict['list3']))print ("List 4 : " + str(mul_list_dict['list4'])) The initialized lists are : List 1 : [1] List 2 : [2] List 3 : [3] List 4 : [4] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n30 Dec, 2018" }, { "code": null, "e": 25810, "s": 25537, "text": "In real applications, we often have to work with multiple lists and to initialize them with empty lists hampers the readability of code. Hence a one-liner is required to perform this task in short so as to give a clear idea of type and number of lists declared to be used." }, { "code": null, "e": 26018, "s": 25810, "text": "Method #1 : Using * operatorWe can enlist all the required list comma separated and then initialize them with an empty list and multiply that empty list using the * operator by the number of lists specified." }, { "code": "# Python3 code to demonstrate # to initialize multiple lists# using * operator # using * operator# to initialize multiple listslist1, list2, list3, list4 = ([], ) * 4 # printing listsprint (\"The initialized lists are : \")print (\"List 1 : \" + str(list1))print (\"List 2 : \" + str(list2))print (\"List 3 : \" + str(list3))print (\"List 4 : \" + str(list4))", "e": 26370, "s": 26018, "text": null }, { "code": null, "e": 26448, "s": 26370, "text": "The initialized lists are : \nList 1 : []\nList 2 : []\nList 3 : []\nList 4 : []\n" }, { "code": null, "e": 26635, "s": 26448, "text": " Method #2 : Using loopThis method is similar to the method explained above but the only difference is that we use loop instead of * operator to perform the task of multiple assignments." }, { "code": "# Python3 code to demonstrate # to initialize multiple lists# using loop # using loop# to initialize multiple listslist1, list2, list3, list4 = ([] for i in range(4)) # printing listsprint (\"The initialized lists are : \")print (\"List 1 : \" + str(list1))print (\"List 2 : \" + str(list2))print (\"List 3 : \" + str(list3))print (\"List 4 : \" + str(list4))", "e": 26987, "s": 26635, "text": null }, { "code": null, "e": 27065, "s": 26987, "text": "The initialized lists are : \nList 1 : []\nList 2 : []\nList 3 : []\nList 4 : []\n" }, { "code": null, "e": 27387, "s": 27065, "text": " Method #3 : Using defaultdict()This is a method different and also performs a slightly different utility than the above two methods discussed. This creates a dictionary with a specific name and we have option to make any number of keys and perform the append operations straight away as they get initialized by the list." }, { "code": "# Python3 code to demonstrate # to initialize multiple lists# using defaultdict()import collections # using defaultdict()# to initialize multiple lists# no need to initialize with empty listsmul_list_dict = collections.defaultdict(list)mul_list_dict['list1'].append(1)mul_list_dict['list2'].append(2)mul_list_dict['list3'].append(3)mul_list_dict['list4'].append(4) # printing listsprint (\"The initialized lists are : \")print (\"List 1 : \" + str(mul_list_dict['list1']))print (\"List 2 : \" + str(mul_list_dict['list2']))print (\"List 3 : \" + str(mul_list_dict['list3']))print (\"List 4 : \" + str(mul_list_dict['list4']))", "e": 28005, "s": 27387, "text": null }, { "code": null, "e": 28087, "s": 28005, "text": "The initialized lists are : \nList 1 : [1]\nList 2 : [2]\nList 3 : [3]\nList 4 : [4]\n" }, { "code": null, "e": 28108, "s": 28087, "text": "Python list-programs" }, { "code": null, "e": 28115, "s": 28108, "text": "Python" }, { "code": null, "e": 28131, "s": 28115, "text": "Python Programs" }, { "code": null, "e": 28229, "s": 28131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28261, "s": 28229, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28303, "s": 28261, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28345, "s": 28303, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28401, "s": 28345, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28428, "s": 28401, "text": "Python Classes and Objects" }, { "code": null, "e": 28450, "s": 28428, "text": "Defaultdict in Python" }, { "code": null, "e": 28489, "s": 28450, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28535, "s": 28489, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28573, "s": 28535, "text": "Python | Convert a list to dictionary" } ]
Check if a path exists from start to end cell in given Matrix with obstacles in at most K moves - GeeksforGeeks
05 Apr, 2022 Given a positive integer K and a matrix grid of dimensions N * M consisting of characters ‘.’ and ‘#’, where ‘.’ represents the unblocked cells and ‘#’ represents the blocked cells, the task is to check if the bottom-right of the grid can be reached from the top-left cell of the matrix through unblocked cells in at most K moves or not such that it takes one move to move to its adjacent cell in the right or downward direction. Examples: Input: grid[][] = {{‘.’, ‘.’, ‘.’}, {‘#’, ‘.’, ‘.’}, {‘#’, ‘#’, ‘.’}}, K = 4Output: YesExplanation: It is possible to reach the bottom right cell of the given grid using the following set of moves: right-> down -> right -> down. Hence, the number of moves required are 4 which is the minimum possible and is less than K. Input: grid[][] = {{‘.’, ‘.’, ‘.’, ‘.’}, {‘.’, ‘.’, ‘.’, ‘.’}, {‘#’, ‘#’, ‘#’, ‘#’}, {‘.’, ‘.’, ‘.’, ‘.’}}, K = 4Output: NoExplanation: There are no possible set of moves to reach the bottom right cell from the top left cell of the given matrix. Approach: The given problem can be solved with the help of Dynamic Programming by using a tabulation approach. It can be solved by precomputing the minimum number of moves required to move from the top-left to the bottom-right cell using an approach similar to the one discussed in this article. It can be observed that if dp[i][j] represents the minimum number of moves to reach the cell (i, j) from (0, 0), then the DP relation can be formulated as below: dp[i][j] = min(dp[i][j], 1 + dp[i – 1][j], 1+ dp[i][j – 1])) Thereafter, if the minimum number of moves is at most K then print “Yes”, otherwise print “No”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation for the above approach#include "bits/stdc++.h"using namespace std; // Function to check if it is possible// to reach the bottom right of the grid// from top left using atmost K movesstring canReach(vector<vector<char> >& grid, int K){ int N = grid.size(); int M = grid[0].size(); // Stores the DP states vector<vector<long long> > dp( N, vector<long long>(M, INT_MAX)); // if first cell or last cell is blocked then // not possible if(grid[0][0] != '.' || grid[N - 1][M - 1] != '.') return "No"; // Initial condition dp[0][0] = 0; // Initializing the DP table // in 1st row for (int i = 1; i < M; i++) { if (grid[0][i] == '.') { dp[0][i] = 1 + dp[0][i - 1]; } else break; } // Initializing the DP table // in 1st column for (int i = 1; i < N; i++) { if (grid[i][0] == '.') { dp[i][0] = 1 + dp[i - 1][0]; } else break; } // Iterate through the grid for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i][j] == '.') { dp[i][j] = min( dp[i][j], 1 + min(dp[i - 1][j], dp[i][j - 1])); } } } // Return answer return (dp[N - 1][M - 1] <= K ? "Yes" : "No");} // Driver Codeint main(){ vector<vector<char> > grid = { { '.', '.', '.' }, { '#', '.', '.' }, { '#', '#', '.' } }; int K = 4; cout << canReach(grid, K); return 0;} // Java implementation for the above approach//include "bits/stdJava.h"import java.util.*; class GFG{ // Function to check if it is possible// to reach the bottom right of the grid// from top left using atmost K movesstatic String canReach(char[][] grid, int K){ int N = grid.length; int M = grid[0].length; // Stores the DP states int[][] dp = new int[N][M]; for(int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { dp[i][j] = Integer.MAX_VALUE; } } // if first cell or last cell is blocked then // not possible if(grid[0][0] != '.' || grid[N - 1][M - 1] != '.') return "No"; // Initial condition dp[0][0] = 0; // Initializing the DP table // in 1st row for (int i = 1; i < M; i++) { if (grid[0][i] == '.') { dp[0][i] = 1 + dp[0][i - 1]; } else break; } // Initializing the DP table // in 1st column for (int i = 1; i < N; i++) { if (grid[i][0] == '.') { dp[i][0] = 1 + dp[i - 1][0]; } else break; } // Iterate through the grid for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i][j] == '.') { dp[i][j] = Math.min( dp[i][j], 1 + Math.min(dp[i - 1][j], dp[i][j - 1])); } } } // Return answer return (dp[N - 1][M - 1] <= K ? "Yes" : "No");} // Driver Codepublic static void main(String[] args){ char[][] grid = { { '.', '.', '.' }, { '#', '.', '.' }, { '#', '#', '.' } }; int K = 4; System.out.print(canReach(grid, K));}} // This code is contributed by 29AjayKumar # Python3 implementation for the above approachINT_MAX = 2147483647 # Function to check if it is possible# to reach the bottom right of the grid# from top left using atmost K movesdef canReach(grid, K): N = len(grid) M = len(grid[0]) # Stores the DP states dp = [[INT_MAX for _ in range(M)] for _ in range(N)] # if first cell or last cell is blocked then # not possible if(grid[0][0] != '.' or grid[N - 1][M - 1] != '.'): return("No") # Initial condition dp[0][0] = 0 # Initializing the DP table # in 1st row for i in range(1, M): if (grid[0][i] == '.'): dp[0][i] = 1 + dp[0][i - 1] else: break # Initializing the DP table # in 1st column for i in range(1, N): if (grid[i][0] == '.'): dp[i][0] = 1 + dp[i - 1][0] else: break # Iterate through the grid for i in range(1, N): for j in range(1, M): # If current position # is not an obstacle, # update the dp state if (grid[i][j] == '.'): dp[i][j] = min(dp[i][j], 1 + min(dp[i - 1][j], dp[i][j - 1])) # Return answer if dp[N - 1][M - 1] <= K: return("Yes") else: return("No") # Driver Codeif __name__ == "__main__": grid = [ [ '.', '.', '.' ], [ '#', '.', '.' ], [ '#', '#', '.' ] ] K = 4 print(canReach(grid, K)) # This code is contributed by rakeshsahni // C# implementation for the above approach//include "bits/stdJava.h"using System; class GFG{ // Function to check if it is possible// to reach the bottom right of the grid// from top left using atmost K movesstatic String canReach(char[,] grid, int K){ int N = grid.GetLength(0); int M = grid.GetLength(1); // Stores the DP states int[,] dp = new int[N,M]; for(int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { dp[i, j] = int.MaxValue; } } // if first cell or last cell is blocked then // not possible if(grid[0, 0] != '.' || grid[N - 1, M - 1] != '.') return "No"; // Initial condition dp[0, 0] = 0; // Initializing the DP table // in 1st row for (int i = 1; i < M; i++) { if (grid[0, i] == '.') { dp[0, i] = 1 + dp[0, i - 1]; } else break; } // Initializing the DP table // in 1st column for (int i = 1; i < N; i++) { if (grid[i, 0] == '.') { dp[i, 0] = 1 + dp[i - 1, 0]; } else break; } // Iterate through the grid for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i, j] == '.') { dp[i, j] = Math.Min( dp[i, j], 1 + Math.Min(dp[i - 1, j], dp[i, j - 1])); } } } // Return answer return (dp[N - 1, M - 1] <= K ? "Yes" : "No");} // Driver Codepublic static void Main(){ char[,] grid = { { '.', '.', '.' }, { '/', '.', '.' }, { '/', '/', '.' } }; int K = 4; Console.Write(canReach(grid, K));}} // This code is contributed by Saurabh jaiswal <script> // JavaScript Program to implement // the above approach // Function to check if it is possible // to reach the bottom right of the grid // from top left using atmost K moves function canReach(grid, K) { let N = grid.length; let M = grid[0].length; // Stores the DP states let dp = new Array(N); for (let i = 0; i < dp.length; i++) { dp[i] = new Array(M).fill(Number.MAX_VALUE); } // if first cell or last cell is blocked then // not possible if(grid[0][0] != '.' || grid[N - 1][M - 1] != '.') return "No"; // Initial condition dp[0][0] = 0; // Initializing the DP table // in 1st row for (let i = 1; i < M; i++) { if (grid[0][i] == '.') { dp[0][i] = 1 + dp[0][i - 1]; } else break; } // Initializing the DP table // in 1st column for (let i = 1; i < N; i++) { if (grid[i][0] == '.') { dp[i][0] = 1 + dp[i - 1][0]; } else break; } // Iterate through the grid for (let i = 1; i < N; i++) { for (let j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i][j] == '.') { dp[i][j] = Math.min( dp[i][j], 1 + Math.min(dp[i - 1][j], dp[i][j - 1])); } } } // Return answer return (dp[N - 1][M - 1] <= K ? "Yes" : "No"); } // Driver Code let grid = [['.', '.', '.'], ['#', '.', '.'], ['#', '#', '.']]; let K = 4; document.write(canReach(grid, K)); // This code is contributed by Potta Lokesh </script> Yes Time Complexity: O(N * M)Auxiliary Space: O(N * M) lokeshpotta20 rakeshsahni 29AjayKumar _saurabh_jaiswal harendrakumar123 D-E-Shaw DE Shaw Dynamic Programming Matrix D-E-Shaw DE Shaw Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Optimal Substructure Property in Dynamic Programming | DP-2 Optimal Binary Search Tree | DP-24 Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Program to find largest element in an array Print a given matrix in spiral form Rat in a Maze | Backtracking-2 Maximum size square sub-matrix with all 1s Sudoku | Backtracking-7
[ { "code": null, "e": 25941, "s": 25913, "text": "\n05 Apr, 2022" }, { "code": null, "e": 26371, "s": 25941, "text": "Given a positive integer K and a matrix grid of dimensions N * M consisting of characters ‘.’ and ‘#’, where ‘.’ represents the unblocked cells and ‘#’ represents the blocked cells, the task is to check if the bottom-right of the grid can be reached from the top-left cell of the matrix through unblocked cells in at most K moves or not such that it takes one move to move to its adjacent cell in the right or downward direction." }, { "code": null, "e": 26381, "s": 26371, "text": "Examples:" }, { "code": null, "e": 26702, "s": 26381, "text": "Input: grid[][] = {{‘.’, ‘.’, ‘.’}, {‘#’, ‘.’, ‘.’}, {‘#’, ‘#’, ‘.’}}, K = 4Output: YesExplanation: It is possible to reach the bottom right cell of the given grid using the following set of moves: right-> down -> right -> down. Hence, the number of moves required are 4 which is the minimum possible and is less than K." }, { "code": null, "e": 26948, "s": 26702, "text": "Input: grid[][] = {{‘.’, ‘.’, ‘.’, ‘.’}, {‘.’, ‘.’, ‘.’, ‘.’}, {‘#’, ‘#’, ‘#’, ‘#’}, {‘.’, ‘.’, ‘.’, ‘.’}}, K = 4Output: NoExplanation: There are no possible set of moves to reach the bottom right cell from the top left cell of the given matrix." }, { "code": null, "e": 27406, "s": 26948, "text": "Approach: The given problem can be solved with the help of Dynamic Programming by using a tabulation approach. It can be solved by precomputing the minimum number of moves required to move from the top-left to the bottom-right cell using an approach similar to the one discussed in this article. It can be observed that if dp[i][j] represents the minimum number of moves to reach the cell (i, j) from (0, 0), then the DP relation can be formulated as below:" }, { "code": null, "e": 27467, "s": 27406, "text": "dp[i][j] = min(dp[i][j], 1 + dp[i – 1][j], 1+ dp[i][j – 1]))" }, { "code": null, "e": 27564, "s": 27467, "text": "Thereafter, if the minimum number of moves is at most K then print “Yes”, otherwise print “No”. " }, { "code": null, "e": 27615, "s": 27564, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27619, "s": 27615, "text": "C++" }, { "code": null, "e": 27624, "s": 27619, "text": "Java" }, { "code": null, "e": 27632, "s": 27624, "text": "Python3" }, { "code": null, "e": 27635, "s": 27632, "text": "C#" }, { "code": null, "e": 27646, "s": 27635, "text": "Javascript" }, { "code": "// C++ implementation for the above approach#include \"bits/stdc++.h\"using namespace std; // Function to check if it is possible// to reach the bottom right of the grid// from top left using atmost K movesstring canReach(vector<vector<char> >& grid, int K){ int N = grid.size(); int M = grid[0].size(); // Stores the DP states vector<vector<long long> > dp( N, vector<long long>(M, INT_MAX)); // if first cell or last cell is blocked then // not possible if(grid[0][0] != '.' || grid[N - 1][M - 1] != '.') return \"No\"; // Initial condition dp[0][0] = 0; // Initializing the DP table // in 1st row for (int i = 1; i < M; i++) { if (grid[0][i] == '.') { dp[0][i] = 1 + dp[0][i - 1]; } else break; } // Initializing the DP table // in 1st column for (int i = 1; i < N; i++) { if (grid[i][0] == '.') { dp[i][0] = 1 + dp[i - 1][0]; } else break; } // Iterate through the grid for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i][j] == '.') { dp[i][j] = min( dp[i][j], 1 + min(dp[i - 1][j], dp[i][j - 1])); } } } // Return answer return (dp[N - 1][M - 1] <= K ? \"Yes\" : \"No\");} // Driver Codeint main(){ vector<vector<char> > grid = { { '.', '.', '.' }, { '#', '.', '.' }, { '#', '#', '.' } }; int K = 4; cout << canReach(grid, K); return 0;}", "e": 29372, "s": 27646, "text": null }, { "code": "// Java implementation for the above approach//include \"bits/stdJava.h\"import java.util.*; class GFG{ // Function to check if it is possible// to reach the bottom right of the grid// from top left using atmost K movesstatic String canReach(char[][] grid, int K){ int N = grid.length; int M = grid[0].length; // Stores the DP states int[][] dp = new int[N][M]; for(int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { dp[i][j] = Integer.MAX_VALUE; } } // if first cell or last cell is blocked then // not possible if(grid[0][0] != '.' || grid[N - 1][M - 1] != '.') return \"No\"; // Initial condition dp[0][0] = 0; // Initializing the DP table // in 1st row for (int i = 1; i < M; i++) { if (grid[0][i] == '.') { dp[0][i] = 1 + dp[0][i - 1]; } else break; } // Initializing the DP table // in 1st column for (int i = 1; i < N; i++) { if (grid[i][0] == '.') { dp[i][0] = 1 + dp[i - 1][0]; } else break; } // Iterate through the grid for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i][j] == '.') { dp[i][j] = Math.min( dp[i][j], 1 + Math.min(dp[i - 1][j], dp[i][j - 1])); } } } // Return answer return (dp[N - 1][M - 1] <= K ? \"Yes\" : \"No\");} // Driver Codepublic static void main(String[] args){ char[][] grid = { { '.', '.', '.' }, { '#', '.', '.' }, { '#', '#', '.' } }; int K = 4; System.out.print(canReach(grid, K));}} // This code is contributed by 29AjayKumar", "e": 31242, "s": 29372, "text": null }, { "code": "# Python3 implementation for the above approachINT_MAX = 2147483647 # Function to check if it is possible# to reach the bottom right of the grid# from top left using atmost K movesdef canReach(grid, K): N = len(grid) M = len(grid[0]) # Stores the DP states dp = [[INT_MAX for _ in range(M)] for _ in range(N)] # if first cell or last cell is blocked then # not possible if(grid[0][0] != '.' or grid[N - 1][M - 1] != '.'): return(\"No\") # Initial condition dp[0][0] = 0 # Initializing the DP table # in 1st row for i in range(1, M): if (grid[0][i] == '.'): dp[0][i] = 1 + dp[0][i - 1] else: break # Initializing the DP table # in 1st column for i in range(1, N): if (grid[i][0] == '.'): dp[i][0] = 1 + dp[i - 1][0] else: break # Iterate through the grid for i in range(1, N): for j in range(1, M): # If current position # is not an obstacle, # update the dp state if (grid[i][j] == '.'): dp[i][j] = min(dp[i][j], 1 + min(dp[i - 1][j], dp[i][j - 1])) # Return answer if dp[N - 1][M - 1] <= K: return(\"Yes\") else: return(\"No\") # Driver Codeif __name__ == \"__main__\": grid = [ [ '.', '.', '.' ], [ '#', '.', '.' ], [ '#', '#', '.' ] ] K = 4 print(canReach(grid, K)) # This code is contributed by rakeshsahni", "e": 32798, "s": 31242, "text": null }, { "code": "// C# implementation for the above approach//include \"bits/stdJava.h\"using System; class GFG{ // Function to check if it is possible// to reach the bottom right of the grid// from top left using atmost K movesstatic String canReach(char[,] grid, int K){ int N = grid.GetLength(0); int M = grid.GetLength(1); // Stores the DP states int[,] dp = new int[N,M]; for(int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { dp[i, j] = int.MaxValue; } } // if first cell or last cell is blocked then // not possible if(grid[0, 0] != '.' || grid[N - 1, M - 1] != '.') return \"No\"; // Initial condition dp[0, 0] = 0; // Initializing the DP table // in 1st row for (int i = 1; i < M; i++) { if (grid[0, i] == '.') { dp[0, i] = 1 + dp[0, i - 1]; } else break; } // Initializing the DP table // in 1st column for (int i = 1; i < N; i++) { if (grid[i, 0] == '.') { dp[i, 0] = 1 + dp[i - 1, 0]; } else break; } // Iterate through the grid for (int i = 1; i < N; i++) { for (int j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i, j] == '.') { dp[i, j] = Math.Min( dp[i, j], 1 + Math.Min(dp[i - 1, j], dp[i, j - 1])); } } } // Return answer return (dp[N - 1, M - 1] <= K ? \"Yes\" : \"No\");} // Driver Codepublic static void Main(){ char[,] grid = { { '.', '.', '.' }, { '/', '.', '.' }, { '/', '/', '.' } }; int K = 4; Console.Write(canReach(grid, K));}} // This code is contributed by Saurabh jaiswal", "e": 34650, "s": 32798, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to check if it is possible // to reach the bottom right of the grid // from top left using atmost K moves function canReach(grid, K) { let N = grid.length; let M = grid[0].length; // Stores the DP states let dp = new Array(N); for (let i = 0; i < dp.length; i++) { dp[i] = new Array(M).fill(Number.MAX_VALUE); } // if first cell or last cell is blocked then // not possible if(grid[0][0] != '.' || grid[N - 1][M - 1] != '.') return \"No\"; // Initial condition dp[0][0] = 0; // Initializing the DP table // in 1st row for (let i = 1; i < M; i++) { if (grid[0][i] == '.') { dp[0][i] = 1 + dp[0][i - 1]; } else break; } // Initializing the DP table // in 1st column for (let i = 1; i < N; i++) { if (grid[i][0] == '.') { dp[i][0] = 1 + dp[i - 1][0]; } else break; } // Iterate through the grid for (let i = 1; i < N; i++) { for (let j = 1; j < M; j++) { // If current position // is not an obstacle, // update the dp state if (grid[i][j] == '.') { dp[i][j] = Math.min( dp[i][j], 1 + Math.min(dp[i - 1][j], dp[i][j - 1])); } } } // Return answer return (dp[N - 1][M - 1] <= K ? \"Yes\" : \"No\"); } // Driver Code let grid = [['.', '.', '.'], ['#', '.', '.'], ['#', '#', '.']]; let K = 4; document.write(canReach(grid, K)); // This code is contributed by Potta Lokesh </script>", "e": 36783, "s": 34650, "text": null }, { "code": null, "e": 36787, "s": 36783, "text": "Yes" }, { "code": null, "e": 36838, "s": 36787, "text": "Time Complexity: O(N * M)Auxiliary Space: O(N * M)" }, { "code": null, "e": 36852, "s": 36838, "text": "lokeshpotta20" }, { "code": null, "e": 36864, "s": 36852, "text": "rakeshsahni" }, { "code": null, "e": 36876, "s": 36864, "text": "29AjayKumar" }, { "code": null, "e": 36893, "s": 36876, "text": "_saurabh_jaiswal" }, { "code": null, "e": 36910, "s": 36893, "text": "harendrakumar123" }, { "code": null, "e": 36919, "s": 36910, "text": "D-E-Shaw" }, { "code": null, "e": 36927, "s": 36919, "text": "DE Shaw" }, { "code": null, "e": 36947, "s": 36927, "text": "Dynamic Programming" }, { "code": null, "e": 36954, "s": 36947, "text": "Matrix" }, { "code": null, "e": 36963, "s": 36954, "text": "D-E-Shaw" }, { "code": null, "e": 36971, "s": 36963, "text": "DE Shaw" }, { "code": null, "e": 36991, "s": 36971, "text": "Dynamic Programming" }, { "code": null, "e": 36998, "s": 36991, "text": "Matrix" }, { "code": null, "e": 37096, "s": 36998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37139, "s": 37096, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 37199, "s": 37139, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 37234, "s": 37199, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 37255, "s": 37234, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 37311, "s": 37255, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 37355, "s": 37311, "text": "Program to find largest element in an array" }, { "code": null, "e": 37391, "s": 37355, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 37422, "s": 37391, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 37465, "s": 37422, "text": "Maximum size square sub-matrix with all 1s" } ]
Python GUI - tkinter - GeeksforGeeks
07 Jan, 2020 Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.To create a tkinter app: Importing the module – tkinterCreate the main window (container)Add any number of widgets to the main windowApply the event Trigger on the widgets. Importing the module – tkinter Create the main window (container) Add any number of widgets to the main window Apply the event Trigger on the widgets. Importing tkinter is same as importing any other module in the Python code. Note that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’. import tkinter There are two main methods used which the user needs to remember while creating the Python application with GUI. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:m=tkinter.Tk() where m is the name of the main window objectmainloop(): There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event as long as the window is not closed.m.mainloop()import tkinterm = tkinter.Tk()'''widgets are added here'''m.mainloop() Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:m=tkinter.Tk() where m is the name of the main window object m=tkinter.Tk() where m is the name of the main window object mainloop(): There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event as long as the window is not closed.m.mainloop()import tkinterm = tkinter.Tk()'''widgets are added here'''m.mainloop() m.mainloop() import tkinterm = tkinter.Tk()'''widgets are added here'''m.mainloop() tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the parent windows. There are mainly three geometry manager classes class. pack() method:It organizes the widgets in blocks before placing in the parent widget.grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget.place() method:It organizes the widgets by placing them on specific positions directed by the programmer. pack() method:It organizes the widgets in blocks before placing in the parent widget. grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget. place() method:It organizes the widgets by placing them on specific positions directed by the programmer. There are a number of widgets which you can put in your tkinter application. Some of the major widgets are explained below: Button:To add a button in your application, this widget is used.The general syntax is:w=Button(master, option=value)master is the parameter used to represent the parent window.There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when button is under the cursor.activeforeground: to set the foreground color when button is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height: to set the height of the button.import tkinter as tkr = tk.Tk()r.title('Counting Seconds')button = tk.Button(r, text='Stop', width=25, command=r.destroy)button.pack()r.mainloop()Output:Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.The general syntax is:w = Canvas(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used in the canvas.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *master = Tk()w = Canvas(master, width=40, height=60)w.pack()canvas_height=20canvas_width=200y = int(canvas_height / 2)w.create_line(0, y, canvas_width, y )mainloop()Output:CheckButton: To select any number of options by displaying a number of options to a user as toggle buttons. The general syntax is:w = CheckButton(master, option=value)There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.Title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import *master = Tk()var1 = IntVar()Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)var2 = IntVar()Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)mainloop()Output:Entry:It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.The general syntax is:w=Entry(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.command: to call a function.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the button.height: to set the height of the button.from tkinter import *master = Tk()Label(master, text='First Name').grid(row=0)Label(master, text='Last Name').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop()Output:Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The general syntax is:w = Frame(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * root = Tk()frame = Frame(root)frame.pack()bottomframe = Frame(root)bottomframe.pack( side = BOTTOM )redbutton = Button(frame, text = 'Red', fg ='red')redbutton.pack( side = LEFT)greenbutton = Button(frame, text = 'Brown', fg='brown')greenbutton.pack( side = LEFT )bluebutton = Button(frame, text ='Blue', fg ='blue')bluebutton.pack( side = LEFT )blackbutton = Button(bottomframe, text ='Black', fg ='black')blackbutton.pack( side = BOTTOM)root.mainloop()Output:Label: It refers to the display box where you can put any text or image which can be updated any time as per the code.The general syntax is:w=Label(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bg to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height” to set the height of the button.from tkinter import *root = Tk()w = Label(root, text='GeeksForGeeks.org!')w.pack()root.mainloop()Output:Listbox: It offers a list to the user from which the user can accept any number of options.The general syntax is:w = Listbox(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bg: to set he normal background color.bd: to set the border width in pixels.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * top = Tk()Lb = Listbox(top)Lb.insert(1, 'Python')Lb.insert(2, 'Java')Lb.insert(3, 'C++')Lb.insert(4, 'Any other')Lb.pack()top.mainloop()Output:MenuButton: It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is:w = MenuButton(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: To set the background when mouse is over the widget.activeforeground: To set the foreground when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.highlightcolor: To set the color of the focus highlight when widget has to be focused.from tkinter import * top = Tk()mb = Menubutton ( top, text = "GfG")mb.grid()mb.menu = Menu ( mb, tearoff = 0 )mb["menu"] = mb.menucVar = IntVar()aVar = IntVar()mb.menu.add_checkbutton ( label ='Contact', variable = cVar )mb.menu.add_checkbutton ( label = 'About', variable = aVar )mb.pack()top.mainloop()Output:Menu: It is used to create all kinds of menus used by the application.The general syntax is:w = Menu(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import * root = Tk()menu = Menu(root)root.config(menu=menu)filemenu = Menu(menu)menu.add_cascade(label='File', menu=filemenu)filemenu.add_command(label='New')filemenu.add_command(label='Open...')filemenu.add_separator()filemenu.add_command(label='Exit', command=root.quit)helpmenu = Menu(menu)menu.add_cascade(label='Help', menu=helpmenu)helpmenu.add_command(label='About')mainloop()Output:Message: It refers to the multi-line and non-editable text. It works same as that of Label.The general syntax is:w = Message(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border around the indicator.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *main = Tk()ourMessage ='This is our Message'messageVar = Message(main, text = ourMessage)messageVar.config(bg='lightgreen')messageVar.pack( )main.mainloop( )Output:RadioButton: It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option.The general syntax is:w = RadioButton(master, option=value) There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the label in characters.height: to set the height of the label in characters.from tkinter import *root = Tk()v = IntVar()Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)mainloop()Output:Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is:w = Scale(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.cursor: To change the cursor pattern when the mouse is over the widget.activebackground: To set the background of the widget when mouse is over the widget.bg: to set he normal background color.orient: Set it to HORIZONTAL or VERTICAL according to the requirement.from_: To set the value of one end of the scale range.to: To set the value of the other end of the scale range.image: to set the image on the widget.width: to set the width of the widget.from tkinter import *master = Tk()w = Scale(master, from_=0, to=42)w.pack()w = Scale(master, from_=0, to=200, orient=HORIZONTAL)w.pack()mainloop()Output:Scrollbar: It refers to the slide controller which will be used to implement listed widgets.The general syntax is:w = Scrollbar(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.from tkinter import *root = Tk()scrollbar = Scrollbar(root)scrollbar.pack( side = RIGHT, fill = Y )mylist = Listbox(root, yscrollcommand = scrollbar.set )for line in range(100): mylist.insert(END, 'This is line number' + str(line))mylist.pack( side = LEFT, fill = BOTH )scrollbar.config( command = mylist.yview )mainloop()Output:Text: To edit a multi-line text and format the way it has to be displayed.The general syntax is:w =Text(master, option=value) There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.insertbackground: To set the background of the widget.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()T = Text(root, height=2, width=30)T.pack()T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n')mainloop()Output:TopLevel: This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is:w = TopLevel(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()root.title('GfG')top = Toplevel()top.title('Python')top.mainloop()Output:SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The general syntax is:w = SpinBox(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.command: To call a function.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.disabledbackground: To disable the background when mouse is over the widget.from_: To set the value of one end of the range.to: To set the value of the other end of the range.from tkinter import *master = Tk()w = Spinbox(master, from_ = 0, to = 10)w.pack()mainloop()Output:PannedWindowIt is a container widget which is used to handle number of panes arranged in it. The general syntax is:w = PannedWindow(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *m1 = PanedWindow()m1.pack(fill = BOTH, expand = 1)left = Entry(m1, bd = 5)m1.add(left)m2 = PanedWindow(m1, orient = VERTICAL)m1.add(m2)top = Scale( m2, orient = HORIZONTAL)m2.add(top)mainloop()Output: Button:To add a button in your application, this widget is used.The general syntax is:w=Button(master, option=value)master is the parameter used to represent the parent window.There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when button is under the cursor.activeforeground: to set the foreground color when button is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height: to set the height of the button.import tkinter as tkr = tk.Tk()r.title('Counting Seconds')button = tk.Button(r, text='Stop', width=25, command=r.destroy)button.pack()r.mainloop()Output: w=Button(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below. activebackground: to set the background color when button is under the cursor. activeforeground: to set the foreground color when button is under the cursor. bg: to set he normal background color. command: to call a function. font: to set the font on the button label. image: to set the image on the button. width: to set the width of the button. height: to set the height of the button. import tkinter as tkr = tk.Tk()r.title('Counting Seconds')button = tk.Button(r, text='Stop', width=25, command=r.destroy)button.pack()r.mainloop() Output: Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.The general syntax is:w = Canvas(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used in the canvas.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *master = Tk()w = Canvas(master, width=40, height=60)w.pack()canvas_height=20canvas_width=200y = int(canvas_height / 2)w.create_line(0, y, canvas_width, y )mainloop()Output: w = Canvas(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bd: to set the border width in pixels. bg: to set the normal background color. cursor: to set the cursor used in the canvas. highlightcolor: to set the color shown in the focus highlight. width: to set the width of the widget. height: to set the height of the widget. from tkinter import *master = Tk()w = Canvas(master, width=40, height=60)w.pack()canvas_height=20canvas_width=200y = int(canvas_height / 2)w.create_line(0, y, canvas_width, y )mainloop() Output: CheckButton: To select any number of options by displaying a number of options to a user as toggle buttons. The general syntax is:w = CheckButton(master, option=value)There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.Title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import *master = Tk()var1 = IntVar()Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)var2 = IntVar()Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)mainloop()Output: w = CheckButton(master, option=value) There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. Title: To set the title of the widget. activebackground: to set the background color when widget is under the cursor. activeforeground: to set the foreground color when widget is under the cursor. bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color. Break Secret Code: Attach a File:nd color. command: to call a function. font: to set the font on the button label. image: to set the image on the widget. from tkinter import *master = Tk()var1 = IntVar()Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)var2 = IntVar()Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)mainloop() Output: Entry:It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.The general syntax is:w=Entry(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.command: to call a function.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the button.height: to set the height of the button.from tkinter import *master = Tk()Label(master, text='First Name').grid(row=0)Label(master, text='Last Name').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop()Output: w=Entry(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bd: to set the border width in pixels. bg: to set the normal background color. cursor: to set the cursor used. command: to call a function. highlightcolor: to set the color shown in the focus highlight. width: to set the width of the button. height: to set the height of the button. from tkinter import *master = Tk()Label(master, text='First Name').grid(row=0)Label(master, text='Last Name').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop() Output: Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The general syntax is:w = Frame(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * root = Tk()frame = Frame(root)frame.pack()bottomframe = Frame(root)bottomframe.pack( side = BOTTOM )redbutton = Button(frame, text = 'Red', fg ='red')redbutton.pack( side = LEFT)greenbutton = Button(frame, text = 'Brown', fg='brown')greenbutton.pack( side = LEFT )bluebutton = Button(frame, text ='Blue', fg ='blue')bluebutton.pack( side = LEFT )blackbutton = Button(bottomframe, text ='Black', fg ='black')blackbutton.pack( side = BOTTOM)root.mainloop()Output: w = Frame(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. highlightcolor: To set the color of the focus highlight when widget has to be focused. bd: to set the border width in pixels. bg: to set the normal background color. cursor: to set the cursor used. width: to set the width of the widget. height: to set the height of the widget. from tkinter import * root = Tk()frame = Frame(root)frame.pack()bottomframe = Frame(root)bottomframe.pack( side = BOTTOM )redbutton = Button(frame, text = 'Red', fg ='red')redbutton.pack( side = LEFT)greenbutton = Button(frame, text = 'Brown', fg='brown')greenbutton.pack( side = LEFT )bluebutton = Button(frame, text ='Blue', fg ='blue')bluebutton.pack( side = LEFT )blackbutton = Button(bottomframe, text ='Black', fg ='black')blackbutton.pack( side = BOTTOM)root.mainloop() Output: Label: It refers to the display box where you can put any text or image which can be updated any time as per the code.The general syntax is:w=Label(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bg to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height” to set the height of the button.from tkinter import *root = Tk()w = Label(root, text='GeeksForGeeks.org!')w.pack()root.mainloop()Output: w=Label(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bg: to set he normal background color. bg to set he normal background color. command: to call a function. font: to set the font on the button label. image: to set the image on the button. width: to set the width of the button. height” to set the height of the button. from tkinter import *root = Tk()w = Label(root, text='GeeksForGeeks.org!')w.pack()root.mainloop() Output: Listbox: It offers a list to the user from which the user can accept any number of options.The general syntax is:w = Listbox(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bg: to set he normal background color.bd: to set the border width in pixels.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * top = Tk()Lb = Listbox(top)Lb.insert(1, 'Python')Lb.insert(2, 'Java')Lb.insert(3, 'C++')Lb.insert(4, 'Any other')Lb.pack()top.mainloop()Output: w = Listbox(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. highlightcolor: To set the color of the focus highlight when widget has to be focused. bg: to set he normal background color. bd: to set the border width in pixels. font: to set the font on the button label. image: to set the image on the widget. width: to set the width of the widget. height: to set the height of the widget. from tkinter import * top = Tk()Lb = Listbox(top)Lb.insert(1, 'Python')Lb.insert(2, 'Java')Lb.insert(3, 'C++')Lb.insert(4, 'Any other')Lb.pack()top.mainloop() Output: MenuButton: It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is:w = MenuButton(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: To set the background when mouse is over the widget.activeforeground: To set the foreground when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.highlightcolor: To set the color of the focus highlight when widget has to be focused.from tkinter import * top = Tk()mb = Menubutton ( top, text = "GfG")mb.grid()mb.menu = Menu ( mb, tearoff = 0 )mb["menu"] = mb.menucVar = IntVar()aVar = IntVar()mb.menu.add_checkbutton ( label ='Contact', variable = cVar )mb.menu.add_checkbutton ( label = 'About', variable = aVar )mb.pack()top.mainloop()Output: w = MenuButton(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. activebackground: To set the background when mouse is over the widget. activeforeground: To set the foreground when mouse is over the widget. bg: to set he normal background color. bd: to set the size of border around the indicator. cursor: To appear the cursor when the mouse over the menubutton. image: to set the image on the widget. width: to set the width of the widget. height: to set the height of the widget. highlightcolor: To set the color of the focus highlight when widget has to be focused. from tkinter import * top = Tk()mb = Menubutton ( top, text = "GfG")mb.grid()mb.menu = Menu ( mb, tearoff = 0 )mb["menu"] = mb.menucVar = IntVar()aVar = IntVar()mb.menu.add_checkbutton ( label ='Contact', variable = cVar )mb.menu.add_checkbutton ( label = 'About', variable = aVar )mb.pack()top.mainloop() Output: Menu: It is used to create all kinds of menus used by the application.The general syntax is:w = Menu(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import * root = Tk()menu = Menu(root)root.config(menu=menu)filemenu = Menu(menu)menu.add_cascade(label='File', menu=filemenu)filemenu.add_command(label='New')filemenu.add_command(label='Open...')filemenu.add_separator()filemenu.add_command(label='Exit', command=root.quit)helpmenu = Menu(menu)menu.add_cascade(label='Help', menu=helpmenu)helpmenu.add_command(label='About')mainloop()Output: w = Menu(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. title: To set the title of the widget. activebackground: to set the background color when widget is under the cursor. activeforeground: to set the foreground color when widget is under the cursor. bg: to set he normal background color. command: to call a function. font: to set the font on the button label. image: to set the image on the widget. from tkinter import * root = Tk()menu = Menu(root)root.config(menu=menu)filemenu = Menu(menu)menu.add_cascade(label='File', menu=filemenu)filemenu.add_command(label='New')filemenu.add_command(label='Open...')filemenu.add_separator()filemenu.add_command(label='Exit', command=root.quit)helpmenu = Menu(menu)menu.add_cascade(label='Help', menu=helpmenu)helpmenu.add_command(label='About')mainloop() Output: Message: It refers to the multi-line and non-editable text. It works same as that of Label.The general syntax is:w = Message(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border around the indicator.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *main = Tk()ourMessage ='This is our Message'messageVar = Message(main, text = ourMessage)messageVar.config(bg='lightgreen')messageVar.pack( )main.mainloop( )Output: w = Message(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bd: to set the border around the indicator. bg: to set he normal background color. font: to set the font on the button label. image: to set the image on the widget. width: to set the width of the widget. height: to set the height of the widget. from tkinter import *main = Tk()ourMessage ='This is our Message'messageVar = Message(main, text = ourMessage)messageVar.config(bg='lightgreen')messageVar.pack( )main.mainloop( ) Output: RadioButton: It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option.The general syntax is:w = RadioButton(master, option=value) There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the label in characters.height: to set the height of the label in characters.from tkinter import *root = Tk()v = IntVar()Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)mainloop()Output: w = RadioButton(master, option=value) There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. activebackground: to set the background color when widget is under the cursor. activeforeground: to set the foreground color when widget is under the cursor. bg: to set he normal background color. command: to call a function. font: to set the font on the button label. image: to set the image on the widget. width: to set the width of the label in characters. height: to set the height of the label in characters. from tkinter import *root = Tk()v = IntVar()Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)mainloop() Output: Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is:w = Scale(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.cursor: To change the cursor pattern when the mouse is over the widget.activebackground: To set the background of the widget when mouse is over the widget.bg: to set he normal background color.orient: Set it to HORIZONTAL or VERTICAL according to the requirement.from_: To set the value of one end of the scale range.to: To set the value of the other end of the scale range.image: to set the image on the widget.width: to set the width of the widget.from tkinter import *master = Tk()w = Scale(master, from_=0, to=42)w.pack()w = Scale(master, from_=0, to=200, orient=HORIZONTAL)w.pack()mainloop()Output: w = Scale(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. cursor: To change the cursor pattern when the mouse is over the widget. activebackground: To set the background of the widget when mouse is over the widget. bg: to set he normal background color. orient: Set it to HORIZONTAL or VERTICAL according to the requirement. from_: To set the value of one end of the scale range. to: To set the value of the other end of the scale range. image: to set the image on the widget. width: to set the width of the widget. from tkinter import *master = Tk()w = Scale(master, from_=0, to=42)w.pack()w = Scale(master, from_=0, to=200, orient=HORIZONTAL)w.pack()mainloop() Output: Scrollbar: It refers to the slide controller which will be used to implement listed widgets.The general syntax is:w = Scrollbar(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.from tkinter import *root = Tk()scrollbar = Scrollbar(root)scrollbar.pack( side = RIGHT, fill = Y )mylist = Listbox(root, yscrollcommand = scrollbar.set )for line in range(100): mylist.insert(END, 'This is line number' + str(line))mylist.pack( side = LEFT, fill = BOTH )scrollbar.config( command = mylist.yview )mainloop()Output: w = Scrollbar(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. width: to set the width of the widget. activebackground: To set the background when mouse is over the widget. bg: to set he normal background color. bd: to set the size of border around the indicator. cursor: To appear the cursor when the mouse over the menubutton. from tkinter import *root = Tk()scrollbar = Scrollbar(root)scrollbar.pack( side = RIGHT, fill = Y )mylist = Listbox(root, yscrollcommand = scrollbar.set )for line in range(100): mylist.insert(END, 'This is line number' + str(line))mylist.pack( side = LEFT, fill = BOTH )scrollbar.config( command = mylist.yview )mainloop() Output: Text: To edit a multi-line text and format the way it has to be displayed.The general syntax is:w =Text(master, option=value) There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.insertbackground: To set the background of the widget.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()T = Text(root, height=2, width=30)T.pack()T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n')mainloop()Output: w =Text(master, option=value) There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below. highlightcolor: To set the color of the focus highlight when widget has to be focused. insertbackground: To set the background of the widget. bg: to set he normal background color. font: to set the font on the button label. image: to set the image on the widget. width: to set the width of the widget. height: to set the height of the widget. from tkinter import *root = Tk()T = Text(root, height=2, width=30)T.pack()T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n')mainloop() Output: TopLevel: This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is:w = TopLevel(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()root.title('GfG')top = Toplevel()top.title('Python')top.mainloop()Output: w = TopLevel(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bg: to set he normal background color. bd: to set the size of border around the indicator. cursor: To appear the cursor when the mouse over the menubutton. width: to set the width of the widget. height: to set the height of the widget. from tkinter import *root = Tk()root.title('GfG')top = Toplevel()top.title('Python')top.mainloop() Output: SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The general syntax is:w = SpinBox(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.command: To call a function.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.disabledbackground: To disable the background when mouse is over the widget.from_: To set the value of one end of the range.to: To set the value of the other end of the range.from tkinter import *master = Tk()w = Spinbox(master, from_ = 0, to = 10)w.pack()mainloop()Output: w = SpinBox(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bg: to set he normal background color. bd: to set the size of border around the indicator. cursor: To appear the cursor when the mouse over the menubutton. command: To call a function. width: to set the width of the widget. activebackground: To set the background when mouse is over the widget. disabledbackground: To disable the background when mouse is over the widget. from_: To set the value of one end of the range. to: To set the value of the other end of the range. from tkinter import *master = Tk()w = Spinbox(master, from_ = 0, to = 10)w.pack()mainloop() Output: PannedWindowIt is a container widget which is used to handle number of panes arranged in it. The general syntax is:w = PannedWindow(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *m1 = PanedWindow()m1.pack(fill = BOTH, expand = 1)left = Entry(m1, bd = 5)m1.add(left)m2 = PanedWindow(m1, orient = VERTICAL)m1.add(m2)top = Scale( m2, orient = HORIZONTAL)m2.add(top)mainloop()Output: w = PannedWindow(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bg: to set he normal background color. bd: to set the size of border around the indicator. cursor: To appear the cursor when the mouse over the menubutton. width: to set the width of the widget. height: to set the height of the widget. from tkinter import *m1 = PanedWindow()m1.pack(fill = BOTH, expand = 1)left = Entry(m1, bd = 5)m1.add(left)m2 = PanedWindow(m1, orient = VERTICAL)m1.add(m2)top = Scale( m2, orient = HORIZONTAL)m2.add(top)mainloop() Output: This article is contributed by Rishabh Bansal. 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. abdurrahmaanjanhangeer Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe 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 Check if element exists in list in Python
[ { "code": null, "e": 25635, "s": 25607, "text": "\n07 Jan, 2020" }, { "code": null, "e": 26013, "s": 25635, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.To create a tkinter app:" }, { "code": null, "e": 26161, "s": 26013, "text": "Importing the module – tkinterCreate the main window (container)Add any number of widgets to the main windowApply the event Trigger on the widgets." }, { "code": null, "e": 26192, "s": 26161, "text": "Importing the module – tkinter" }, { "code": null, "e": 26227, "s": 26192, "text": "Create the main window (container)" }, { "code": null, "e": 26272, "s": 26227, "text": "Add any number of widgets to the main window" }, { "code": null, "e": 26312, "s": 26272, "text": "Apply the event Trigger on the widgets." }, { "code": null, "e": 26483, "s": 26312, "text": "Importing tkinter is same as importing any other module in the Python code. Note that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’." }, { "code": null, "e": 26499, "s": 26483, "text": "import tkinter\n" }, { "code": null, "e": 26612, "s": 26499, "text": "There are two main methods used which the user needs to remember while creating the Python application with GUI." }, { "code": null, "e": 27336, "s": 26612, "text": "Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:m=tkinter.Tk() where m is the name of the main window objectmainloop(): There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event as long as the window is not closed.m.mainloop()import tkinterm = tkinter.Tk()'''widgets are added here'''m.mainloop()" }, { "code": null, "e": 27727, "s": 27336, "text": "Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:m=tkinter.Tk() where m is the name of the main window object" }, { "code": null, "e": 27788, "s": 27727, "text": "m=tkinter.Tk() where m is the name of the main window object" }, { "code": null, "e": 28122, "s": 27788, "text": "mainloop(): There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event as long as the window is not closed.m.mainloop()import tkinterm = tkinter.Tk()'''widgets are added here'''m.mainloop()" }, { "code": null, "e": 28135, "s": 28122, "text": "m.mainloop()" }, { "code": "import tkinterm = tkinter.Tk()'''widgets are added here'''m.mainloop()", "e": 28206, "s": 28135, "text": null }, { "code": null, "e": 28388, "s": 28206, "text": "tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the parent windows. There are mainly three geometry manager classes class." }, { "code": null, "e": 28685, "s": 28388, "text": "pack() method:It organizes the widgets in blocks before placing in the parent widget.grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget.place() method:It organizes the widgets by placing them on specific positions directed by the programmer." }, { "code": null, "e": 28771, "s": 28685, "text": "pack() method:It organizes the widgets in blocks before placing in the parent widget." }, { "code": null, "e": 28878, "s": 28771, "text": "grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget." }, { "code": null, "e": 28984, "s": 28878, "text": "place() method:It organizes the widgets by placing them on specific positions directed by the programmer." }, { "code": null, "e": 29108, "s": 28984, "text": "There are a number of widgets which you can put in your tkinter application. Some of the major widgets are explained below:" }, { "code": null, "e": 44767, "s": 29108, "text": "Button:To add a button in your application, this widget is used.The general syntax is:w=Button(master, option=value)master is the parameter used to represent the parent window.There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when button is under the cursor.activeforeground: to set the foreground color when button is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height: to set the height of the button.import tkinter as tkr = tk.Tk()r.title('Counting Seconds')button = tk.Button(r, text='Stop', width=25, command=r.destroy)button.pack()r.mainloop()Output:Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.The general syntax is:w = Canvas(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used in the canvas.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *master = Tk()w = Canvas(master, width=40, height=60)w.pack()canvas_height=20canvas_width=200y = int(canvas_height / 2)w.create_line(0, y, canvas_width, y )mainloop()Output:CheckButton: To select any number of options by displaying a number of options to a user as toggle buttons. The general syntax is:w = CheckButton(master, option=value)There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.Title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import *master = Tk()var1 = IntVar()Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)var2 = IntVar()Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)mainloop()Output:Entry:It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.The general syntax is:w=Entry(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.command: to call a function.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the button.height: to set the height of the button.from tkinter import *master = Tk()Label(master, text='First Name').grid(row=0)Label(master, text='Last Name').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop()Output:Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The general syntax is:w = Frame(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * root = Tk()frame = Frame(root)frame.pack()bottomframe = Frame(root)bottomframe.pack( side = BOTTOM )redbutton = Button(frame, text = 'Red', fg ='red')redbutton.pack( side = LEFT)greenbutton = Button(frame, text = 'Brown', fg='brown')greenbutton.pack( side = LEFT )bluebutton = Button(frame, text ='Blue', fg ='blue')bluebutton.pack( side = LEFT )blackbutton = Button(bottomframe, text ='Black', fg ='black')blackbutton.pack( side = BOTTOM)root.mainloop()Output:Label: It refers to the display box where you can put any text or image which can be updated any time as per the code.The general syntax is:w=Label(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bg to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height” to set the height of the button.from tkinter import *root = Tk()w = Label(root, text='GeeksForGeeks.org!')w.pack()root.mainloop()Output:Listbox: It offers a list to the user from which the user can accept any number of options.The general syntax is:w = Listbox(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bg: to set he normal background color.bd: to set the border width in pixels.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * top = Tk()Lb = Listbox(top)Lb.insert(1, 'Python')Lb.insert(2, 'Java')Lb.insert(3, 'C++')Lb.insert(4, 'Any other')Lb.pack()top.mainloop()Output:MenuButton: It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is:w = MenuButton(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: To set the background when mouse is over the widget.activeforeground: To set the foreground when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.highlightcolor: To set the color of the focus highlight when widget has to be focused.from tkinter import * top = Tk()mb = Menubutton ( top, text = \"GfG\")mb.grid()mb.menu = Menu ( mb, tearoff = 0 )mb[\"menu\"] = mb.menucVar = IntVar()aVar = IntVar()mb.menu.add_checkbutton ( label ='Contact', variable = cVar )mb.menu.add_checkbutton ( label = 'About', variable = aVar )mb.pack()top.mainloop()Output:Menu: It is used to create all kinds of menus used by the application.The general syntax is:w = Menu(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import * root = Tk()menu = Menu(root)root.config(menu=menu)filemenu = Menu(menu)menu.add_cascade(label='File', menu=filemenu)filemenu.add_command(label='New')filemenu.add_command(label='Open...')filemenu.add_separator()filemenu.add_command(label='Exit', command=root.quit)helpmenu = Menu(menu)menu.add_cascade(label='Help', menu=helpmenu)helpmenu.add_command(label='About')mainloop()Output:Message: It refers to the multi-line and non-editable text. It works same as that of Label.The general syntax is:w = Message(master, option=value)\nmaster is the parameter used to represent the parent window.\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border around the indicator.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *main = Tk()ourMessage ='This is our Message'messageVar = Message(main, text = ourMessage)messageVar.config(bg='lightgreen')messageVar.pack( )main.mainloop( )Output:RadioButton: It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option.The general syntax is:w = RadioButton(master, option=value)\nThere are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the label in characters.height: to set the height of the label in characters.from tkinter import *root = Tk()v = IntVar()Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)mainloop()Output:Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is:w = Scale(master, option=value)\nmaster is the parameter used to represent the parent window.\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.cursor: To change the cursor pattern when the mouse is over the widget.activebackground: To set the background of the widget when mouse is over the widget.bg: to set he normal background color.orient: Set it to HORIZONTAL or VERTICAL according to the requirement.from_: To set the value of one end of the scale range.to: To set the value of the other end of the scale range.image: to set the image on the widget.width: to set the width of the widget.from tkinter import *master = Tk()w = Scale(master, from_=0, to=42)w.pack()w = Scale(master, from_=0, to=200, orient=HORIZONTAL)w.pack()mainloop()Output:Scrollbar: It refers to the slide controller which will be used to implement listed widgets.The general syntax is:w = Scrollbar(master, option=value)\nmaster is the parameter used to represent the parent window.\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.from tkinter import *root = Tk()scrollbar = Scrollbar(root)scrollbar.pack( side = RIGHT, fill = Y )mylist = Listbox(root, yscrollcommand = scrollbar.set )for line in range(100): mylist.insert(END, 'This is line number' + str(line))mylist.pack( side = LEFT, fill = BOTH )scrollbar.config( command = mylist.yview )mainloop()Output:Text: To edit a multi-line text and format the way it has to be displayed.The general syntax is:w =Text(master, option=value)\nThere are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.insertbackground: To set the background of the widget.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()T = Text(root, height=2, width=30)T.pack()T.insert(END, 'GeeksforGeeks\\nBEST WEBSITE\\n')mainloop()Output:TopLevel: This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is:w = TopLevel(master, option=value)\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()root.title('GfG')top = Toplevel()top.title('Python')top.mainloop()Output:SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The general syntax is:w = SpinBox(master, option=value)\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.command: To call a function.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.disabledbackground: To disable the background when mouse is over the widget.from_: To set the value of one end of the range.to: To set the value of the other end of the range.from tkinter import *master = Tk()w = Spinbox(master, from_ = 0, to = 10)w.pack()mainloop()Output:PannedWindowIt is a container widget which is used to handle number of panes arranged in it. The general syntax is:w = PannedWindow(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *m1 = PanedWindow()m1.pack(fill = BOTH, expand = 1)left = Entry(m1, bd = 5)m1.add(left)m2 = PanedWindow(m1, orient = VERTICAL)m1.add(m2)top = Scale( m2, orient = HORIZONTAL)m2.add(top)mainloop()Output:" }, { "code": null, "e": 45654, "s": 44767, "text": "Button:To add a button in your application, this widget is used.The general syntax is:w=Button(master, option=value)master is the parameter used to represent the parent window.There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when button is under the cursor.activeforeground: to set the foreground color when button is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height: to set the height of the button.import tkinter as tkr = tk.Tk()r.title('Counting Seconds')button = tk.Button(r, text='Stop', width=25, command=r.destroy)button.pack()r.mainloop()Output:" }, { "code": null, "e": 45685, "s": 45654, "text": "w=Button(master, option=value)" }, { "code": null, "e": 45923, "s": 45685, "text": "master is the parameter used to represent the parent window.There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 46002, "s": 45923, "text": "activebackground: to set the background color when button is under the cursor." }, { "code": null, "e": 46081, "s": 46002, "text": "activeforeground: to set the foreground color when button is under the cursor." }, { "code": null, "e": 46120, "s": 46081, "text": "bg: to set he normal background color." }, { "code": null, "e": 46149, "s": 46120, "text": "command: to call a function." }, { "code": null, "e": 46192, "s": 46149, "text": "font: to set the font on the button label." }, { "code": null, "e": 46231, "s": 46192, "text": "image: to set the image on the button." }, { "code": null, "e": 46270, "s": 46231, "text": "width: to set the width of the button." }, { "code": null, "e": 46311, "s": 46270, "text": "height: to set the height of the button." }, { "code": "import tkinter as tkr = tk.Tk()r.title('Counting Seconds')button = tk.Button(r, text='Stop', width=25, command=r.destroy)button.pack()r.mainloop()", "e": 46458, "s": 46311, "text": null }, { "code": null, "e": 46466, "s": 46458, "text": "Output:" }, { "code": null, "e": 47306, "s": 46466, "text": "Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.The general syntax is:w = Canvas(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used in the canvas.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *master = Tk()w = Canvas(master, width=40, height=60)w.pack()canvas_height=20canvas_width=200y = int(canvas_height / 2)w.create_line(0, y, canvas_width, y )mainloop()Output:" }, { "code": null, "e": 47400, "s": 47306, "text": "w = Canvas(master, option=value)\nmaster is the parameter used to represent the parent window." }, { "code": null, "e": 47577, "s": 47400, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 47616, "s": 47577, "text": "bd: to set the border width in pixels." }, { "code": null, "e": 47656, "s": 47616, "text": "bg: to set the normal background color." }, { "code": null, "e": 47702, "s": 47656, "text": "cursor: to set the cursor used in the canvas." }, { "code": null, "e": 47765, "s": 47702, "text": "highlightcolor: to set the color shown in the focus highlight." }, { "code": null, "e": 47804, "s": 47765, "text": "width: to set the width of the widget." }, { "code": null, "e": 47845, "s": 47804, "text": "height: to set the height of the widget." }, { "code": "from tkinter import *master = Tk()w = Canvas(master, width=40, height=60)w.pack()canvas_height=20canvas_width=200y = int(canvas_height / 2)w.create_line(0, y, canvas_width, y )mainloop()", "e": 48032, "s": 47845, "text": null }, { "code": null, "e": 48040, "s": 48032, "text": "Output:" }, { "code": null, "e": 48990, "s": 48040, "text": "CheckButton: To select any number of options by displaying a number of options to a user as toggle buttons. The general syntax is:w = CheckButton(master, option=value)There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.Title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import *master = Tk()var1 = IntVar()Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)var2 = IntVar()Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)mainloop()Output:" }, { "code": null, "e": 49028, "s": 48990, "text": "w = CheckButton(master, option=value)" }, { "code": null, "e": 49206, "s": 49028, "text": "There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 49245, "s": 49206, "text": "Title: To set the title of the widget." }, { "code": null, "e": 49324, "s": 49245, "text": "activebackground: to set the background color when widget is under the cursor." }, { "code": null, "e": 49403, "s": 49324, "text": "activeforeground: to set the foreground color when widget is under the cursor." }, { "code": null, "e": 49486, "s": 49403, "text": "bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color." }, { "code": null, "e": 49492, "s": 49486, "text": "Break" }, { "code": null, "e": 49505, "s": 49492, "text": "Secret Code:" }, { "code": null, "e": 49529, "s": 49505, "text": "Attach a File:nd color." }, { "code": null, "e": 49558, "s": 49529, "text": "command: to call a function." }, { "code": null, "e": 49601, "s": 49558, "text": "font: to set the font on the button label." }, { "code": null, "e": 49640, "s": 49601, "text": "image: to set the image on the widget." }, { "code": "from tkinter import *master = Tk()var1 = IntVar()Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)var2 = IntVar()Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)mainloop()", "e": 49855, "s": 49640, "text": null }, { "code": null, "e": 49863, "s": 49855, "text": "Output:" }, { "code": null, "e": 50766, "s": 49863, "text": "Entry:It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.The general syntax is:w=Entry(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.command: to call a function.highlightcolor: to set the color shown in the focus highlight.width: to set the width of the button.height: to set the height of the button.from tkinter import *master = Tk()Label(master, text='First Name').grid(row=0)Label(master, text='Last Name').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop()Output:" }, { "code": null, "e": 50797, "s": 50766, "text": "w=Entry(master, option=value)\n" }, { "code": null, "e": 51034, "s": 50797, "text": "master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 51073, "s": 51034, "text": "bd: to set the border width in pixels." }, { "code": null, "e": 51113, "s": 51073, "text": "bg: to set the normal background color." }, { "code": null, "e": 51145, "s": 51113, "text": "cursor: to set the cursor used." }, { "code": null, "e": 51174, "s": 51145, "text": "command: to call a function." }, { "code": null, "e": 51237, "s": 51174, "text": "highlightcolor: to set the color shown in the focus highlight." }, { "code": null, "e": 51276, "s": 51237, "text": "width: to set the width of the button." }, { "code": null, "e": 51317, "s": 51276, "text": "height: to set the height of the button." }, { "code": "from tkinter import *master = Tk()Label(master, text='First Name').grid(row=0)Label(master, text='Last Name').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop()", "e": 51533, "s": 51317, "text": null }, { "code": null, "e": 51541, "s": 51533, "text": "Output:" }, { "code": null, "e": 52691, "s": 51541, "text": "Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The general syntax is:w = Frame(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bd: to set the border width in pixels.bg: to set the normal background color.cursor: to set the cursor used.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * root = Tk()frame = Frame(root)frame.pack()bottomframe = Frame(root)bottomframe.pack( side = BOTTOM )redbutton = Button(frame, text = 'Red', fg ='red')redbutton.pack( side = LEFT)greenbutton = Button(frame, text = 'Brown', fg='brown')greenbutton.pack( side = LEFT )bluebutton = Button(frame, text ='Blue', fg ='blue')bluebutton.pack( side = LEFT )blackbutton = Button(bottomframe, text ='Black', fg ='black')blackbutton.pack( side = BOTTOM)root.mainloop()Output:" }, { "code": null, "e": 52784, "s": 52691, "text": "w = Frame(master, option=value)\nmaster is the parameter used to represent the parent window." }, { "code": null, "e": 52961, "s": 52784, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 53048, "s": 52961, "text": "highlightcolor: To set the color of the focus highlight when widget has to be focused." }, { "code": null, "e": 53087, "s": 53048, "text": "bd: to set the border width in pixels." }, { "code": null, "e": 53127, "s": 53087, "text": "bg: to set the normal background color." }, { "code": null, "e": 53159, "s": 53127, "text": "cursor: to set the cursor used." }, { "code": null, "e": 53198, "s": 53159, "text": "width: to set the width of the widget." }, { "code": null, "e": 53239, "s": 53198, "text": "height: to set the height of the widget." }, { "code": "from tkinter import * root = Tk()frame = Frame(root)frame.pack()bottomframe = Frame(root)bottomframe.pack( side = BOTTOM )redbutton = Button(frame, text = 'Red', fg ='red')redbutton.pack( side = LEFT)greenbutton = Button(frame, text = 'Brown', fg='brown')greenbutton.pack( side = LEFT )bluebutton = Button(frame, text ='Blue', fg ='blue')bluebutton.pack( side = LEFT )blackbutton = Button(bottomframe, text ='Black', fg ='black')blackbutton.pack( side = BOTTOM)root.mainloop()", "e": 53717, "s": 53239, "text": null }, { "code": null, "e": 53725, "s": 53717, "text": "Output:" }, { "code": null, "e": 54497, "s": 53725, "text": "Label: It refers to the display box where you can put any text or image which can be updated any time as per the code.The general syntax is:w=Label(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bg to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the button.width: to set the width of the button.height” to set the height of the button.from tkinter import *root = Tk()w = Label(root, text='GeeksForGeeks.org!')w.pack()root.mainloop()Output:" }, { "code": null, "e": 54588, "s": 54497, "text": "w=Label(master, option=value)\nmaster is the parameter used to represent the parent window." }, { "code": null, "e": 54765, "s": 54588, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 54804, "s": 54765, "text": "bg: to set he normal background color." }, { "code": null, "e": 54842, "s": 54804, "text": "bg to set he normal background color." }, { "code": null, "e": 54871, "s": 54842, "text": "command: to call a function." }, { "code": null, "e": 54914, "s": 54871, "text": "font: to set the font on the button label." }, { "code": null, "e": 54953, "s": 54914, "text": "image: to set the image on the button." }, { "code": null, "e": 54992, "s": 54953, "text": "width: to set the width of the button." }, { "code": null, "e": 55033, "s": 54992, "text": "height” to set the height of the button." }, { "code": "from tkinter import *root = Tk()w = Label(root, text='GeeksForGeeks.org!')w.pack()root.mainloop()", "e": 55131, "s": 55033, "text": null }, { "code": null, "e": 55139, "s": 55131, "text": "Output:" }, { "code": null, "e": 56009, "s": 55139, "text": "Listbox: It offers a list to the user from which the user can accept any number of options.The general syntax is:w = Listbox(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.bg: to set he normal background color.bd: to set the border width in pixels.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import * top = Tk()Lb = Listbox(top)Lb.insert(1, 'Python')Lb.insert(2, 'Java')Lb.insert(3, 'C++')Lb.insert(4, 'Any other')Lb.pack()top.mainloop()Output:" }, { "code": null, "e": 56104, "s": 56009, "text": "w = Listbox(master, option=value)\nmaster is the parameter used to represent the parent window." }, { "code": null, "e": 56281, "s": 56104, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 56368, "s": 56281, "text": "highlightcolor: To set the color of the focus highlight when widget has to be focused." }, { "code": null, "e": 56407, "s": 56368, "text": "bg: to set he normal background color." }, { "code": null, "e": 56446, "s": 56407, "text": "bd: to set the border width in pixels." }, { "code": null, "e": 56489, "s": 56446, "text": "font: to set the font on the button label." }, { "code": null, "e": 56528, "s": 56489, "text": "image: to set the image on the widget." }, { "code": null, "e": 56567, "s": 56528, "text": "width: to set the width of the widget." }, { "code": null, "e": 56608, "s": 56567, "text": "height: to set the height of the widget." }, { "code": "from tkinter import * top = Tk()Lb = Listbox(top)Lb.insert(1, 'Python')Lb.insert(2, 'Java')Lb.insert(3, 'C++')Lb.insert(4, 'Any other')Lb.pack()top.mainloop()", "e": 56768, "s": 56608, "text": null }, { "code": null, "e": 56776, "s": 56768, "text": "Output:" }, { "code": null, "e": 58012, "s": 56776, "text": "MenuButton: It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is:w = MenuButton(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: To set the background when mouse is over the widget.activeforeground: To set the foreground when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.highlightcolor: To set the color of the focus highlight when widget has to be focused.from tkinter import * top = Tk()mb = Menubutton ( top, text = \"GfG\")mb.grid()mb.menu = Menu ( mb, tearoff = 0 )mb[\"menu\"] = mb.menucVar = IntVar()aVar = IntVar()mb.menu.add_checkbutton ( label ='Contact', variable = cVar )mb.menu.add_checkbutton ( label = 'About', variable = aVar )mb.pack()top.mainloop()Output:" }, { "code": null, "e": 58110, "s": 58012, "text": "w = MenuButton(master, option=value)\nmaster is the parameter used to represent the parent window." }, { "code": null, "e": 58287, "s": 58110, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 58358, "s": 58287, "text": "activebackground: To set the background when mouse is over the widget." }, { "code": null, "e": 58429, "s": 58358, "text": "activeforeground: To set the foreground when mouse is over the widget." }, { "code": null, "e": 58468, "s": 58429, "text": "bg: to set he normal background color." }, { "code": null, "e": 58520, "s": 58468, "text": "bd: to set the size of border around the indicator." }, { "code": null, "e": 58585, "s": 58520, "text": "cursor: To appear the cursor when the mouse over the menubutton." }, { "code": null, "e": 58624, "s": 58585, "text": "image: to set the image on the widget." }, { "code": null, "e": 58663, "s": 58624, "text": "width: to set the width of the widget." }, { "code": null, "e": 58704, "s": 58663, "text": "height: to set the height of the widget." }, { "code": null, "e": 58791, "s": 58704, "text": "highlightcolor: To set the color of the focus highlight when widget has to be focused." }, { "code": "from tkinter import * top = Tk()mb = Menubutton ( top, text = \"GfG\")mb.grid()mb.menu = Menu ( mb, tearoff = 0 )mb[\"menu\"] = mb.menucVar = IntVar()aVar = IntVar()mb.menu.add_checkbutton ( label ='Contact', variable = cVar )mb.menu.add_checkbutton ( label = 'About', variable = aVar )mb.pack()top.mainloop()", "e": 59104, "s": 58791, "text": null }, { "code": null, "e": 59112, "s": 59104, "text": "Output:" }, { "code": null, "e": 60221, "s": 59112, "text": "Menu: It is used to create all kinds of menus used by the application.The general syntax is:w = Menu(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.title: To set the title of the widget.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.from tkinter import * root = Tk()menu = Menu(root)root.config(menu=menu)filemenu = Menu(menu)menu.add_cascade(label='File', menu=filemenu)filemenu.add_command(label='New')filemenu.add_command(label='Open...')filemenu.add_separator()filemenu.add_command(label='Exit', command=root.quit)helpmenu = Menu(menu)menu.add_cascade(label='Help', menu=helpmenu)helpmenu.add_command(label='About')mainloop()Output:" }, { "code": null, "e": 60313, "s": 60221, "text": "w = Menu(master, option=value)\nmaster is the parameter used to represent the parent window." }, { "code": null, "e": 60491, "s": 60313, "text": "There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 60530, "s": 60491, "text": "title: To set the title of the widget." }, { "code": null, "e": 60609, "s": 60530, "text": "activebackground: to set the background color when widget is under the cursor." }, { "code": null, "e": 60688, "s": 60609, "text": "activeforeground: to set the foreground color when widget is under the cursor." }, { "code": null, "e": 60727, "s": 60688, "text": "bg: to set he normal background color." }, { "code": null, "e": 60756, "s": 60727, "text": "command: to call a function." }, { "code": null, "e": 60799, "s": 60756, "text": "font: to set the font on the button label." }, { "code": null, "e": 60838, "s": 60799, "text": "image: to set the image on the widget." }, { "code": "from tkinter import * root = Tk()menu = Menu(root)root.config(menu=menu)filemenu = Menu(menu)menu.add_cascade(label='File', menu=filemenu)filemenu.add_command(label='New')filemenu.add_command(label='Open...')filemenu.add_separator()filemenu.add_command(label='Exit', command=root.quit)helpmenu = Menu(menu)menu.add_cascade(label='Help', menu=helpmenu)helpmenu.add_command(label='About')mainloop()", "e": 61240, "s": 60838, "text": null }, { "code": null, "e": 61248, "s": 61240, "text": "Output:" }, { "code": null, "e": 62057, "s": 61248, "text": "Message: It refers to the multi-line and non-editable text. It works same as that of Label.The general syntax is:w = Message(master, option=value)\nmaster is the parameter used to represent the parent window.\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bd: to set the border around the indicator.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *main = Tk()ourMessage ='This is our Message'messageVar = Message(main, text = ourMessage)messageVar.config(bg='lightgreen')messageVar.pack( )main.mainloop( )Output:" }, { "code": null, "e": 62153, "s": 62057, "text": "w = Message(master, option=value)\nmaster is the parameter used to represent the parent window.\n" }, { "code": null, "e": 62330, "s": 62153, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 62374, "s": 62330, "text": "bd: to set the border around the indicator." }, { "code": null, "e": 62413, "s": 62374, "text": "bg: to set he normal background color." }, { "code": null, "e": 62456, "s": 62413, "text": "font: to set the font on the button label." }, { "code": null, "e": 62495, "s": 62456, "text": "image: to set the image on the widget." }, { "code": null, "e": 62534, "s": 62495, "text": "width: to set the width of the widget." }, { "code": null, "e": 62575, "s": 62534, "text": "height: to set the height of the widget." }, { "code": "from tkinter import *main = Tk()ourMessage ='This is our Message'messageVar = Message(main, text = ourMessage)messageVar.config(bg='lightgreen')messageVar.pack( )main.mainloop( )", "e": 62754, "s": 62575, "text": null }, { "code": null, "e": 62762, "s": 62754, "text": "Output:" }, { "code": null, "e": 63739, "s": 62762, "text": "RadioButton: It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option.The general syntax is:w = RadioButton(master, option=value)\nThere are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.activebackground: to set the background color when widget is under the cursor.activeforeground: to set the foreground color when widget is under the cursor.bg: to set he normal background color.command: to call a function.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the label in characters.height: to set the height of the label in characters.from tkinter import *root = Tk()v = IntVar()Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)mainloop()Output:" }, { "code": null, "e": 63778, "s": 63739, "text": "w = RadioButton(master, option=value)\n" }, { "code": null, "e": 63956, "s": 63778, "text": "There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 64035, "s": 63956, "text": "activebackground: to set the background color when widget is under the cursor." }, { "code": null, "e": 64114, "s": 64035, "text": "activeforeground: to set the foreground color when widget is under the cursor." }, { "code": null, "e": 64153, "s": 64114, "text": "bg: to set he normal background color." }, { "code": null, "e": 64182, "s": 64153, "text": "command: to call a function." }, { "code": null, "e": 64225, "s": 64182, "text": "font: to set the font on the button label." }, { "code": null, "e": 64264, "s": 64225, "text": "image: to set the image on the widget." }, { "code": null, "e": 64316, "s": 64264, "text": "width: to set the width of the label in characters." }, { "code": null, "e": 64370, "s": 64316, "text": "height: to set the height of the label in characters." }, { "code": "from tkinter import *root = Tk()v = IntVar()Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)mainloop()", "e": 64555, "s": 64370, "text": null }, { "code": null, "e": 64563, "s": 64555, "text": "Output:" }, { "code": null, "e": 65555, "s": 64563, "text": "Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is:w = Scale(master, option=value)\nmaster is the parameter used to represent the parent window.\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.cursor: To change the cursor pattern when the mouse is over the widget.activebackground: To set the background of the widget when mouse is over the widget.bg: to set he normal background color.orient: Set it to HORIZONTAL or VERTICAL according to the requirement.from_: To set the value of one end of the scale range.to: To set the value of the other end of the scale range.image: to set the image on the widget.width: to set the width of the widget.from tkinter import *master = Tk()w = Scale(master, from_=0, to=42)w.pack()w = Scale(master, from_=0, to=200, orient=HORIZONTAL)w.pack()mainloop()Output:" }, { "code": null, "e": 65649, "s": 65555, "text": "w = Scale(master, option=value)\nmaster is the parameter used to represent the parent window.\n" }, { "code": null, "e": 65826, "s": 65649, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 65898, "s": 65826, "text": "cursor: To change the cursor pattern when the mouse is over the widget." }, { "code": null, "e": 65983, "s": 65898, "text": "activebackground: To set the background of the widget when mouse is over the widget." }, { "code": null, "e": 66022, "s": 65983, "text": "bg: to set he normal background color." }, { "code": null, "e": 66093, "s": 66022, "text": "orient: Set it to HORIZONTAL or VERTICAL according to the requirement." }, { "code": null, "e": 66148, "s": 66093, "text": "from_: To set the value of one end of the scale range." }, { "code": null, "e": 66206, "s": 66148, "text": "to: To set the value of the other end of the scale range." }, { "code": null, "e": 66245, "s": 66206, "text": "image: to set the image on the widget." }, { "code": null, "e": 66284, "s": 66245, "text": "width: to set the width of the widget." }, { "code": "from tkinter import *master = Tk()w = Scale(master, from_=0, to=42)w.pack()w = Scale(master, from_=0, to=200, orient=HORIZONTAL)w.pack()mainloop()", "e": 66431, "s": 66284, "text": null }, { "code": null, "e": 66439, "s": 66431, "text": "Output:" }, { "code": null, "e": 67419, "s": 66439, "text": "Scrollbar: It refers to the slide controller which will be used to implement listed widgets.The general syntax is:w = Scrollbar(master, option=value)\nmaster is the parameter used to represent the parent window.\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.from tkinter import *root = Tk()scrollbar = Scrollbar(root)scrollbar.pack( side = RIGHT, fill = Y )mylist = Listbox(root, yscrollcommand = scrollbar.set )for line in range(100): mylist.insert(END, 'This is line number' + str(line))mylist.pack( side = LEFT, fill = BOTH )scrollbar.config( command = mylist.yview )mainloop()Output:" }, { "code": null, "e": 67517, "s": 67419, "text": "w = Scrollbar(master, option=value)\nmaster is the parameter used to represent the parent window.\n" }, { "code": null, "e": 67694, "s": 67517, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 67733, "s": 67694, "text": "width: to set the width of the widget." }, { "code": null, "e": 67804, "s": 67733, "text": "activebackground: To set the background when mouse is over the widget." }, { "code": null, "e": 67843, "s": 67804, "text": "bg: to set he normal background color." }, { "code": null, "e": 67895, "s": 67843, "text": "bd: to set the size of border around the indicator." }, { "code": null, "e": 67960, "s": 67895, "text": "cursor: To appear the cursor when the mouse over the menubutton." }, { "code": "from tkinter import *root = Tk()scrollbar = Scrollbar(root)scrollbar.pack( side = RIGHT, fill = Y )mylist = Listbox(root, yscrollcommand = scrollbar.set )for line in range(100): mylist.insert(END, 'This is line number' + str(line))mylist.pack( side = LEFT, fill = BOTH )scrollbar.config( command = mylist.yview )mainloop()", "e": 68285, "s": 67960, "text": null }, { "code": null, "e": 68293, "s": 68285, "text": "Output:" }, { "code": null, "e": 69068, "s": 68293, "text": "Text: To edit a multi-line text and format the way it has to be displayed.The general syntax is:w =Text(master, option=value)\nThere are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.highlightcolor: To set the color of the focus highlight when widget has to be focused.insertbackground: To set the background of the widget.bg: to set he normal background color.font: to set the font on the button label.image: to set the image on the widget.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()T = Text(root, height=2, width=30)T.pack()T.insert(END, 'GeeksforGeeks\\nBEST WEBSITE\\n')mainloop()Output:" }, { "code": null, "e": 69100, "s": 69068, "text": "w =Text(master, option=value)\n" }, { "code": null, "e": 69275, "s": 69100, "text": "There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 69362, "s": 69275, "text": "highlightcolor: To set the color of the focus highlight when widget has to be focused." }, { "code": null, "e": 69417, "s": 69362, "text": "insertbackground: To set the background of the widget." }, { "code": null, "e": 69456, "s": 69417, "text": "bg: to set he normal background color." }, { "code": null, "e": 69499, "s": 69456, "text": "font: to set the font on the button label." }, { "code": null, "e": 69538, "s": 69499, "text": "image: to set the image on the widget." }, { "code": null, "e": 69577, "s": 69538, "text": "width: to set the width of the widget." }, { "code": null, "e": 69618, "s": 69577, "text": "height: to set the height of the widget." }, { "code": "from tkinter import *root = Tk()T = Text(root, height=2, width=30)T.pack()T.insert(END, 'GeeksforGeeks\\nBEST WEBSITE\\n')mainloop()", "e": 69749, "s": 69618, "text": null }, { "code": null, "e": 69757, "s": 69749, "text": "Output:" }, { "code": null, "e": 70438, "s": 69757, "text": "TopLevel: This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is:w = TopLevel(master, option=value)\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *root = Tk()root.title('GfG')top = Toplevel()top.title('Python')top.mainloop()Output:" }, { "code": null, "e": 70474, "s": 70438, "text": "w = TopLevel(master, option=value)\n" }, { "code": null, "e": 70651, "s": 70474, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 70690, "s": 70651, "text": "bg: to set he normal background color." }, { "code": null, "e": 70742, "s": 70690, "text": "bd: to set the size of border around the indicator." }, { "code": null, "e": 70807, "s": 70742, "text": "cursor: To appear the cursor when the mouse over the menubutton." }, { "code": null, "e": 70846, "s": 70807, "text": "width: to set the width of the widget." }, { "code": null, "e": 70887, "s": 70846, "text": "height: to set the height of the widget." }, { "code": "from tkinter import *root = Tk()root.title('GfG')top = Toplevel()top.title('Python')top.mainloop()", "e": 70986, "s": 70887, "text": null }, { "code": null, "e": 70994, "s": 70986, "text": "Output:" }, { "code": null, "e": 71895, "s": 70994, "text": "SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The general syntax is:w = SpinBox(master, option=value)\nThere are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.command: To call a function.width: to set the width of the widget.activebackground: To set the background when mouse is over the widget.disabledbackground: To disable the background when mouse is over the widget.from_: To set the value of one end of the range.to: To set the value of the other end of the range.from tkinter import *master = Tk()w = Spinbox(master, from_ = 0, to = 10)w.pack()mainloop()Output:" }, { "code": null, "e": 71930, "s": 71895, "text": "w = SpinBox(master, option=value)\n" }, { "code": null, "e": 72107, "s": 71930, "text": "There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 72146, "s": 72107, "text": "bg: to set he normal background color." }, { "code": null, "e": 72198, "s": 72146, "text": "bd: to set the size of border around the indicator." }, { "code": null, "e": 72263, "s": 72198, "text": "cursor: To appear the cursor when the mouse over the menubutton." }, { "code": null, "e": 72292, "s": 72263, "text": "command: To call a function." }, { "code": null, "e": 72331, "s": 72292, "text": "width: to set the width of the widget." }, { "code": null, "e": 72402, "s": 72331, "text": "activebackground: To set the background when mouse is over the widget." }, { "code": null, "e": 72479, "s": 72402, "text": "disabledbackground: To disable the background when mouse is over the widget." }, { "code": null, "e": 72528, "s": 72479, "text": "from_: To set the value of one end of the range." }, { "code": null, "e": 72580, "s": 72528, "text": "to: To set the value of the other end of the range." }, { "code": "from tkinter import *master = Tk()w = Spinbox(master, from_ = 0, to = 10)w.pack()mainloop()", "e": 72672, "s": 72580, "text": null }, { "code": null, "e": 72680, "s": 72672, "text": "Output:" }, { "code": null, "e": 73523, "s": 72680, "text": "PannedWindowIt is a container widget which is used to handle number of panes arranged in it. The general syntax is:w = PannedWindow(master, option=value)\nmaster is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.bg: to set he normal background color.bd: to set the size of border around the indicator.cursor: To appear the cursor when the mouse over the menubutton.width: to set the width of the widget.height: to set the height of the widget.from tkinter import *m1 = PanedWindow()m1.pack(fill = BOTH, expand = 1)left = Entry(m1, bd = 5)m1.add(left)m2 = PanedWindow(m1, orient = VERTICAL)m1.add(m2)top = Scale( m2, orient = HORIZONTAL)m2.add(top)mainloop()Output:" }, { "code": null, "e": 73563, "s": 73523, "text": "w = PannedWindow(master, option=value)\n" }, { "code": null, "e": 73800, "s": 73563, "text": "master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below." }, { "code": null, "e": 73839, "s": 73800, "text": "bg: to set he normal background color." }, { "code": null, "e": 73891, "s": 73839, "text": "bd: to set the size of border around the indicator." }, { "code": null, "e": 73956, "s": 73891, "text": "cursor: To appear the cursor when the mouse over the menubutton." }, { "code": null, "e": 73995, "s": 73956, "text": "width: to set the width of the widget." }, { "code": null, "e": 74036, "s": 73995, "text": "height: to set the height of the widget." }, { "code": "from tkinter import *m1 = PanedWindow()m1.pack(fill = BOTH, expand = 1)left = Entry(m1, bd = 5)m1.add(left)m2 = PanedWindow(m1, orient = VERTICAL)m1.add(m2)top = Scale( m2, orient = HORIZONTAL)m2.add(top)mainloop()", "e": 74251, "s": 74036, "text": null }, { "code": null, "e": 74259, "s": 74251, "text": "Output:" }, { "code": null, "e": 74561, "s": 74259, "text": "This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 74686, "s": 74561, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 74709, "s": 74686, "text": "abdurrahmaanjanhangeer" }, { "code": null, "e": 74716, "s": 74709, "text": "Python" }, { "code": null, "e": 74814, "s": 74716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 74832, "s": 74814, "text": "Python Dictionary" }, { "code": null, "e": 74867, "s": 74832, "text": "Read a file line by line in Python" }, { "code": null, "e": 74899, "s": 74867, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 74941, "s": 74899, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 74967, "s": 74941, "text": "Python String | replace()" }, { "code": null, "e": 74996, "s": 74967, "text": "*args and **kwargs in Python" }, { "code": null, "e": 75040, "s": 74996, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 75077, "s": 75040, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 75113, "s": 75077, "text": "Convert integer to string in Python" } ]
scipy stats.normaltest() function | Python - GeeksforGeeks
11 Feb, 2019 scipy.stats.normaltest(array, axis=0) function test whether the sample is different from the normal distribution. This function tests the null hypothesis of the population that the sample was drawn from. Parameters :array : Input array or object having the elements.axis : Axis along which the normal distribution test is to be computed. By default axis = 0. Returns : k2 value and P-value for the hypothesis test on data set. Code #1: # Performing normaltestfrom scipy.stats import normaltestimport numpy as np import pylab as p x1 = np.linspace( -5, 5, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '.') print( '\nNormal test for given data :\n', normaltest(y1)) Output : Normal test for given data : NormaltestResult(statistic=146.08066794511544, pvalue=1.901016994532079e-32) Code #2: # Performing normaltestfrom scipy.stats import normaltestimport numpy as np import pylab as p x1 = np.linspace( -5, 12, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '.') print( '\nNormal test for given data :\n', normaltest(y1)) Output : Normal test for given data : NormaltestResult(statistic=344.05533061429884, pvalue=1.9468577593501764e-75) Python scipy-stats-functions Python-scipy 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 | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 Feb, 2019" }, { "code": null, "e": 25741, "s": 25537, "text": "scipy.stats.normaltest(array, axis=0) function test whether the sample is different from the normal distribution. This function tests the null hypothesis of the population that the sample was drawn from." }, { "code": null, "e": 25896, "s": 25741, "text": "Parameters :array : Input array or object having the elements.axis : Axis along which the normal distribution test is to be computed. By default axis = 0." }, { "code": null, "e": 25964, "s": 25896, "text": "Returns : k2 value and P-value for the hypothesis test on data set." }, { "code": null, "e": 25973, "s": 25964, "text": "Code #1:" }, { "code": "# Performing normaltestfrom scipy.stats import normaltestimport numpy as np import pylab as p x1 = np.linspace( -5, 5, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '.') print( '\\nNormal test for given data :\\n', normaltest(y1))", "e": 26234, "s": 25973, "text": null }, { "code": null, "e": 26243, "s": 26234, "text": "Output :" }, { "code": null, "e": 26353, "s": 26243, "text": "\n\nNormal test for given data :\n NormaltestResult(statistic=146.08066794511544, pvalue=1.901016994532079e-32)\n" }, { "code": null, "e": 26363, "s": 26353, "text": " Code #2:" }, { "code": "# Performing normaltestfrom scipy.stats import normaltestimport numpy as np import pylab as p x1 = np.linspace( -5, 12, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '.') print( '\\nNormal test for given data :\\n', normaltest(y1))", "e": 26625, "s": 26363, "text": null }, { "code": null, "e": 26634, "s": 26625, "text": "Output :" }, { "code": null, "e": 26745, "s": 26634, "text": "\n\nNormal test for given data :\n NormaltestResult(statistic=344.05533061429884, pvalue=1.9468577593501764e-75)\n" }, { "code": null, "e": 26774, "s": 26745, "text": "Python scipy-stats-functions" }, { "code": null, "e": 26787, "s": 26774, "text": "Python-scipy" }, { "code": null, "e": 26794, "s": 26787, "text": "Python" }, { "code": null, "e": 26892, "s": 26794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26924, "s": 26892, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26966, "s": 26924, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27008, "s": 26966, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27064, "s": 27008, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27091, "s": 27064, "text": "Python Classes and Objects" }, { "code": null, "e": 27130, "s": 27091, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27161, "s": 27130, "text": "Python | os.path.join() method" }, { "code": null, "e": 27183, "s": 27161, "text": "Defaultdict in Python" }, { "code": null, "e": 27212, "s": 27183, "text": "Create a directory in Python" } ]
Compare two strings considering only alphanumeric characters - GeeksforGeeks
03 Jun, 2021 Given two strings that can contain lower and uppercase alphabets, numbers and special characters like dots, blank spaces, commas, etc. Compare both strings considering only alphanumeric characters([a-b], [A-B] and [0-9]) if they are equal or not. For example, strings “Ram, Shyam” and “Ram-Shyam” both are the same and also “/.’;[]” and “@# >” are same. Examples: Input: str1 = "Ram, Shyam", str2 = " Ram - Shyam." Output: Equal Explanation: if we ignore all characters except alphanumeric characters then strings will be, str1 = "RamShyam" and str2 = "RamShyam". Therefore both strings are equal. Input : str1 = "aaa123", str2 = "@aaa-12-3" Output : Equal Input : str1 = "abc123", str2 = "123abc" Output : Unequal Explanation: In this, str1 = "abc123" and str2 = "123abc". Therefore both strings are not equal. Since we have to compare only alphanumeric characters therefore whenever any other character is found simply ignore it by increasing iterator pointer. For doing it simply take two integer variables i and j and initialize them by 0. Now run a loop to compare each and every character of both strings. Compare one by one if the character is alphanumeric otherwise increase the value of i or j by one. Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <iostream>using namespace std; // Function to check alphanumeric equality of both stringsbool CompareAlphanumeric(string& str1, string& str2){ // variable declaration int i, j; i = 0; j = 0; // Length of first string int len1 = str1.size(); // Length of second string int len2 = str2.size(); // To check each and every characters of both string while (i <= len1 && j <= len2) { // If the current character of the first string is not an // alphanumeric character, increase the pointer i while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] >= '0' && str1[i] <= '9')))) { i++; } // If the current character of the second string is not an // alphanumeric character, increase the pointer j while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') || (str2[j] >= 'A' && str2[j] <= 'Z') || (str2[j] >= '0' && str2[j] <= '9')))) { j++; } // if all alphanumeric characters of both strings are same // then return true if (i == len1 && j == len2) return true; // if any alphanumeric characters of both strings are not same // then return false else if (str1[i] != str2[j]) return false; // If current character matched, // increase both pointers to check the next character else { i++; j++; } } // If not same, then return false return false;} // Function to print Equal or Unequal if strings are same or notvoid CompareAlphanumericUtil(string str1, string str2){ bool res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1, str2); // if both are alphanumeric equal, print Equal if (res == true) cout << "Equal" << endl; // otherwise print Unequal else cout << "Unequal" << endl;} // Driver codeint main(){ string str1, str2; str1 = "Ram, Shyam"; str2 = " Ram - Shyam."; CompareAlphanumericUtil(str1, str2); str1 = "abc123"; str2 = "123abc"; CompareAlphanumericUtil(str1, str2); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to check alphanumeric// equality of both stringsstatic boolean CompareAlphanumeric(char[] str1, char[] str2){ // variable declaration int i, j; i = 0; j = 0; // Length of first string int len1 = str1.length; // Length of second string int len2 = str2.length; // To check each and every characters // of both string while (i <= len1 && j <= len2) { // If the current character of the first string is not an // alphanumeric character, increase the pointer i while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] >= '0' && str1[i] <= '9')))) { i++; } // If the current character of the second string is not an // alphanumeric character, increase the pointer j while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') || (str2[j] >= 'A' && str2[j] <= 'Z') || (str2[j] >= '0' && str2[j] <= '9')))) { j++; } // if all alphanumeric characters of // both strings are same then return true if (i == len1 && j == len2) { return true; } // if any alphanumeric characters of // both strings are not same then return false else if (str1[i] != str2[j]) { return false; } // If current character matched, // increase both pointers to // check the next character else { i++; j++; } } // If not same, then return false return false;} // Function to print Equal or Unequal// if strings are same or notstatic void CompareAlphanumericUtil(String str1, String str2){ boolean res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1.toCharArray(), str2.toCharArray()); // if both are alphanumeric equal, // print Equal if (res == true) { System.out.println("Equal"); } // otherwise print Unequal else { System.out.println("Unequal"); }} // Driver codepublic static void main(String[] args){ String str1, str2; str1 = "Ram, Shyam"; str2 = " Ram - Shyam."; CompareAlphanumericUtil(str1, str2); str1 = "abc123"; str2 = "123abc"; CompareAlphanumericUtil(str1, str2);}} // This code is contributed by Rajput-Ji # Function to check alphanumeric equality# of both stringsdef CompareAlphanumeric(str1, str2): # variable declaration i = 0 j = 0 # Length of first string len1 = len(str1) # Length of second string len2 = len(str2) # To check each and every character of both string while (i <= len1 and j <= len2): # If the current character of the first string # is not an alphanumeric character, # increase the pointer i while (i < len1 and (((str1[i] >= 'a' and str1[i] <= 'z') or (str1[i] >= 'A' and str1[i] <= 'Z') or (str1[i] >= '0' and str1[i] <= '9')) == False)): i += 1 # If the current character of the second string # is not an alphanumeric character, # increase the pointer j while (j < len2 and (((str2[j] >= 'a' and str2[j] <= 'z') or (str2[j] >= 'A' and str2[j] <= 'Z') or (str2[j] >= '0' and str2[j] <= '9')) == False)): j += 1 # if all alphanumeric characters of # both strings are same, then return true if (i == len1 and j == len2): return True # if any alphanumeric characters of # both strings are not same, then return false elif (str1[i] != str2[j]): return False # If current character matched, # increase both pointers # to check the next character else: i += 1 j += 1 # If not same, then return false return False # Function to print Equal or Unequal# if strings are same or notdef CompareAlphanumericUtil(str1, str2): # check alphanumeric equality of both strings res = CompareAlphanumeric(str1, str2) # if both are alphanumeric equal, print Equal if (res == True): print("Equal") # otherwise print Unequal else: print("Unequal") # Driver codeif __name__ == '__main__': str1 = "Ram, Shyam" str2 = " Ram - Shyam." CompareAlphanumericUtil(str1, str2) str1 = "abc123" str2 = "123abc" CompareAlphanumericUtil(str1, str2) # This code is contributed by Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function to check alphanumeric // equality of both strings static bool CompareAlphanumeric(char []str1, char []str2) { // variable declaration int i, j; i = 0; j = 0; // Length of first string int len1 = str1.Length; // Length of second string int len2 = str2.Length; // To check each and every characters // of both string while (i <= len1 && j <= len2) { // If the current character of the first // string is not an alphanumeric character, // increase the pointer i while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] >= '0' && str1[i] <= '9')))) { i++; } // If the current character of the second // string is not an alphanumeric character, // increase the pointer j while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') || (str2[j] >= 'A' && str2[j] <= 'Z') || (str2[j] >= '0' && str2[j] <= '9')))) { j++; } // if all alphanumeric characters of // both strings are same then return true if (i == len1 && j == len2) { return true; } // if any alphanumeric characters of // both strings are not same then return false else if (str1[i] != str2[j]) { return false; } // If current character matched, // increase both pointers to // check the next character else { i++; j++; } } // If not same, then return false return false; } // Function to print Equal or Unequal // if strings are same or not static void CompareAlphanumericUtil(string str1, string str2) { bool res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1.ToCharArray(), str2.ToCharArray()); // if both are alphanumeric equal, // print Equal if (res == true) { Console.WriteLine("Equal"); } // otherwise print Unequal else { Console.WriteLine("Unequal"); } } // Driver code public static void Main() { string str1, str2; str1 = "Ram, Shyam"; str2 = " Ram - Shyam."; CompareAlphanumericUtil(str1, str2); str1 = "abc123"; str2 = "123abc"; CompareAlphanumericUtil(str1, str2); }} // This code is contributed by AnkitRai01 <script> // JavaScript implementation of the approach // Function to check alphanumeric // equality of both strings function CompareAlphanumeric(str1, str2) { // variable declaration let i, j; i = 0; j = 0; // Length of first string let len1 = str1.length; // Length of second string let len2 = str2.length; // To check each and every characters // of both string while (i <= len1 && j <= len2) { // If the current character of the first // string is not an alphanumeric character, // increase the pointer i while (i < len1 && (!((str1[i].charCodeAt() >= 'a'.charCodeAt() && str1[i].charCodeAt() <= 'z'.charCodeAt()) || (str1[i].charCodeAt() >= 'A'.charCodeAt() && str1[i].charCodeAt() <= 'Z'.charCodeAt()) || (str1[i].charCodeAt() >= '0'.charCodeAt() && str1[i].charCodeAt() <= '9'.charCodeAt())))) { i++; } // If the current character of the second // string is not an alphanumeric character, // increase the pointer j while (j < len2 && (!((str2[j].charCodeAt() >= 'a'.charCodeAt() && str2[j].charCodeAt() <= 'z'.charCodeAt()) || (str2[j].charCodeAt() >= 'A'.charCodeAt() && str2[j].charCodeAt() <= 'Z'.charCodeAt()) || (str2[j].charCodeAt() >= '0'.charCodeAt() && str2[j].charCodeAt() <= '9'.charCodeAt())))) { j++; } // if all alphanumeric characters of // both strings are same then return true if (i == len1 && j == len2) { return true; } // if any alphanumeric characters of // both strings are not same then return false else if (str1[i] != str2[j]) { return false; } // If current character matched, // increase both pointers to // check the next character else { i++; j++; } } // If not same, then return false return false; } // Function to print Equal or Unequal // if strings are same or not function CompareAlphanumericUtil(str1, str2) { let res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1.split(''), str2.split('')); // if both are alphanumeric equal, // print Equal if (res == true) { document.write("Equal" + "</br>"); } // otherwise print Unequal else { document.write("Unequal"); } } let str1, str2; str1 = "Ram, Shyam"; str2 = " Ram - Shyam."; CompareAlphanumericUtil(str1, str2); str1 = "abc123"; str2 = "123abc"; CompareAlphanumericUtil(str1, str2); </script> Equal Unequal Rajput-Ji ankthon SURENDRA_GANGWAR akshaysingh98088 suresh07 Strings Strings 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++ How to Append a Character to a String in C Program to count occurrence of a given character in a string Naive algorithm for Pattern Searching
[ { "code": null, "e": 26099, "s": 26071, "text": "\n03 Jun, 2021" }, { "code": null, "e": 26453, "s": 26099, "text": "Given two strings that can contain lower and uppercase alphabets, numbers and special characters like dots, blank spaces, commas, etc. Compare both strings considering only alphanumeric characters([a-b], [A-B] and [0-9]) if they are equal or not. For example, strings “Ram, Shyam” and “Ram-Shyam” both are the same and also “/.’;[]” and “@# >” are same." }, { "code": null, "e": 26464, "s": 26453, "text": "Examples: " }, { "code": null, "e": 26921, "s": 26464, "text": "Input: str1 = \"Ram, Shyam\", str2 = \" Ram - Shyam.\"\nOutput: Equal\nExplanation: \nif we ignore all characters \nexcept alphanumeric characters \nthen strings will be, \nstr1 = \"RamShyam\" and str2 = \"RamShyam\". \nTherefore both strings are equal.\n\nInput : str1 = \"aaa123\", str2 = \"@aaa-12-3\"\nOutput : Equal\n\nInput : str1 = \"abc123\", str2 = \"123abc\"\nOutput : Unequal\nExplanation: \nIn this, str1 = \"abc123\" and str2 = \"123abc\". \nTherefore both strings are not equal." }, { "code": null, "e": 27320, "s": 26921, "text": "Since we have to compare only alphanumeric characters therefore whenever any other character is found simply ignore it by increasing iterator pointer. For doing it simply take two integer variables i and j and initialize them by 0. Now run a loop to compare each and every character of both strings. Compare one by one if the character is alphanumeric otherwise increase the value of i or j by one." }, { "code": null, "e": 27373, "s": 27320, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27377, "s": 27373, "text": "C++" }, { "code": null, "e": 27382, "s": 27377, "text": "Java" }, { "code": null, "e": 27390, "s": 27382, "text": "Python3" }, { "code": null, "e": 27393, "s": 27390, "text": "C#" }, { "code": null, "e": 27404, "s": 27393, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function to check alphanumeric equality of both stringsbool CompareAlphanumeric(string& str1, string& str2){ // variable declaration int i, j; i = 0; j = 0; // Length of first string int len1 = str1.size(); // Length of second string int len2 = str2.size(); // To check each and every characters of both string while (i <= len1 && j <= len2) { // If the current character of the first string is not an // alphanumeric character, increase the pointer i while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] >= '0' && str1[i] <= '9')))) { i++; } // If the current character of the second string is not an // alphanumeric character, increase the pointer j while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') || (str2[j] >= 'A' && str2[j] <= 'Z') || (str2[j] >= '0' && str2[j] <= '9')))) { j++; } // if all alphanumeric characters of both strings are same // then return true if (i == len1 && j == len2) return true; // if any alphanumeric characters of both strings are not same // then return false else if (str1[i] != str2[j]) return false; // If current character matched, // increase both pointers to check the next character else { i++; j++; } } // If not same, then return false return false;} // Function to print Equal or Unequal if strings are same or notvoid CompareAlphanumericUtil(string str1, string str2){ bool res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1, str2); // if both are alphanumeric equal, print Equal if (res == true) cout << \"Equal\" << endl; // otherwise print Unequal else cout << \"Unequal\" << endl;} // Driver codeint main(){ string str1, str2; str1 = \"Ram, Shyam\"; str2 = \" Ram - Shyam.\"; CompareAlphanumericUtil(str1, str2); str1 = \"abc123\"; str2 = \"123abc\"; CompareAlphanumericUtil(str1, str2); return 0;}", "e": 29690, "s": 27404, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to check alphanumeric// equality of both stringsstatic boolean CompareAlphanumeric(char[] str1, char[] str2){ // variable declaration int i, j; i = 0; j = 0; // Length of first string int len1 = str1.length; // Length of second string int len2 = str2.length; // To check each and every characters // of both string while (i <= len1 && j <= len2) { // If the current character of the first string is not an // alphanumeric character, increase the pointer i while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] >= '0' && str1[i] <= '9')))) { i++; } // If the current character of the second string is not an // alphanumeric character, increase the pointer j while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') || (str2[j] >= 'A' && str2[j] <= 'Z') || (str2[j] >= '0' && str2[j] <= '9')))) { j++; } // if all alphanumeric characters of // both strings are same then return true if (i == len1 && j == len2) { return true; } // if any alphanumeric characters of // both strings are not same then return false else if (str1[i] != str2[j]) { return false; } // If current character matched, // increase both pointers to // check the next character else { i++; j++; } } // If not same, then return false return false;} // Function to print Equal or Unequal// if strings are same or notstatic void CompareAlphanumericUtil(String str1, String str2){ boolean res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1.toCharArray(), str2.toCharArray()); // if both are alphanumeric equal, // print Equal if (res == true) { System.out.println(\"Equal\"); } // otherwise print Unequal else { System.out.println(\"Unequal\"); }} // Driver codepublic static void main(String[] args){ String str1, str2; str1 = \"Ram, Shyam\"; str2 = \" Ram - Shyam.\"; CompareAlphanumericUtil(str1, str2); str1 = \"abc123\"; str2 = \"123abc\"; CompareAlphanumericUtil(str1, str2);}} // This code is contributed by Rajput-Ji", "e": 32346, "s": 29690, "text": null }, { "code": "# Function to check alphanumeric equality# of both stringsdef CompareAlphanumeric(str1, str2): # variable declaration i = 0 j = 0 # Length of first string len1 = len(str1) # Length of second string len2 = len(str2) # To check each and every character of both string while (i <= len1 and j <= len2): # If the current character of the first string # is not an alphanumeric character, # increase the pointer i while (i < len1 and (((str1[i] >= 'a' and str1[i] <= 'z') or (str1[i] >= 'A' and str1[i] <= 'Z') or (str1[i] >= '0' and str1[i] <= '9')) == False)): i += 1 # If the current character of the second string # is not an alphanumeric character, # increase the pointer j while (j < len2 and (((str2[j] >= 'a' and str2[j] <= 'z') or (str2[j] >= 'A' and str2[j] <= 'Z') or (str2[j] >= '0' and str2[j] <= '9')) == False)): j += 1 # if all alphanumeric characters of # both strings are same, then return true if (i == len1 and j == len2): return True # if any alphanumeric characters of # both strings are not same, then return false elif (str1[i] != str2[j]): return False # If current character matched, # increase both pointers # to check the next character else: i += 1 j += 1 # If not same, then return false return False # Function to print Equal or Unequal# if strings are same or notdef CompareAlphanumericUtil(str1, str2): # check alphanumeric equality of both strings res = CompareAlphanumeric(str1, str2) # if both are alphanumeric equal, print Equal if (res == True): print(\"Equal\") # otherwise print Unequal else: print(\"Unequal\") # Driver codeif __name__ == '__main__': str1 = \"Ram, Shyam\" str2 = \" Ram - Shyam.\" CompareAlphanumericUtil(str1, str2) str1 = \"abc123\" str2 = \"123abc\" CompareAlphanumericUtil(str1, str2) # This code is contributed by Surendra_Gangwar", "e": 34520, "s": 32346, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to check alphanumeric // equality of both strings static bool CompareAlphanumeric(char []str1, char []str2) { // variable declaration int i, j; i = 0; j = 0; // Length of first string int len1 = str1.Length; // Length of second string int len2 = str2.Length; // To check each and every characters // of both string while (i <= len1 && j <= len2) { // If the current character of the first // string is not an alphanumeric character, // increase the pointer i while (i < len1 && (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z') || (str1[i] >= '0' && str1[i] <= '9')))) { i++; } // If the current character of the second // string is not an alphanumeric character, // increase the pointer j while (j < len2 && (!((str2[j] >= 'a' && str2[j] <= 'z') || (str2[j] >= 'A' && str2[j] <= 'Z') || (str2[j] >= '0' && str2[j] <= '9')))) { j++; } // if all alphanumeric characters of // both strings are same then return true if (i == len1 && j == len2) { return true; } // if any alphanumeric characters of // both strings are not same then return false else if (str1[i] != str2[j]) { return false; } // If current character matched, // increase both pointers to // check the next character else { i++; j++; } } // If not same, then return false return false; } // Function to print Equal or Unequal // if strings are same or not static void CompareAlphanumericUtil(string str1, string str2) { bool res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1.ToCharArray(), str2.ToCharArray()); // if both are alphanumeric equal, // print Equal if (res == true) { Console.WriteLine(\"Equal\"); } // otherwise print Unequal else { Console.WriteLine(\"Unequal\"); } } // Driver code public static void Main() { string str1, str2; str1 = \"Ram, Shyam\"; str2 = \" Ram - Shyam.\"; CompareAlphanumericUtil(str1, str2); str1 = \"abc123\"; str2 = \"123abc\"; CompareAlphanumericUtil(str1, str2); }} // This code is contributed by AnkitRai01", "e": 37597, "s": 34520, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to check alphanumeric // equality of both strings function CompareAlphanumeric(str1, str2) { // variable declaration let i, j; i = 0; j = 0; // Length of first string let len1 = str1.length; // Length of second string let len2 = str2.length; // To check each and every characters // of both string while (i <= len1 && j <= len2) { // If the current character of the first // string is not an alphanumeric character, // increase the pointer i while (i < len1 && (!((str1[i].charCodeAt() >= 'a'.charCodeAt() && str1[i].charCodeAt() <= 'z'.charCodeAt()) || (str1[i].charCodeAt() >= 'A'.charCodeAt() && str1[i].charCodeAt() <= 'Z'.charCodeAt()) || (str1[i].charCodeAt() >= '0'.charCodeAt() && str1[i].charCodeAt() <= '9'.charCodeAt())))) { i++; } // If the current character of the second // string is not an alphanumeric character, // increase the pointer j while (j < len2 && (!((str2[j].charCodeAt() >= 'a'.charCodeAt() && str2[j].charCodeAt() <= 'z'.charCodeAt()) || (str2[j].charCodeAt() >= 'A'.charCodeAt() && str2[j].charCodeAt() <= 'Z'.charCodeAt()) || (str2[j].charCodeAt() >= '0'.charCodeAt() && str2[j].charCodeAt() <= '9'.charCodeAt())))) { j++; } // if all alphanumeric characters of // both strings are same then return true if (i == len1 && j == len2) { return true; } // if any alphanumeric characters of // both strings are not same then return false else if (str1[i] != str2[j]) { return false; } // If current character matched, // increase both pointers to // check the next character else { i++; j++; } } // If not same, then return false return false; } // Function to print Equal or Unequal // if strings are same or not function CompareAlphanumericUtil(str1, str2) { let res; // check alphanumeric equality of both strings res = CompareAlphanumeric(str1.split(''), str2.split('')); // if both are alphanumeric equal, // print Equal if (res == true) { document.write(\"Equal\" + \"</br>\"); } // otherwise print Unequal else { document.write(\"Unequal\"); } } let str1, str2; str1 = \"Ram, Shyam\"; str2 = \" Ram - Shyam.\"; CompareAlphanumericUtil(str1, str2); str1 = \"abc123\"; str2 = \"123abc\"; CompareAlphanumericUtil(str1, str2); </script>", "e": 40759, "s": 37597, "text": null }, { "code": null, "e": 40773, "s": 40759, "text": "Equal\nUnequal" }, { "code": null, "e": 40785, "s": 40775, "text": "Rajput-Ji" }, { "code": null, "e": 40793, "s": 40785, "text": "ankthon" }, { "code": null, "e": 40810, "s": 40793, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 40827, "s": 40810, "text": "akshaysingh98088" }, { "code": null, "e": 40836, "s": 40827, "text": "suresh07" }, { "code": null, "e": 40844, "s": 40836, "text": "Strings" }, { "code": null, "e": 40852, "s": 40844, "text": "Strings" }, { "code": null, "e": 40950, "s": 40852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40995, "s": 40950, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 41040, "s": 40995, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 41057, "s": 41040, "text": "Vigenère Cipher" }, { "code": null, "e": 41086, "s": 41057, "text": "String class in Java | Set 1" }, { "code": null, "e": 41101, "s": 41086, "text": "sprintf() in C" }, { "code": null, "e": 41136, "s": 41101, "text": "Print all subsequences of a string" }, { "code": null, "e": 41177, "s": 41136, "text": "Convert character array to string in C++" }, { "code": null, "e": 41220, "s": 41177, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 41281, "s": 41220, "text": "Program to count occurrence of a given character in a string" } ]
Python | Simple calculator using Tkinter - GeeksforGeeks
15 Jul, 2021 Prerequisite : Tkinter IntroductionPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.Let’s see how to create a basic calculator using Tkinter. Basic steps: First we create an object named root out of tk. We create an object of the calc and pass root as master to the init method. Mainloop starts an event loop, which is basically an infinite loop waiting for events and respond accordingly. The mainloop can be terminated by closing the window or using close method. Below is the implementation: Python3 # importing Tkinter and mathfrom tkinter import *import math # calc classclass calc: def getandreplace(self): """replace x with * and ÷ with /""" self.expression = self.e.get() self.newtext=self.expression.replace('/','/') self.newtext=self.newtext.replace('x','*') def equals(self): """when the equal button is pressed""" self.getandreplace() try: # evaluate the expression using the eval function self.value= eval(self.newtext) except SyntaxError or NameError: self.e.delete(0,END) self.e.insert(0,'Invalid Input!') else: self.e.delete(0,END) self.e.insert(0,self.value) def squareroot(self): """squareroot method""" self.getandreplace() try: # evaluate the expression using the eval function self.value= eval(self.newtext) except SyntaxError or NameError: self.e.delete(0,END) self.e.insert(0,'Invalid Input!') else: self.sqrtval=math.sqrt(self.value) self.e.delete(0,END) self.e.insert(0,self.sqrtval) def square(self): """square method""" self.getandreplace() try: #evaluate the expression using the eval function self.value= eval(self.newtext) except SyntaxError or NameError: self.e.delete(0,END) self.e.insert(0,'Invalid Input!') else: self.sqval=math.pow(self.value,2) self.e.delete(0,END) self.e.insert(0,self.sqval) def clearall(self): """when clear button is pressed,clears the text input area""" self.e.delete(0,END) def clear1(self): self.txt=self.e.get()[:-1] self.e.delete(0,END) self.e.insert(0,self.txt) def action(self,argi): """pressed button's value is inserted into the end of the text area""" self.e.insert(END,argi) def __init__(self,master): """Constructor method""" master.title('Calculator') master.geometry() self.e = Entry(master) self.e.grid(row=0,column=0,columnspan=6,pady=3) self.e.focus_set() #Sets focus on the input text area # Generating Buttons Button(master,text="=",width=11,height=3,fg="blue", bg="orange",command=lambda:self.equals()).grid( row=4, column=4,columnspan=2) Button(master,text='AC',width=5,height=3, fg="red", bg="light green", command=lambda:self.clearall()).grid(row=1, column=4) Button(master,text='C',width=5,height=3, fg="red",bg="light green", command=lambda:self.clear1()).grid(row=1, column=5) Button(master,text="+",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action('+')).grid(row=4, column=3) Button(master,text="x",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action('x')).grid(row=2, column=3) Button(master,text="-",width=5,height=3, fg="red",bg="light green", command=lambda:self.action('-')).grid(row=3, column=3) Button(master,text="÷",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action('/')).grid(row=1, column=3) Button(master,text="%",width=5,height=3, fg="red",bg="light green", command=lambda:self.action('%')).grid(row=4, column=2) Button(master,text="7",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action('7')).grid(row=1, column=0) Button(master,text="8",width=5,height=3, fg="red",bg="light green", command=lambda:self.action(8)).grid(row=1, column=1) Button(master,text="9",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action(9)).grid(row=1, column=2) Button(master,text="4",width=5,height=3, fg="red",bg="light green", command=lambda:self.action(4)).grid(row=2, column=0) Button(master,text="5",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action(5)).grid(row=2, column=1) Button(master,text="6",width=5,height=3, fg="white",bg="blue", command=lambda:self.action(6)).grid(row=2, column=2) Button(master,text="1",width=5,height=3, fg="red",bg="light green", command=lambda:self.action(1)).grid(row=3, column=0) Button(master,text="2",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action(2)).grid(row=3, column=1) Button(master,text="3",width=5,height=3, fg="white",bg="blue", command=lambda:self.action(3)).grid(row=3, column=2) Button(master,text="0",width=5,height=3, fg="white",bg="blue", command=lambda:self.action(0)).grid(row=4, column=0) Button(master,text=".",width=5,height=3, fg="red",bg="light green", command=lambda:self.action('.')).grid(row=4, column=1) Button(master,text="(",width=5,height=3, fg="white",bg="blue", command=lambda:self.action('(')).grid(row=2, column=4) Button(master,text=")",width=5,height=3, fg="blue",bg="orange", command=lambda:self.action(')')).grid(row=2, column=5) Button(master,text="?",width=5,height=3, fg="red",bg="light green", command=lambda:self.squareroot()).grid(row=3, column=4) Button(master,text="x2",width=5,height=3, fg="white",bg="blue", command=lambda:self.square()).grid(row=3, column=5) # Driver Coderoot = Tk() obj=calc(root) # object instantiated root.mainloop() Output: anikaseth98 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 ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Check if element exists in list in Python Create a Pandas DataFrame from Lists sum() function in Python
[ { "code": null, "e": 25589, "s": 25561, "text": "\n15 Jul, 2021" }, { "code": null, "e": 26041, "s": 25589, "text": "Prerequisite : Tkinter IntroductionPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.Let’s see how to create a basic calculator using Tkinter. " }, { "code": null, "e": 26055, "s": 26041, "text": "Basic steps: " }, { "code": null, "e": 26103, "s": 26055, "text": "First we create an object named root out of tk." }, { "code": null, "e": 26179, "s": 26103, "text": "We create an object of the calc and pass root as master to the init method." }, { "code": null, "e": 26366, "s": 26179, "text": "Mainloop starts an event loop, which is basically an infinite loop waiting for events and respond accordingly. The mainloop can be terminated by closing the window or using close method." }, { "code": null, "e": 26396, "s": 26366, "text": "Below is the implementation: " }, { "code": null, "e": 26404, "s": 26396, "text": "Python3" }, { "code": "# importing Tkinter and mathfrom tkinter import *import math # calc classclass calc: def getandreplace(self): \"\"\"replace x with * and ÷ with /\"\"\" self.expression = self.e.get() self.newtext=self.expression.replace('/','/') self.newtext=self.newtext.replace('x','*') def equals(self): \"\"\"when the equal button is pressed\"\"\" self.getandreplace() try: # evaluate the expression using the eval function self.value= eval(self.newtext) except SyntaxError or NameError: self.e.delete(0,END) self.e.insert(0,'Invalid Input!') else: self.e.delete(0,END) self.e.insert(0,self.value) def squareroot(self): \"\"\"squareroot method\"\"\" self.getandreplace() try: # evaluate the expression using the eval function self.value= eval(self.newtext) except SyntaxError or NameError: self.e.delete(0,END) self.e.insert(0,'Invalid Input!') else: self.sqrtval=math.sqrt(self.value) self.e.delete(0,END) self.e.insert(0,self.sqrtval) def square(self): \"\"\"square method\"\"\" self.getandreplace() try: #evaluate the expression using the eval function self.value= eval(self.newtext) except SyntaxError or NameError: self.e.delete(0,END) self.e.insert(0,'Invalid Input!') else: self.sqval=math.pow(self.value,2) self.e.delete(0,END) self.e.insert(0,self.sqval) def clearall(self): \"\"\"when clear button is pressed,clears the text input area\"\"\" self.e.delete(0,END) def clear1(self): self.txt=self.e.get()[:-1] self.e.delete(0,END) self.e.insert(0,self.txt) def action(self,argi): \"\"\"pressed button's value is inserted into the end of the text area\"\"\" self.e.insert(END,argi) def __init__(self,master): \"\"\"Constructor method\"\"\" master.title('Calculator') master.geometry() self.e = Entry(master) self.e.grid(row=0,column=0,columnspan=6,pady=3) self.e.focus_set() #Sets focus on the input text area # Generating Buttons Button(master,text=\"=\",width=11,height=3,fg=\"blue\", bg=\"orange\",command=lambda:self.equals()).grid( row=4, column=4,columnspan=2) Button(master,text='AC',width=5,height=3, fg=\"red\", bg=\"light green\", command=lambda:self.clearall()).grid(row=1, column=4) Button(master,text='C',width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.clear1()).grid(row=1, column=5) Button(master,text=\"+\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action('+')).grid(row=4, column=3) Button(master,text=\"x\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action('x')).grid(row=2, column=3) Button(master,text=\"-\",width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.action('-')).grid(row=3, column=3) Button(master,text=\"÷\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action('/')).grid(row=1, column=3) Button(master,text=\"%\",width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.action('%')).grid(row=4, column=2) Button(master,text=\"7\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action('7')).grid(row=1, column=0) Button(master,text=\"8\",width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.action(8)).grid(row=1, column=1) Button(master,text=\"9\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action(9)).grid(row=1, column=2) Button(master,text=\"4\",width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.action(4)).grid(row=2, column=0) Button(master,text=\"5\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action(5)).grid(row=2, column=1) Button(master,text=\"6\",width=5,height=3, fg=\"white\",bg=\"blue\", command=lambda:self.action(6)).grid(row=2, column=2) Button(master,text=\"1\",width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.action(1)).grid(row=3, column=0) Button(master,text=\"2\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action(2)).grid(row=3, column=1) Button(master,text=\"3\",width=5,height=3, fg=\"white\",bg=\"blue\", command=lambda:self.action(3)).grid(row=3, column=2) Button(master,text=\"0\",width=5,height=3, fg=\"white\",bg=\"blue\", command=lambda:self.action(0)).grid(row=4, column=0) Button(master,text=\".\",width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.action('.')).grid(row=4, column=1) Button(master,text=\"(\",width=5,height=3, fg=\"white\",bg=\"blue\", command=lambda:self.action('(')).grid(row=2, column=4) Button(master,text=\")\",width=5,height=3, fg=\"blue\",bg=\"orange\", command=lambda:self.action(')')).grid(row=2, column=5) Button(master,text=\"?\",width=5,height=3, fg=\"red\",bg=\"light green\", command=lambda:self.squareroot()).grid(row=3, column=4) Button(master,text=\"x2\",width=5,height=3, fg=\"white\",bg=\"blue\", command=lambda:self.square()).grid(row=3, column=5) # Driver Coderoot = Tk() obj=calc(root) # object instantiated root.mainloop()", "e": 32691, "s": 26404, "text": null }, { "code": null, "e": 32700, "s": 32691, "text": "Output: " }, { "code": null, "e": 32714, "s": 32702, "text": "anikaseth98" }, { "code": null, "e": 32721, "s": 32714, "text": "Python" }, { "code": null, "e": 32819, "s": 32721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32837, "s": 32819, "text": "Python Dictionary" }, { "code": null, "e": 32869, "s": 32837, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32911, "s": 32869, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32937, "s": 32911, "text": "Python String | replace()" }, { "code": null, "e": 32981, "s": 32937, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 33010, "s": 32981, "text": "*args and **kwargs in Python" }, { "code": null, "e": 33046, "s": 33010, "text": "Convert integer to string in Python" }, { "code": null, "e": 33088, "s": 33046, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33125, "s": 33088, "text": "Create a Pandas DataFrame from Lists" } ]
Tryit Editor v3.7
HTML Input types Tryit: HTML reset button
[ { "code": null, "e": 27, "s": 10, "text": "HTML Input types" } ]
How to create a Random Joke using React app through API fetching? - GeeksforGeeks
27 Nov, 2020 In this tutorial, we’ll make a website that fetches data (joke) from an external API and displays it on the screen. We’ll be using React completely to base this website. Each time we reload the page and click the button, a new joke fetched and rendered on the screen by React. As we are using React for this project, we need not reload the page to display the fetched data. The “Button” component. The “App” file is a functional component and contains a state variable Joke, which initially set to an empty string, and depending upon the state of the Joke, the output gets rendered. The Component outputs the “Button” component if the Joke contains an empty string or the value of Joke if it is not empty. The “Button” component that is getting rendered is also an imported functional component that outputs a button element. We are also passing some props to the “Button” component, which is a method named callAPI. Prerequisite: The pre-requisites for this project are: React Function Components ReactJS AJAX and API ES6 Reason to Create this app: The purpose of building such a simple website is to get some experience of working with API’s as all of them are more or less the same. The website uses a simple interface where we have a button, when hovered changes color, and when clicked makes a request to some external API and fetches data. Example: Create a new React project using the command npx create-react-app. In the same directory, we have a file index.js which manages all our components and renders the App component to the screen. Step 1(Creating Button.js): Before starting with the ReactJS part create component Button.js. which will be used in returning Button and App component respectively.The Button component accepts props and renders a button. We’ve added an event listener to the button which when clicked calls the function callAPI(). The callAPI() function is discussed in the next section in detail. The Button component is very simple and doesn’t require much explanation. It only returns a button element. Button.js:JavascriptJavascript// Import React (Mandatory Step).import React from "react"; // Create a functional component const Button = (props) => { return <button onClick={props.callApi}> Hello Geek!! </button>; } // Export Button Componentexport default Button; Step 1(Creating Button.js): Before starting with the ReactJS part create component Button.js. which will be used in returning Button and App component respectively. The Button component accepts props and renders a button. We’ve added an event listener to the button which when clicked calls the function callAPI(). The callAPI() function is discussed in the next section in detail. The Button component is very simple and doesn’t require much explanation. It only returns a button element. Button.js: Javascript // Import React (Mandatory Step).import React from "react"; // Create a functional component const Button = (props) => { return <button onClick={props.callApi}> Hello Geek!! </button>; } // Export Button Componentexport default Button; App.js: This file will return the main App which works as a container to all other components. In this project, we’ve used only functional components but the same can be done using class components. The App component is the parent to all other components. It returns a div that has a conditional statement, which returns the Button component if the value of the Joke variable is the empty string (“”), else returns the string stored in Joke with paragraph tags.At first, we have defined a state variable that is initialized as “”. It has been destructured so that we have direct access to the Joke variable and setJoke() which can be used to change the state of Joke.We also have a callAPI() which calls the API, takes the response, and passes it to json() which takes a response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc. It returns an object which has a property named joke which can be accessed using data.joke and can be logged in the console using console.log(data.joke). And then we change the state of the Joke variable using setJoke as data.joke.The moment we set the state as data.joke, react re-renders the entire component. And the string stored in Joke gets displayed on the string.JavascriptJavascript// Import React (Mandatory Step).import React from "react";// Import ReactDOM (Mandatory Step).import ReactDOM from "react-dom"; // Import The Button Component from Button.js import Button from "./Component/Button"; const rootElement = document.getElementById("root"); // Create a functional componentconst App = () => { // Declare a state variable const [Joke, setJoke] = React.useState(""); const fetchApi = () => { // Fetching data from the API fetch("https://sv443.net/jokeapi/v2/joke/Programming?type=single") .then((res) => res.json()) .then((data) => setJoke(data.joke)); }; return ( // Return the Button Component with a conditional statement <div>{Joke === "" ? <Button callApi={fetchApi} /> : <p>{Joke}</p>}</div> );} // Rendering the App Component.ReactDOM.render( <App />, rootElement);export default App App.js: This file will return the main App which works as a container to all other components. In this project, we’ve used only functional components but the same can be done using class components. The App component is the parent to all other components. It returns a div that has a conditional statement, which returns the Button component if the value of the Joke variable is the empty string (“”), else returns the string stored in Joke with paragraph tags. At first, we have defined a state variable that is initialized as “”. It has been destructured so that we have direct access to the Joke variable and setJoke() which can be used to change the state of Joke. We also have a callAPI() which calls the API, takes the response, and passes it to json() which takes a response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc. It returns an object which has a property named joke which can be accessed using data.joke and can be logged in the console using console.log(data.joke). And then we change the state of the Joke variable using setJoke as data.joke. The moment we set the state as data.joke, react re-renders the entire component. And the string stored in Joke gets displayed on the string. Javascript // Import React (Mandatory Step).import React from "react";// Import ReactDOM (Mandatory Step).import ReactDOM from "react-dom"; // Import The Button Component from Button.js import Button from "./Component/Button"; const rootElement = document.getElementById("root"); // Create a functional componentconst App = () => { // Declare a state variable const [Joke, setJoke] = React.useState(""); const fetchApi = () => { // Fetching data from the API fetch("https://sv443.net/jokeapi/v2/joke/Programming?type=single") .then((res) => res.json()) .then((data) => setJoke(data.joke)); }; return ( // Return the Button Component with a conditional statement <div>{Joke === "" ? <Button callApi={fetchApi} /> : <p>{Joke}</p>}</div> );} // Rendering the App Component.ReactDOM.render( <App />, rootElement);export default App Output: Our app is now complete and working, although the app is simple, it helps a lot in understanding how to make API calls in react and manipulate the response received to use it in the app. react-js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to get selected value in dropdown list 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": 24909, "s": 24881, "text": "\n27 Nov, 2020" }, { "code": null, "e": 25283, "s": 24909, "text": "In this tutorial, we’ll make a website that fetches data (joke) from an external API and displays it on the screen. We’ll be using React completely to base this website. Each time we reload the page and click the button, a new joke fetched and rendered on the screen by React. As we are using React for this project, we need not reload the page to display the fetched data." }, { "code": null, "e": 25827, "s": 25283, "text": "The “Button” component. The “App” file is a functional component and contains a state variable Joke, which initially set to an empty string, and depending upon the state of the Joke, the output gets rendered. The Component outputs the “Button” component if the Joke contains an empty string or the value of Joke if it is not empty. The “Button” component that is getting rendered is also an imported functional component that outputs a button element. We are also passing some props to the “Button” component, which is a method named callAPI. " }, { "code": null, "e": 25882, "s": 25827, "text": "Prerequisite: The pre-requisites for this project are:" }, { "code": null, "e": 25888, "s": 25882, "text": "React" }, { "code": null, "e": 25908, "s": 25888, "text": "Function Components" }, { "code": null, "e": 25929, "s": 25908, "text": "ReactJS AJAX and API" }, { "code": null, "e": 25933, "s": 25929, "text": "ES6" }, { "code": null, "e": 26256, "s": 25933, "text": "Reason to Create this app: The purpose of building such a simple website is to get some experience of working with API’s as all of them are more or less the same. The website uses a simple interface where we have a button, when hovered changes color, and when clicked makes a request to some external API and fetches data." }, { "code": null, "e": 26457, "s": 26256, "text": "Example: Create a new React project using the command npx create-react-app. In the same directory, we have a file index.js which manages all our components and renders the App component to the screen." }, { "code": null, "e": 27247, "s": 26457, "text": "Step 1(Creating Button.js): Before starting with the ReactJS part create component Button.js. which will be used in returning Button and App component respectively.The Button component accepts props and renders a button. We’ve added an event listener to the button which when clicked calls the function callAPI(). The callAPI() function is discussed in the next section in detail. The Button component is very simple and doesn’t require much explanation. It only returns a button element. Button.js:JavascriptJavascript// Import React (Mandatory Step).import React from \"react\"; // Create a functional component const Button = (props) => { return <button onClick={props.callApi}> Hello Geek!! </button>; } // Export Button Componentexport default Button;" }, { "code": null, "e": 27412, "s": 27247, "text": "Step 1(Creating Button.js): Before starting with the ReactJS part create component Button.js. which will be used in returning Button and App component respectively." }, { "code": null, "e": 27738, "s": 27412, "text": "The Button component accepts props and renders a button. We’ve added an event listener to the button which when clicked calls the function callAPI(). The callAPI() function is discussed in the next section in detail. The Button component is very simple and doesn’t require much explanation. It only returns a button element. " }, { "code": null, "e": 27749, "s": 27738, "text": "Button.js:" }, { "code": null, "e": 27760, "s": 27749, "text": "Javascript" }, { "code": "// Import React (Mandatory Step).import React from \"react\"; // Create a functional component const Button = (props) => { return <button onClick={props.callApi}> Hello Geek!! </button>; } // Export Button Componentexport default Button;", "e": 28031, "s": 27760, "text": null }, { "code": null, "e": 30289, "s": 28031, "text": "App.js: This file will return the main App which works as a container to all other components. In this project, we’ve used only functional components but the same can be done using class components. The App component is the parent to all other components. It returns a div that has a conditional statement, which returns the Button component if the value of the Joke variable is the empty string (“”), else returns the string stored in Joke with paragraph tags.At first, we have defined a state variable that is initialized as “”. It has been destructured so that we have direct access to the Joke variable and setJoke() which can be used to change the state of Joke.We also have a callAPI() which calls the API, takes the response, and passes it to json() which takes a response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc. It returns an object which has a property named joke which can be accessed using data.joke and can be logged in the console using console.log(data.joke). And then we change the state of the Joke variable using setJoke as data.joke.The moment we set the state as data.joke, react re-renders the entire component. And the string stored in Joke gets displayed on the string.JavascriptJavascript// Import React (Mandatory Step).import React from \"react\";// Import ReactDOM (Mandatory Step).import ReactDOM from \"react-dom\"; // Import The Button Component from Button.js import Button from \"./Component/Button\"; const rootElement = document.getElementById(\"root\"); // Create a functional componentconst App = () => { // Declare a state variable const [Joke, setJoke] = React.useState(\"\"); const fetchApi = () => { // Fetching data from the API fetch(\"https://sv443.net/jokeapi/v2/joke/Programming?type=single\") .then((res) => res.json()) .then((data) => setJoke(data.joke)); }; return ( // Return the Button Component with a conditional statement <div>{Joke === \"\" ? <Button callApi={fetchApi} /> : <p>{Joke}</p>}</div> );} // Rendering the App Component.ReactDOM.render( <App />, rootElement);export default App" }, { "code": null, "e": 30751, "s": 30289, "text": "App.js: This file will return the main App which works as a container to all other components. In this project, we’ve used only functional components but the same can be done using class components. The App component is the parent to all other components. It returns a div that has a conditional statement, which returns the Button component if the value of the Joke variable is the empty string (“”), else returns the string stored in Joke with paragraph tags." }, { "code": null, "e": 30958, "s": 30751, "text": "At first, we have defined a state variable that is initialized as “”. It has been destructured so that we have direct access to the Joke variable and setJoke() which can be used to change the state of Joke." }, { "code": null, "e": 31485, "s": 30958, "text": "We also have a callAPI() which calls the API, takes the response, and passes it to json() which takes a response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON, which is a JavaScript value of datatype object, string, etc. It returns an object which has a property named joke which can be accessed using data.joke and can be logged in the console using console.log(data.joke). And then we change the state of the Joke variable using setJoke as data.joke." }, { "code": null, "e": 31626, "s": 31485, "text": "The moment we set the state as data.joke, react re-renders the entire component. And the string stored in Joke gets displayed on the string." }, { "code": null, "e": 31637, "s": 31626, "text": "Javascript" }, { "code": "// Import React (Mandatory Step).import React from \"react\";// Import ReactDOM (Mandatory Step).import ReactDOM from \"react-dom\"; // Import The Button Component from Button.js import Button from \"./Component/Button\"; const rootElement = document.getElementById(\"root\"); // Create a functional componentconst App = () => { // Declare a state variable const [Joke, setJoke] = React.useState(\"\"); const fetchApi = () => { // Fetching data from the API fetch(\"https://sv443.net/jokeapi/v2/joke/Programming?type=single\") .then((res) => res.json()) .then((data) => setJoke(data.joke)); }; return ( // Return the Button Component with a conditional statement <div>{Joke === \"\" ? <Button callApi={fetchApi} /> : <p>{Joke}</p>}</div> );} // Rendering the App Component.ReactDOM.render( <App />, rootElement);export default App", "e": 32542, "s": 31637, "text": null }, { "code": null, "e": 32737, "s": 32542, "text": "Output: Our app is now complete and working, although the app is simple, it helps a lot in understanding how to make API calls in react and manipulate the response received to use it in the app." }, { "code": null, "e": 32746, "s": 32737, "text": "react-js" }, { "code": null, "e": 32757, "s": 32746, "text": "JavaScript" }, { "code": null, "e": 32774, "s": 32757, "text": "Web Technologies" }, { "code": null, "e": 32872, "s": 32774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32881, "s": 32872, "text": "Comments" }, { "code": null, "e": 32894, "s": 32881, "text": "Old Comments" }, { "code": null, "e": 32955, "s": 32894, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32996, "s": 32955, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 33036, "s": 32996, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33090, "s": 33036, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 33152, "s": 33090, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 33208, "s": 33152, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33241, "s": 33208, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33303, "s": 33241, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33346, "s": 33303, "text": "How to fetch data from an API in ReactJS ?" } ]
How to initialize a tuple to an empty tuple in C#?
To initialize a tuple to an empty tuple − Tuple<string, string> myTuple; If you want to check for values in a tuple, that whether it is null or not − using System; namespace Demo { class Program { static void Main(string[] args) { Tuple <int, string> tuple = new Tuple<int, string>(10, null); if (tuple.Item1 == 10) { Console.WriteLine(tuple.Item1); } if (tuple.Item2 == null) { Console.WriteLine("Item is null"); } } } }
[ { "code": null, "e": 1104, "s": 1062, "text": "To initialize a tuple to an empty tuple −" }, { "code": null, "e": 1135, "s": 1104, "text": "Tuple<string, string> myTuple;" }, { "code": null, "e": 1212, "s": 1135, "text": "If you want to check for values in a tuple, that whether it is null or not −" }, { "code": null, "e": 1574, "s": 1212, "text": "using System;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n Tuple <int, string> tuple = new Tuple<int, string>(10, null);\n\n if (tuple.Item1 == 10) {\n Console.WriteLine(tuple.Item1);\n }\n\n if (tuple.Item2 == null) {\n Console.WriteLine(\"Item is null\");\n }\n }\n }\n}" } ]
How to read inputs as strings in C#?
To read inputs as strings in C#, use the Console.ReadLine() method. str = Console.ReadLine(); The above will read input as string. You don’t need to use the Convert method here since the input takes string by default. Now display the string entered by user − Live Demo using System; using System.Collections.Generic; class Demo { static void Main() { string myStr; // use ReadLine() to read the entered line myStr = Console.ReadLine(); // display the line Console.WriteLine("Result = {0}", myStr); } } Result = The following is the output. Let’s say the user entered “Amit” as the input − Result = amit
[ { "code": null, "e": 1130, "s": 1062, "text": "To read inputs as strings in C#, use the Console.ReadLine() method." }, { "code": null, "e": 1156, "s": 1130, "text": "str = Console.ReadLine();" }, { "code": null, "e": 1280, "s": 1156, "text": "The above will read input as string. You don’t need to use the Convert method here since the input takes string by default." }, { "code": null, "e": 1321, "s": 1280, "text": "Now display the string entered by user −" }, { "code": null, "e": 1332, "s": 1321, "text": " Live Demo" }, { "code": null, "e": 1604, "s": 1332, "text": "using System;\nusing System.Collections.Generic;\n\nclass Demo {\n static void Main() {\n string myStr;\n\n // use ReadLine() to read the entered line\n myStr = Console.ReadLine();\n\n // display the line\n Console.WriteLine(\"Result = {0}\", myStr);\n }\n}" }, { "code": null, "e": 1613, "s": 1604, "text": "Result =" }, { "code": null, "e": 1691, "s": 1613, "text": "The following is the output. Let’s say the user entered “Amit” as the input −" }, { "code": null, "e": 1705, "s": 1691, "text": "Result = amit" } ]
How to clear complete cache data in ReactJS ? - GeeksforGeeks
26 Apr, 2021 We can use the following approach in ReactJS to clear complete cache data. We can clear complete cache data from the browser as per the user requirement. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested. Approach: Follow these simple steps in order to clear complete cache data in ReactJS. We have created our clearCacheData function which clears the entire cache data from the browser. When we click on the button, the function is triggered, and the entire caches get deleted from the browser and, and we see an alert popup. In the following example, we have 5 caches stored in the browser named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below, and we clear the complete cache using our defined function. Creating React Application: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import * as React from 'react'; export default function App() { // Function to clear complete cache data const clearCacheData = () => { caches.keys().then((names) => { names.forEach((name) => { caches.delete(name); }); }); alert('Complete Cache Cleared') }; return ( <div style={{ height: 500, width: '80%' }}> <h4>How to clear complete cache data in ReactJS?</h4> <button onClick={() => clearCacheData()} > Clear Cache Data</button> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to redirect to another page in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS setState() Re-rendering Components in ReactJS ReactJS defaultProps Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24384, "s": 24356, "text": "\n26 Apr, 2021" }, { "code": null, "e": 24664, "s": 24384, "text": "We can use the following approach in ReactJS to clear complete cache data. We can clear complete cache data from the browser as per the user requirement. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested." }, { "code": null, "e": 24987, "s": 24664, "text": "Approach: Follow these simple steps in order to clear complete cache data in ReactJS. We have created our clearCacheData function which clears the entire cache data from the browser. When we click on the button, the function is triggered, and the entire caches get deleted from the browser and, and we see an alert popup. " }, { "code": null, "e": 25191, "s": 24987, "text": "In the following example, we have 5 caches stored in the browser named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below, and we clear the complete cache using our defined function." }, { "code": null, "e": 25219, "s": 25191, "text": "Creating React Application:" }, { "code": null, "e": 25314, "s": 25219, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 25378, "s": 25314, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25410, "s": 25378, "text": "npx create-react-app foldername" }, { "code": null, "e": 25523, "s": 25410, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 25623, "s": 25523, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25637, "s": 25623, "text": "cd foldername" }, { "code": null, "e": 25689, "s": 25637, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25707, "s": 25689, "text": "Project Structure" }, { "code": null, "e": 25837, "s": 25707, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 25844, "s": 25837, "text": "App.js" }, { "code": "import * as React from 'react'; export default function App() { // Function to clear complete cache data const clearCacheData = () => { caches.keys().then((names) => { names.forEach((name) => { caches.delete(name); }); }); alert('Complete Cache Cleared') }; return ( <div style={{ height: 500, width: '80%' }}> <h4>How to clear complete cache data in ReactJS?</h4> <button onClick={() => clearCacheData()} > Clear Cache Data</button> </div> );}", "e": 26348, "s": 25844, "text": null }, { "code": null, "e": 26461, "s": 26348, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26471, "s": 26461, "text": "npm start" }, { "code": null, "e": 26570, "s": 26471, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 26586, "s": 26570, "text": "React-Questions" }, { "code": null, "e": 26594, "s": 26586, "text": "ReactJS" }, { "code": null, "e": 26611, "s": 26594, "text": "Web Technologies" }, { "code": null, "e": 26709, "s": 26611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26754, "s": 26709, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 26822, "s": 26754, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 26841, "s": 26822, "text": "ReactJS setState()" }, { "code": null, "e": 26876, "s": 26841, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 26897, "s": 26876, "text": "ReactJS defaultProps" }, { "code": null, "e": 26939, "s": 26897, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27001, "s": 26939, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27034, "s": 27001, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27079, "s": 27034, "text": "Convert a string to an integer in JavaScript" } ]
Angular7 - Overview
Angular 7 is owned by Google and the stable release was done on 18th October 2018. This is the latest version of Angular. Below is the list of Angular versions released so far − The release dates for the next two major upcoming versions of Angular are given below − Google plans to release the major Angular version every 6 months. The version released so far are backward compatible and can be updated to the newer one very easily. Let us discuss the new features added to Angular 7. Angular 7 is a major release where in the angular core framework, Angular CLI, Angular Materials are updated. In case you are using Angular 5 or 6 and want to update to Angular 7, below is the command which will update your app to the recent version of Angular − ng update @angular/cli @angular/core While doing project setup using angular CLI, it prompts you about the built-in features available, i.e., routing and stylesheet support as shown below − In Angular 7, there is bundle budget added in angular.json as shown below − Budgets is a feature added to Angular CLI which allows you to set limit inside your configuration to make sure your application size is within the limit set. You can set the size so that the app can be warned when the limit is crossed. The version of Angular Material/CDK is updated in Angular 7. Also there are 2 features added to CDK − virtual scrolling, and drag and drop. Virtual scrolling feature shows up the visible dom elements to the user, as the user scrolls, the next list is displayed. This gives faster experience as the full list is not loaded at one go and only loaded as per the visibility on the screen. You can drag and drop elements from a list and place it wherever required within the list. The new feature is very smooth and fast. 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": 2183, "s": 2061, "text": "Angular 7 is owned by Google and the stable release was done on 18th October 2018. This is the latest version of Angular." }, { "code": null, "e": 2239, "s": 2183, "text": "Below is the list of Angular versions released so far −" }, { "code": null, "e": 2327, "s": 2239, "text": "The release dates for the next two major upcoming versions of Angular are given below −" }, { "code": null, "e": 2494, "s": 2327, "text": "Google plans to release the major Angular version every 6 months. The version released so far are backward compatible and can be updated to the newer one very easily." }, { "code": null, "e": 2546, "s": 2494, "text": "Let us discuss the new features added to Angular 7." }, { "code": null, "e": 2809, "s": 2546, "text": "Angular 7 is a major release where in the angular core framework, Angular CLI, Angular Materials are updated. In case you are using Angular 5 or 6 and want to update to Angular 7, below is the command which will update your app to the recent version of Angular −" }, { "code": null, "e": 2847, "s": 2809, "text": "ng update @angular/cli @angular/core\n" }, { "code": null, "e": 3000, "s": 2847, "text": "While doing project setup using angular CLI, it prompts you about the built-in features available, i.e., routing and stylesheet support as shown below −" }, { "code": null, "e": 3076, "s": 3000, "text": "In Angular 7, there is bundle budget added in angular.json as shown below −" }, { "code": null, "e": 3312, "s": 3076, "text": "Budgets is a feature added to Angular CLI which allows you to set limit inside your configuration to make sure your application size is within the limit set. You can set the size so that the app can be warned when the limit is crossed." }, { "code": null, "e": 3452, "s": 3312, "text": "The version of Angular Material/CDK is updated in Angular 7. Also there are 2 features added to CDK − virtual scrolling, and drag and drop." }, { "code": null, "e": 3697, "s": 3452, "text": "Virtual scrolling feature shows up the visible dom elements to the user, as the user scrolls, the next list is displayed. This gives faster experience as the full list is not loaded at one go and only loaded as per the visibility on the screen." }, { "code": null, "e": 3829, "s": 3697, "text": "You can drag and drop elements from a list and place it wherever required within the list. The new feature is very smooth and fast." }, { "code": null, "e": 3864, "s": 3829, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3878, "s": 3864, "text": " Anadi Sharma" }, { "code": null, "e": 3913, "s": 3878, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3927, "s": 3913, "text": " Anadi Sharma" }, { "code": null, "e": 3962, "s": 3927, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3982, "s": 3962, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4017, "s": 3982, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4034, "s": 4017, "text": " Frahaan Hussain" }, { "code": null, "e": 4067, "s": 4034, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4079, "s": 4067, "text": " Senol Atac" }, { "code": null, "e": 4114, "s": 4079, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4126, "s": 4114, "text": " Senol Atac" }, { "code": null, "e": 4133, "s": 4126, "text": " Print" }, { "code": null, "e": 4144, "s": 4133, "text": " Add Notes" } ]
Trading Strategy: Back testing with Backtrader | by J Li | Towards Data Science
(This post is also available in my blog) In one of my older post, I demonstrates how to compute technical indicators which can be combined logically to build a trading strategy. As emphasized in the post, one should validate how well the strategy does with backtesting before applying it in real market. Backtesting is the process of applying a trading strategy or analytical method to historical data to see how accurately the strategy or method would have predicted actual results.- from investing answers Backtest is like cross validation in machine learning. But it’s not exactly the same. Backtest requires splitting data into two parts like cross validation. One set is for training, the other is for validation purpose. The difference is training testing split can be randomly done for cross validation. While in trading backtesting, your data is time series. Your training data must be older than your testing data. Otherwise you peek in future which results in incorrect measurement of your strategy. So dataset split cannot be random in backtesting. Backtesting involves market simulation in real world. It could be hard and error-prone to implement your own backtesting libraries. Luckily there’s Backtrader. Backtrader is an awesome open source python framework which allows you to focus on writing reusable trading strategies, indicators and analyzers instead of having to spend time building infrastructure. It supports backtesting for you to evaluate the strategy you come up with too! With that being said, it is a free and complete solution for technical people to build their own strategies. Let’s start to have a glance. pip install backtrader[plotting] Backtrader has defined a strategy interface for you. You need to create a class with implement this interface. An important method is next() where you should make decision whether you should BUY, SELL or DO NOTHING based on the technical indicators in a specific day. A simple strategy looks like this. import backtrader as btclass MyStrategy(bt.Strategy): def __init__(self): self.sma = bt.indicators.SimpleMovingAverage(period=15) def next(self): if self.sma > self.data.close: # Do something pass elif self.sma < self.data.close: # Do something else pass As you can see, backtrader has shipped with a set of common technical indicators. It means you don’t need to reply on your self or TA lib to compute technical indicators. Backtrader also offers features in simulating trading in the marking. Once can factor the commission in your trading operation based on dollar or percentage. cerebro.broker.setcommission(commission=0.001) Below is the whole example for demonstration of backtesting with Facebook historical market data. Note that, historical trading data is downloaded from Yahoo Finance. It also supports pandas dataframe. I have a post about collecting trading data with pandas here. The example consists of a simple TestStrategy and a driver piece of code that kick of the backtesting. The simple strategy only considers RSI for BUY/SELL signal. You should add more logics for your selected stocks. from __future__ import (absolute_import, division, print_function, unicode_literals)import datetimeimport os.pathimport sysimport backtrader as btclass TestStrategy(bt.Strategy): def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): self.dataclose = self.datas[0].close self.order = None self.buyprice = None self.buycomm = None self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=15) self.rsi = bt.indicators.RelativeStrengthIndex() def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: return if order.status in [order.Completed]: if order.isbuy(): self.log( 'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.buyprice = order.executed.price self.buycomm = order.executed.comm else: # Sell self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log('Order Canceled/Margin/Rejected') # Write down: no pending order self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm)) def next(self): self.log('Close, %.2f' % self.dataclose[0]) print('rsi:', self.rsi[0]) if self.order: return if not self.position: if (self.rsi[0] < 30): self.log('BUY CREATE, %.2f' % self.dataclose[0]) self.order = self.buy(size=500) else: if (self.rsi[0] > 70): self.log('SELL CREATE, %.2f' % self.dataclose[0]) self.order = self.sell(size=500)if __name__ == '__main__': cerebro = bt.Cerebro() cerebro.addstrategy(TestStrategy) cerebro.broker.setcommission(commission=0.001) datapath = 'FB.csv' # Create a Data Feed data = bt.feeds.YahooFinanceCSVData( dataname=datapath, fromdate=datetime.datetime(2013, 1, 1), todate=datetime.datetime(2018, 8, 5), reverse=True) cerebro.adddata(data) cerebro.broker.setcash(100000.0) print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.plot() At the end of execution, you can find out your final value of portfolio. As well, you are able to plot the stock price, technical indicators, your BUY/SELL operations and your portfolio value with regard to the time. As you can see, this simple strategy works ok with FB as it captures a few buy and sell opportunities. That’s it for backtesting with backtrader. If you want to dive deeper, I encourage you visit backtrader’s doc for more advanced usage. If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc. Happy coding and trading! Recommended reading: Hands-On Machine Learning Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython What Hedge Funds Really Do My posts: My posts about FAANG interview My YouTube Channel My posts about Finance and Tech From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda Full Stack Development Tutorial: Visualize Trading Data on Angular SPA Reinforcement Learning: Introduction to Q Learning
[ { "code": null, "e": 213, "s": 172, "text": "(This post is also available in my blog)" }, { "code": null, "e": 476, "s": 213, "text": "In one of my older post, I demonstrates how to compute technical indicators which can be combined logically to build a trading strategy. As emphasized in the post, one should validate how well the strategy does with backtesting before applying it in real market." }, { "code": null, "e": 680, "s": 476, "text": "Backtesting is the process of applying a trading strategy or analytical method to historical data to see how accurately the strategy or method would have predicted actual results.- from investing answers" }, { "code": null, "e": 1392, "s": 680, "text": "Backtest is like cross validation in machine learning. But it’s not exactly the same. Backtest requires splitting data into two parts like cross validation. One set is for training, the other is for validation purpose. The difference is training testing split can be randomly done for cross validation. While in trading backtesting, your data is time series. Your training data must be older than your testing data. Otherwise you peek in future which results in incorrect measurement of your strategy. So dataset split cannot be random in backtesting. Backtesting involves market simulation in real world. It could be hard and error-prone to implement your own backtesting libraries. Luckily there’s Backtrader." }, { "code": null, "e": 1673, "s": 1392, "text": "Backtrader is an awesome open source python framework which allows you to focus on writing reusable trading strategies, indicators and analyzers instead of having to spend time building infrastructure. It supports backtesting for you to evaluate the strategy you come up with too!" }, { "code": null, "e": 1812, "s": 1673, "text": "With that being said, it is a free and complete solution for technical people to build their own strategies. Let’s start to have a glance." }, { "code": null, "e": 1845, "s": 1812, "text": "pip install backtrader[plotting]" }, { "code": null, "e": 2148, "s": 1845, "text": "Backtrader has defined a strategy interface for you. You need to create a class with implement this interface. An important method is next() where you should make decision whether you should BUY, SELL or DO NOTHING based on the technical indicators in a specific day. A simple strategy looks like this." }, { "code": null, "e": 2474, "s": 2148, "text": "import backtrader as btclass MyStrategy(bt.Strategy): def __init__(self): self.sma = bt.indicators.SimpleMovingAverage(period=15) def next(self): if self.sma > self.data.close: # Do something pass elif self.sma < self.data.close: # Do something else pass" }, { "code": null, "e": 2645, "s": 2474, "text": "As you can see, backtrader has shipped with a set of common technical indicators. It means you don’t need to reply on your self or TA lib to compute technical indicators." }, { "code": null, "e": 2803, "s": 2645, "text": "Backtrader also offers features in simulating trading in the marking. Once can factor the commission in your trading operation based on dollar or percentage." }, { "code": null, "e": 2851, "s": 2803, "text": "cerebro.broker.setcommission(commission=0.001) " }, { "code": null, "e": 3331, "s": 2851, "text": "Below is the whole example for demonstration of backtesting with Facebook historical market data. Note that, historical trading data is downloaded from Yahoo Finance. It also supports pandas dataframe. I have a post about collecting trading data with pandas here. The example consists of a simple TestStrategy and a driver piece of code that kick of the backtesting. The simple strategy only considers RSI for BUY/SELL signal. You should add more logics for your selected stocks." }, { "code": null, "e": 6195, "s": 3331, "text": "from __future__ import (absolute_import, division, print_function, unicode_literals)import datetimeimport os.pathimport sysimport backtrader as btclass TestStrategy(bt.Strategy): def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): self.dataclose = self.datas[0].close self.order = None self.buyprice = None self.buycomm = None self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=15) self.rsi = bt.indicators.RelativeStrengthIndex() def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: return if order.status in [order.Completed]: if order.isbuy(): self.log( 'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.buyprice = order.executed.price self.buycomm = order.executed.comm else: # Sell self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log('Order Canceled/Margin/Rejected') # Write down: no pending order self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm)) def next(self): self.log('Close, %.2f' % self.dataclose[0]) print('rsi:', self.rsi[0]) if self.order: return if not self.position: if (self.rsi[0] < 30): self.log('BUY CREATE, %.2f' % self.dataclose[0]) self.order = self.buy(size=500) else: if (self.rsi[0] > 70): self.log('SELL CREATE, %.2f' % self.dataclose[0]) self.order = self.sell(size=500)if __name__ == '__main__': cerebro = bt.Cerebro() cerebro.addstrategy(TestStrategy) cerebro.broker.setcommission(commission=0.001) datapath = 'FB.csv' # Create a Data Feed data = bt.feeds.YahooFinanceCSVData( dataname=datapath, fromdate=datetime.datetime(2013, 1, 1), todate=datetime.datetime(2018, 8, 5), reverse=True) cerebro.adddata(data) cerebro.broker.setcash(100000.0) print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.plot()" }, { "code": null, "e": 6412, "s": 6195, "text": "At the end of execution, you can find out your final value of portfolio. As well, you are able to plot the stock price, technical indicators, your BUY/SELL operations and your portfolio value with regard to the time." }, { "code": null, "e": 6515, "s": 6412, "text": "As you can see, this simple strategy works ok with FB as it captures a few buy and sell opportunities." }, { "code": null, "e": 6855, "s": 6515, "text": "That’s it for backtesting with backtrader. If you want to dive deeper, I encourage you visit backtrader’s doc for more advanced usage. If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc. Happy coding and trading!" }, { "code": null, "e": 6876, "s": 6855, "text": "Recommended reading:" }, { "code": null, "e": 6902, "s": 6876, "text": "Hands-On Machine Learning" }, { "code": null, "e": 6975, "s": 6902, "text": "Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython" }, { "code": null, "e": 7002, "s": 6975, "text": "What Hedge Funds Really Do" }, { "code": null, "e": 7012, "s": 7002, "text": "My posts:" }, { "code": null, "e": 7043, "s": 7012, "text": "My posts about FAANG interview" }, { "code": null, "e": 7062, "s": 7043, "text": "My YouTube Channel" }, { "code": null, "e": 7094, "s": 7062, "text": "My posts about Finance and Tech" }, { "code": null, "e": 7183, "s": 7094, "text": "From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning" }, { "code": null, "e": 7273, "s": 7183, "text": "Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA" }, { "code": null, "e": 7374, "s": 7273, "text": "Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda" }, { "code": null, "e": 7445, "s": 7374, "text": "Full Stack Development Tutorial: Visualize Trading Data on Angular SPA" } ]
time.Date() Function in Golang With Examples - GeeksforGeeks
21 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Date() function in Go language is used to find Date the Time which is equivalent to yyyy-mm-dd hh:mm:ss + nsec nanoseconds in the proper time zone in the stated location. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time Here, “loc” is pointed to the location. Return Value: It returns a time that is proper in one of the two associated zones in the conversion, but it won’t guarantee that which one is returned. And it returns panics if the given “loc” is nil. Note: Here, the value of the month, day hour, min, sec and nsec can be more than the normal ranges but they will be automatically normalized during the conversion. For example, if the date is April 34 then it is converted to May 1. Example 1: // Golang program to illustrate the usage of// time.Date() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling Date() method // with all its parameters tm := time.Date(2020, time.April, 11, 21, 34, 01, 0, time.UTC) // Using Local() for location and printing // the stated time and date in UTC fmt.Printf("%s", tm.Local())} Output: 2020-04-11 21:34:01 +0000 UTC Example 2: // Golang program to illustrate the usage of// time.Date() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling Date() method // with all its parameters tm := time.Date(2020, time.April, 34, 25, 72, 01, 0, time.UTC) // Using Local() for location and printing // the stated time and date in UTC fmt.Printf("%s", tm.Local())} Output: 2020-05-05 02:12:01 +0000 UTC Here, the range of the values of day, hours, and minutes is outside the normal range but they are normalized during the conversion. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Arrays in Go fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? 6 Best Books to Learn Go Programming Language Golang Maps Slices in Golang Different Ways to Find the Type of Variable in Golang Inheritance in GoLang Interfaces in Golang
[ { "code": null, "e": 25733, "s": 25705, "text": "\n21 Apr, 2020" }, { "code": null, "e": 26138, "s": 25733, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Date() function in Go language is used to find Date the Time which is equivalent to yyyy-mm-dd hh:mm:ss + nsec nanoseconds in the proper time zone in the stated location. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 26146, "s": 26138, "text": "Syntax:" }, { "code": null, "e": 26231, "s": 26146, "text": "func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time\n" }, { "code": null, "e": 26271, "s": 26231, "text": "Here, “loc” is pointed to the location." }, { "code": null, "e": 26472, "s": 26271, "text": "Return Value: It returns a time that is proper in one of the two associated zones in the conversion, but it won’t guarantee that which one is returned. And it returns panics if the given “loc” is nil." }, { "code": null, "e": 26704, "s": 26472, "text": "Note: Here, the value of the month, day hour, min, sec and nsec can be more than the normal ranges but they will be automatically normalized during the conversion. For example, if the date is April 34 then it is converted to May 1." }, { "code": null, "e": 26715, "s": 26704, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// time.Date() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling Date() method // with all its parameters tm := time.Date(2020, time.April, 11, 21, 34, 01, 0, time.UTC) // Using Local() for location and printing // the stated time and date in UTC fmt.Printf(\"%s\", tm.Local())}", "e": 27157, "s": 26715, "text": null }, { "code": null, "e": 27165, "s": 27157, "text": "Output:" }, { "code": null, "e": 27196, "s": 27165, "text": "2020-04-11 21:34:01 +0000 UTC\n" }, { "code": null, "e": 27207, "s": 27196, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// time.Date() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling Date() method // with all its parameters tm := time.Date(2020, time.April, 34, 25, 72, 01, 0, time.UTC) // Using Local() for location and printing // the stated time and date in UTC fmt.Printf(\"%s\", tm.Local())}", "e": 27652, "s": 27207, "text": null }, { "code": null, "e": 27660, "s": 27652, "text": "Output:" }, { "code": null, "e": 27691, "s": 27660, "text": "2020-05-05 02:12:01 +0000 UTC\n" }, { "code": null, "e": 27823, "s": 27691, "text": "Here, the range of the values of day, hours, and minutes is outside the normal range but they are normalized during the conversion." }, { "code": null, "e": 27835, "s": 27823, "text": "GoLang-time" }, { "code": null, "e": 27847, "s": 27835, "text": "Go Language" }, { "code": null, "e": 27945, "s": 27847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27996, "s": 27945, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28009, "s": 27996, "text": "Arrays in Go" }, { "code": null, "e": 28056, "s": 28009, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 28089, "s": 28056, "text": "How to Split a String in Golang?" }, { "code": null, "e": 28135, "s": 28089, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28147, "s": 28135, "text": "Golang Maps" }, { "code": null, "e": 28164, "s": 28147, "text": "Slices in Golang" }, { "code": null, "e": 28218, "s": 28164, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 28240, "s": 28218, "text": "Inheritance in GoLang" } ]
Python String join() Method - GeeksforGeeks
19 Apr, 2022 Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator. Syntax: string_name.join(iterable) Parameters: The join() method takes iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set Return Value: The join() method returns a string concatenated with the elements of iterable. Type Error: If the iterable contains any non-string values, it raises a TypeError exception. Python # Python program to demonstrate the# use of join function to join list# elements with a character. list1 = ['1','2','3','4'] s = "-" # joins elements of list1 by '-'# and stores in string ss = s.join(list1) # join use to join a list of# strings to a separator sprint(s) Output: 1-2-3-4 Python # Python program to demonstrate the# use of join function to join list# elements without any separator. # Joining with empty separatorlist1 = ['g','e','e','k', 's']print("".join(list1)) Output: geeks AmiyaRanjanRout h6zqteft28todkgwkmlupd6nthpstwt8345j3o6o Python-Functions python-list python-string Python python-list 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": 25078, "s": 25050, "text": "\n19 Apr, 2022" }, { "code": null, "e": 25223, "s": 25078, "text": "Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator." }, { "code": null, "e": 25232, "s": 25223, "text": "Syntax: " }, { "code": null, "e": 25260, "s": 25232, "text": "string_name.join(iterable) " }, { "code": null, "e": 25273, "s": 25260, "text": "Parameters: " }, { "code": null, "e": 25425, "s": 25273, "text": "The join() method takes iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set" }, { "code": null, "e": 25440, "s": 25425, "text": "Return Value: " }, { "code": null, "e": 25520, "s": 25440, "text": "The join() method returns a string concatenated with the elements of iterable. " }, { "code": null, "e": 25532, "s": 25520, "text": "Type Error:" }, { "code": null, "e": 25614, "s": 25532, "text": "If the iterable contains any non-string values, it raises a TypeError exception. " }, { "code": null, "e": 25621, "s": 25614, "text": "Python" }, { "code": "# Python program to demonstrate the# use of join function to join list# elements with a character. list1 = ['1','2','3','4'] s = \"-\" # joins elements of list1 by '-'# and stores in string ss = s.join(list1) # join use to join a list of# strings to a separator sprint(s)", "e": 25891, "s": 25621, "text": null }, { "code": null, "e": 25900, "s": 25891, "text": "Output: " }, { "code": null, "e": 25908, "s": 25900, "text": "1-2-3-4" }, { "code": null, "e": 25915, "s": 25908, "text": "Python" }, { "code": "# Python program to demonstrate the# use of join function to join list# elements without any separator. # Joining with empty separatorlist1 = ['g','e','e','k', 's']print(\"\".join(list1))", "e": 26101, "s": 25915, "text": null }, { "code": null, "e": 26110, "s": 26101, "text": "Output: " }, { "code": null, "e": 26116, "s": 26110, "text": "geeks" }, { "code": null, "e": 26132, "s": 26116, "text": "AmiyaRanjanRout" }, { "code": null, "e": 26173, "s": 26132, "text": "h6zqteft28todkgwkmlupd6nthpstwt8345j3o6o" }, { "code": null, "e": 26190, "s": 26173, "text": "Python-Functions" }, { "code": null, "e": 26202, "s": 26190, "text": "python-list" }, { "code": null, "e": 26216, "s": 26202, "text": "python-string" }, { "code": null, "e": 26223, "s": 26216, "text": "Python" }, { "code": null, "e": 26235, "s": 26223, "text": "python-list" }, { "code": null, "e": 26333, "s": 26235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26361, "s": 26333, "text": "Read JSON file using Python" }, { "code": null, "e": 26411, "s": 26361, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26433, "s": 26411, "text": "Python map() function" }, { "code": null, "e": 26477, "s": 26433, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26495, "s": 26477, "text": "Python Dictionary" }, { "code": null, "e": 26518, "s": 26495, "text": "Taking input in Python" }, { "code": null, "e": 26553, "s": 26518, "text": "Read a file line by line in Python" }, { "code": null, "e": 26585, "s": 26553, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26607, "s": 26585, "text": "Enumerate() in Python" } ]
How to create new Collection in MongoDB using Node.js ? - GeeksforGeeks
01 Dec, 2020 MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON (similar to JSON format). Refer (this) article. MongoDB Module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDb database which is running on a particular server on your machine. (Refer to this article). We can also use promises in this method in resolve the object contains all the methods and properties required for collection manipulation and in reject the error occurs during connection. Installing module: node install mongodb Project structure: Running the server on Local IP: mongod --dbpath=data --bind_ip 127.0.0.1 MongoDB Database: Database:GFG Index.js: Javascript const MongoClient = require("mongodb");const url = 'mongodb://localhost:27017/';const databasename = "GFG"; // Database name MongoClient.connect(url).then((client) => { const connect = client.db(databasename); // New Collection const collection = connect .createCollection("GFGCollection"); console.log("collection created");}).catch((err) => { // Handling the error console.log(err.Message);}) Output: MongoDB database: Node.js-Misc Technical Scripter 2020 MongoDB Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB - sort() Method Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 25779, "s": 25751, "text": "\n01 Dec, 2020" }, { "code": null, "e": 26157, "s": 25779, "text": "MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON (similar to JSON format). Refer (this) article." }, { "code": null, "e": 26659, "s": 26157, "text": "MongoDB Module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDb database which is running on a particular server on your machine. (Refer to this article). We can also use promises in this method in resolve the object contains all the methods and properties required for collection manipulation and in reject the error occurs during connection." }, { "code": null, "e": 26678, "s": 26659, "text": "Installing module:" }, { "code": null, "e": 26699, "s": 26678, "text": "node install mongodb" }, { "code": null, "e": 26718, "s": 26699, "text": "Project structure:" }, { "code": null, "e": 26750, "s": 26718, "text": "Running the server on Local IP:" }, { "code": null, "e": 26791, "s": 26750, "text": "mongod --dbpath=data --bind_ip 127.0.0.1" }, { "code": null, "e": 26809, "s": 26791, "text": "MongoDB Database:" }, { "code": null, "e": 26822, "s": 26809, "text": "Database:GFG" }, { "code": null, "e": 26832, "s": 26822, "text": "Index.js:" }, { "code": null, "e": 26843, "s": 26832, "text": "Javascript" }, { "code": "const MongoClient = require(\"mongodb\");const url = 'mongodb://localhost:27017/';const databasename = \"GFG\"; // Database name MongoClient.connect(url).then((client) => { const connect = client.db(databasename); // New Collection const collection = connect .createCollection(\"GFGCollection\"); console.log(\"collection created\");}).catch((err) => { // Handling the error console.log(err.Message);})", "e": 27274, "s": 26843, "text": null }, { "code": null, "e": 27282, "s": 27274, "text": "Output:" }, { "code": null, "e": 27300, "s": 27282, "text": "MongoDB database:" }, { "code": null, "e": 27313, "s": 27300, "text": "Node.js-Misc" }, { "code": null, "e": 27337, "s": 27313, "text": "Technical Scripter 2020" }, { "code": null, "e": 27345, "s": 27337, "text": "MongoDB" }, { "code": null, "e": 27353, "s": 27345, "text": "Node.js" }, { "code": null, "e": 27372, "s": 27353, "text": "Technical Scripter" }, { "code": null, "e": 27389, "s": 27372, "text": "Web Technologies" }, { "code": null, "e": 27487, "s": 27389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27525, "s": 27487, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 27550, "s": 27525, "text": "MongoDB - limit() Method" }, { "code": null, "e": 27577, "s": 27550, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 27613, "s": 27577, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 27637, "s": 27613, "text": "MongoDB - sort() Method" }, { "code": null, "e": 27670, "s": 27637, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27718, "s": 27670, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27751, "s": 27718, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 27781, "s": 27751, "text": "Node.js fs.writeFile() Method" } ]