title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
A Tutorial on Scraping Images from the Web Using BeautifulSoup | by Acusio Bivona | Towards Data Science
In the real world of data science, it’ll often be a task that we have to obtain some or all of our data. As much as we love to work with clean, organized datasets from Kaggle, that perfection is not always replicated in day-to-day tasks at work. That’s why knowing how to scrape data is a very valuable skill to possess, and today I’m going to demonstrate how to do just that with images, along with eventually displaying your image results in a Pandas DataFrame. To start, I’m going to scrape from the website that I first learned to scrape images from, which is books.toscrape.com. This is a great site to practice all of your scraping skills on, not just image scraping. Now, the first thing you’ll want to do is import some necessary packages — BeautifulSoup and requests. from bs4 import BeautifulSoupimport requests Next, you’ll want to make a get request to retrieve your webpage and then pass the contents of the page through BeautifulSoup so that it can be parsed. html_page = requests.get('http://books.toscrape.com/')soup = BeautifulSoup(html_page.content, 'html.parser')warning = soup.find('div', class_="alert alert-warning")book_container = warning.nextSibling.nextSibling Awesome! Now, we need our images. Being efficient with BeautifulSoup means having a little bit of experience and/or understanding of HTML tags. But if you don’t, using Google to find out which tags you need in order to scrape the data you want is pretty easy. Since we want image data, we’ll use the img tag with BeautifulSoup. images = book_container.findAll('img')example = images[0]example And the output of this is the following: <img alt="A Light in the Attic" class="thumbnail" src="media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg"/> Good job! You successfully pulled the first image from this website. But, the part that is most important for us in pulling the actual image is in the beginning of line 2 where it says src=... because this is the URL. Well, it’s not quite fully a URL, but a URL extension. We want to pull that out as a separate variable, which will be done shortly. To breakdown the output a little bit more, we can use the .attrs method to pull out the URL found in src=... Look below: example.attrs['src'] Bam. That’s it! If done correctly, you should receive an output that looks like... 'media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg' Now that this has been pulled out, we can download the image locally! To do this, you’ll want to import another package called shutil. Then, instead of kind of rambling on about what’s going on with the code here, I’m going to paste the code block below and comment on the most important lines so that my brain nor your brain doesn’t explode, because it’s kind of dense :). url_base = "http://books.toscrape.com/" #Original websiteurl_ext = example.attrs['src'] #The extension you pulled earlierfull_url = url_base + url_ext #Combining first 2 variables to create a complete URLr = requests.get(full_url, stream=True) #Get request on full_urlif r.status_code == 200: #200 status code = OK with open("images/book1.jpg", 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) The last block of code where the if statement starts essentially is saying that if you get the OK status code (200), it is going to open the image from book 1 (“A Light In The Attic” — the same book from you URL scrape), decode the raw content, and then save the image onto your local machine. You’re doing great! Now that you have your first image downloaded, you’ll want to preview that image to make sure that it was downloaded correctly. To do this, you’ll need to import two more packages — matplotlib.pyplot and matplotlib.image. import matplotlib.pyplot as pltimport matplotlib.image as mpim To preview your image, run the following code: img = mpimg.imread('images/book1.jpg')imgplot = plt.imshow(img)plt.show() And your output will be.. *drumroll* Your image! Congratulations! From here, the final thing you’ll want to do is display this in a Pandas DataFrame. We have a couple more packages that need to be imported, and I’m going to display the code right underneath that. import pandas as pdfrom IPython.display import Image, HTMLrow_1 = [example.attrs['alt'], '<img src="images/book1.jpg"/>']df = pd.DataFrame(row_1).transpose()df.columns = ['Title', 'Cover']HTML(df.to_html(escape=False)) And voila! You have now converted an image you found on the Internet into a Pandas DataFrame! Obviously, you can write your code so that you can scrape an entire webpage at one time by writing a function instead of doing this process over and over again for each entry. But, this concludes my blog post. Thank you for reading and I hope this helped you learn something new or helped better your scraping skills!
[ { "code": null, "e": 636, "s": 172, "text": "In the real world of data science, it’ll often be a task that we have to obtain some or all of our data. As much as we love to work with clean, organized datasets from Kaggle, that perfection is not always replicated in day-to-day tasks at work. That’s why knowing how to scrape data is a very valuable skill to possess, and today I’m going to demonstrate how to do just that with images, along with eventually displaying your image results in a Pandas DataFrame." }, { "code": null, "e": 949, "s": 636, "text": "To start, I’m going to scrape from the website that I first learned to scrape images from, which is books.toscrape.com. This is a great site to practice all of your scraping skills on, not just image scraping. Now, the first thing you’ll want to do is import some necessary packages — BeautifulSoup and requests." }, { "code": null, "e": 994, "s": 949, "text": "from bs4 import BeautifulSoupimport requests" }, { "code": null, "e": 1146, "s": 994, "text": "Next, you’ll want to make a get request to retrieve your webpage and then pass the contents of the page through BeautifulSoup so that it can be parsed." }, { "code": null, "e": 1359, "s": 1146, "text": "html_page = requests.get('http://books.toscrape.com/')soup = BeautifulSoup(html_page.content, 'html.parser')warning = soup.find('div', class_=\"alert alert-warning\")book_container = warning.nextSibling.nextSibling" }, { "code": null, "e": 1687, "s": 1359, "text": "Awesome! Now, we need our images. Being efficient with BeautifulSoup means having a little bit of experience and/or understanding of HTML tags. But if you don’t, using Google to find out which tags you need in order to scrape the data you want is pretty easy. Since we want image data, we’ll use the img tag with BeautifulSoup." }, { "code": null, "e": 1752, "s": 1687, "text": "images = book_container.findAll('img')example = images[0]example" }, { "code": null, "e": 1793, "s": 1752, "text": "And the output of this is the following:" }, { "code": null, "e": 1906, "s": 1793, "text": "<img alt=\"A Light in the Attic\" class=\"thumbnail\" src=\"media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg\"/>" }, { "code": null, "e": 2377, "s": 1906, "text": "Good job! You successfully pulled the first image from this website. But, the part that is most important for us in pulling the actual image is in the beginning of line 2 where it says src=... because this is the URL. Well, it’s not quite fully a URL, but a URL extension. We want to pull that out as a separate variable, which will be done shortly. To breakdown the output a little bit more, we can use the .attrs method to pull out the URL found in src=... Look below:" }, { "code": null, "e": 2398, "s": 2377, "text": "example.attrs['src']" }, { "code": null, "e": 2481, "s": 2398, "text": "Bam. That’s it! If done correctly, you should receive an output that looks like..." }, { "code": null, "e": 2538, "s": 2481, "text": "'media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg'" }, { "code": null, "e": 2912, "s": 2538, "text": "Now that this has been pulled out, we can download the image locally! To do this, you’ll want to import another package called shutil. Then, instead of kind of rambling on about what’s going on with the code here, I’m going to paste the code block below and comment on the most important lines so that my brain nor your brain doesn’t explode, because it’s kind of dense :)." }, { "code": null, "e": 3365, "s": 2912, "text": "url_base = \"http://books.toscrape.com/\" #Original websiteurl_ext = example.attrs['src'] #The extension you pulled earlierfull_url = url_base + url_ext #Combining first 2 variables to create a complete URLr = requests.get(full_url, stream=True) #Get request on full_urlif r.status_code == 200: #200 status code = OK with open(\"images/book1.jpg\", 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f)" }, { "code": null, "e": 3659, "s": 3365, "text": "The last block of code where the if statement starts essentially is saying that if you get the OK status code (200), it is going to open the image from book 1 (“A Light In The Attic” — the same book from you URL scrape), decode the raw content, and then save the image onto your local machine." }, { "code": null, "e": 3901, "s": 3659, "text": "You’re doing great! Now that you have your first image downloaded, you’ll want to preview that image to make sure that it was downloaded correctly. To do this, you’ll need to import two more packages — matplotlib.pyplot and matplotlib.image." }, { "code": null, "e": 3964, "s": 3901, "text": "import matplotlib.pyplot as pltimport matplotlib.image as mpim" }, { "code": null, "e": 4011, "s": 3964, "text": "To preview your image, run the following code:" }, { "code": null, "e": 4085, "s": 4011, "text": "img = mpimg.imread('images/book1.jpg')imgplot = plt.imshow(img)plt.show()" }, { "code": null, "e": 4122, "s": 4085, "text": "And your output will be.. *drumroll*" }, { "code": null, "e": 4349, "s": 4122, "text": "Your image! Congratulations! From here, the final thing you’ll want to do is display this in a Pandas DataFrame. We have a couple more packages that need to be imported, and I’m going to display the code right underneath that." }, { "code": null, "e": 4568, "s": 4349, "text": "import pandas as pdfrom IPython.display import Image, HTMLrow_1 = [example.attrs['alt'], '<img src=\"images/book1.jpg\"/>']df = pd.DataFrame(row_1).transpose()df.columns = ['Title', 'Cover']HTML(df.to_html(escape=False))" } ]
Java static method
The static keyword is used to create methods that will exist independently of any instances created for the class. Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method. The static modifier is used to create class methods and variables, as in the following example − Live Demo public class InstanceCounter { private static int numInstances = 0; protected static int getCount() { return numInstances; } private static void addInstance() { numInstances++; } InstanceCounter() { InstanceCounter.addInstance(); } public static void main(String[] arguments) { System.out.println("Starting with " + InstanceCounter.getCount() + " instances"); for (int i = 0; i < 500; ++i) { new InstanceCounter(); } System.out.println("Created " + InstanceCounter.getCount() + " instances"); } } Started with 0 instances Created 500 instances
[ { "code": null, "e": 1177, "s": 1062, "text": "The static keyword is used to create methods that will exist independently of any instances created for the class." }, { "code": null, "e": 1400, "s": 1177, "text": "Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables." }, { "code": null, "e": 1524, "s": 1400, "text": " Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method." }, { "code": null, "e": 1621, "s": 1524, "text": "The static modifier is used to create class methods and variables, as in the following example −" }, { "code": null, "e": 1631, "s": 1621, "text": "Live Demo" }, { "code": null, "e": 2212, "s": 1631, "text": "public class InstanceCounter {\n\n private static int numInstances = 0;\n\n protected static int getCount() {\n return numInstances;\n }\n\n private static void addInstance() {\n numInstances++;\n }\n\n InstanceCounter() {\n InstanceCounter.addInstance();\n }\n\n public static void main(String[] arguments) {\n System.out.println(\"Starting with \" + InstanceCounter.getCount() + \" instances\");\n\n for (int i = 0; i < 500; ++i) {\n new InstanceCounter();\n }\n System.out.println(\"Created \" + InstanceCounter.getCount() + \" instances\");\n }\n}" }, { "code": null, "e": 2259, "s": 2212, "text": "Started with 0 instances\nCreated 500 instances" } ]
Camel and Banana Puzzle | DP - GeeksforGeeks
21 Oct, 2021 A person wants to transfer bananas over to a destination A km away. He initially has B bananas and a camel. The camel cannot carry more than C bananas at a time and eats a banana every km it travels. Given three integers A, B, and C, the task is to find the maximum number of bananas the person can transfer to the destination using the camel. Note: The given problem is a generalized version of the famous Camel-Banana puzzle. Examples: Input: A = 10, B = 30, C = 10 Output: 5 Input: A = 1000, B = 3000, C = 1000Output: 533 Approach: The given problem can be solved with the help of Dynamic Programming using Memoization using the following key points: It can be observed that the most effective way to transfer bananas is to divide the path (u, v) having A km into some smaller parts. Suppose x is a breakpoint in the path (u, v). The optimal choice is to transfer all the bananas from u to x and then from x to v. There can be any number of breakpoints in the path (u, v) such that the count of breakpoints < A. The total number of trips the camel which can carry C bananas at a time has to make in order to transfer X bananas over any distance can be calculated by the formula 2 * X / C – 1, if C is a factor of X (i.e, X % C = 0) otherwise 2 * X / C +1. Using the above observations, the given problem can be solved by following the below steps: Consider a 2D array dp[][], where a state dp[A][B] represents the maximum number of bananas a camel can transfer over a distance of A km having B bananas initially. Initialize the dp[][] array with -1. Create a recursive function to iterate over the given path of A km and create a breakpoint at each valid index and recursively call the function for the remaining path. Memoize the maximum number of bananas for each state and return the memorized value if the current state is already calculated. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Stores the overlapping stateint dp[1001][3001]; // Recursive function to find the maximum// number of bananas that can be transferred// to A distance using memoizationint recBananaCnt(int A, int B, int C){ // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A][B] != -1) { return dp[A][B]; } // Stores the maximum count of bananas int maxCount = INT_MIN; // Stores the number of trips to transfer // B bananas using a camel of capacity C int tripCount = B % C == 0 ? ((2 * B) / C) - 1 : ((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (int i = 1; i <= A; i++) { // Recursive call over the // remaining path int curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A][B] = maxCount; } } // Return answer return maxCount;} // Function to find the maximum number of// bananas that can be transferredint maxBananaCnt(int A, int B, int C){ // Initialize dp array with -1 memset(dp, -1, sizeof(dp)); // Function Call return recBananaCnt(A, B, C);} // Driver Codeint main(){ int A = 1000; int B = 3000; int C = 1000; cout << maxBananaCnt(A, B, C); return 0;} // Java program of the above approachpublic class GFG { // Stores the overlapping state final static int dp[][] = new int[1001][3001]; // Recursive function to find the maximum // number of bananas that can be transferred // to A distance using memoization static int recBananaCnt(int A, int B, int C) { // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A][B] != -1) { return dp[A][B]; } // Stores the maximum count of bananas int maxCount = Integer.MIN_VALUE; // Stores the number of trips to transfer // B bananas using a camel of capacity C int tripCount = B % C == 0 ? ((2 * B) / C) - 1 : ((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (int i = 1; i <= A; i++) { // Recursive call over the // remaining path int curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A][B] = maxCount; } } // Return answer return maxCount; } // Function to find the maximum number of // bananas that can be transferred static int maxBananaCnt(int A, int B, int C) { // Initialize dp array with -1 for(int i = 0; i < 1001; i++) for (int j = 0; j < 3001; j++) dp[i][j] = -1; // Function Call return recBananaCnt(A, B, C); } // Driver Code public static void main (String[] args) { int A = 1000; int B = 3000; int C = 1000; System.out.println(maxBananaCnt(A, B, C)); }} // This code is contributed by AnkThon # Python program of the above approach# Stores the overlapping statedp = [[-1 for i in range(3001)] for j in range(1001)] # Recursive function to find the maximum# number of bananas that can be transferred# to A distance using memoizationdef recBananaCnt(A, B, C): # Base Case where count of bananas # is less that the given distance if (B <= A): return 0 # Base Case where count of bananas # is less that camel's capacity if (B <= C): return B - A # Base Case where distance = 0 if (A == 0): return B # If the current state is already # calculated if (dp[A][B] != -1): return dp[A][B] # Stores the maximum count of bananas maxCount = -2**32 # Stores the number of trips to transfer # B bananas using a camel of capacity C tripCount = ((2 * B) // C) - 1 if(B % C == 0 ) else ((2 * B) // C) + 1 # Loop to iterate over all the # breakpoints in range [1, A] for i in range(1,A+1): # Recursive call over the # remaining path curCount = recBananaCnt(A - i, B - tripCount * i, C) # Update the maxCount if (curCount > maxCount): maxCount = curCount # Memoize the current value dp[A][B] = maxCount # Return answer return maxCount # Function to find the maximum number of# bananas that can be transferreddef maxBananaCnt(A, B, C): # Function Call return recBananaCnt(A, B, C) # Driver CodeA = 1000B = 3000C = 1000print(maxBananaCnt(A, B, C)) # This code is contributed by shivanisinghss2110 // C# program of the above approachusing System; public class GFG { // Stores the overlapping state static int[, ] dp = new int[1001, 3001]; // Recursive function to find the maximum // number of bananas that can be transferred // to A distance using memoization static int recBananaCnt(int A, int B, int C) { // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A, B] != -1) { return dp[A, B]; } // Stores the maximum count of bananas int maxCount = Int32.MinValue; // Stores the number of trips to transfer // B bananas using a camel of capacity C int tripCount = B % C == 0 ? ((2 * B) / C) - 1 : ((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (int i = 1; i <= A; i++) { // Recursive call over the // remaining path int curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A, B] = maxCount; } } // Return answer return maxCount; } // Function to find the maximum number of // bananas that can be transferred static int maxBananaCnt(int A, int B, int C) { // Initialize dp array with -1 for (int i = 0; i < 1001; i++) for (int j = 0; j < 3001; j++) dp[i, j] = -1; // Function Call return recBananaCnt(A, B, C); } // Driver Code public static void Main(string[] args) { int A = 1000; int B = 3000; int C = 1000; Console.WriteLine(maxBananaCnt(A, B, C)); }} // This code is contributed by ukasp. <script> // JavaScript Program to implement // the above approach // Stores the overlapping state // Initialize dp array with -1 let dp = new Array(1001); for (let i = 0; i < dp.length; i++) { dp[i] = (new Array(3001).fill(-1)) } // Recursive function to find the maximum // number of bananas that can be transferred // to A distance using memoization function recBananaCnt(A, B, C) { // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A][B] != -1) { return dp[A][B]; } // Stores the maximum count of bananas let maxCount = Number.MIN_VALUE; // Stores the number of trips to transfer // B bananas using a camel of capacity C let tripCount = B % C == 0 ? Math.floor((2 * B) / C) - 1 : Math.floor((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (let i = 1; i <= A; i++) { // Recursive call over the // remaining path let curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A][B] = maxCount; } } // Return answer return maxCount; } // Function to find the maximum number of // bananas that can be transferred function maxBananaCnt(A, B, C) { // Function Call return recBananaCnt(A, B, C); } // Driver Code let A = 1000; let B = 3000; let C = 1000; document.write(maxBananaCnt(A, B, C)); // This code is contributed by Potta Lokesh </script> 533 Time Complexity: O(A*A*B)Auxiliary Space: O(A*B) lokeshpotta20 ankthon ukasp shivanisinghss2110 arorakashish0911 nayanmathur Google Puzzles Dynamic Programming Mathematical Puzzles Recursion Google Dynamic Programming Mathematical Recursion Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Optimal Substructure Property in Dynamic Programming | DP-2 Maximum Subarray Sum using Divide and Conquer algorithm Min Cost Path | DP-6 3 Different ways to print Fibonacci series in Java Gold Mine Problem C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 24281, "s": 24253, "text": "\n21 Oct, 2021" }, { "code": null, "e": 24625, "s": 24281, "text": "A person wants to transfer bananas over to a destination A km away. He initially has B bananas and a camel. The camel cannot carry more than C bananas at a time and eats a banana every km it travels. Given three integers A, B, and C, the task is to find the maximum number of bananas the person can transfer to the destination using the camel." }, { "code": null, "e": 24709, "s": 24625, "text": "Note: The given problem is a generalized version of the famous Camel-Banana puzzle." }, { "code": null, "e": 24719, "s": 24709, "text": "Examples:" }, { "code": null, "e": 24759, "s": 24719, "text": "Input: A = 10, B = 30, C = 10 Output: 5" }, { "code": null, "e": 24806, "s": 24759, "text": "Input: A = 1000, B = 3000, C = 1000Output: 533" }, { "code": null, "e": 24935, "s": 24806, "text": "Approach: The given problem can be solved with the help of Dynamic Programming using Memoization using the following key points:" }, { "code": null, "e": 25198, "s": 24935, "text": "It can be observed that the most effective way to transfer bananas is to divide the path (u, v) having A km into some smaller parts. Suppose x is a breakpoint in the path (u, v). The optimal choice is to transfer all the bananas from u to x and then from x to v." }, { "code": null, "e": 25296, "s": 25198, "text": "There can be any number of breakpoints in the path (u, v) such that the count of breakpoints < A." }, { "code": null, "e": 25540, "s": 25296, "text": "The total number of trips the camel which can carry C bananas at a time has to make in order to transfer X bananas over any distance can be calculated by the formula 2 * X / C – 1, if C is a factor of X (i.e, X % C = 0) otherwise 2 * X / C +1." }, { "code": null, "e": 25633, "s": 25540, "text": " Using the above observations, the given problem can be solved by following the below steps:" }, { "code": null, "e": 25835, "s": 25633, "text": "Consider a 2D array dp[][], where a state dp[A][B] represents the maximum number of bananas a camel can transfer over a distance of A km having B bananas initially. Initialize the dp[][] array with -1." }, { "code": null, "e": 26004, "s": 25835, "text": "Create a recursive function to iterate over the given path of A km and create a breakpoint at each valid index and recursively call the function for the remaining path." }, { "code": null, "e": 26132, "s": 26004, "text": "Memoize the maximum number of bananas for each state and return the memorized value if the current state is already calculated." }, { "code": null, "e": 26183, "s": 26132, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26187, "s": 26183, "text": "C++" }, { "code": null, "e": 26192, "s": 26187, "text": "Java" }, { "code": null, "e": 26200, "s": 26192, "text": "Python3" }, { "code": null, "e": 26203, "s": 26200, "text": "C#" }, { "code": null, "e": 26214, "s": 26203, "text": "Javascript" }, { "code": "// C++ program of the above approach#include <bits/stdc++.h>using namespace std; // Stores the overlapping stateint dp[1001][3001]; // Recursive function to find the maximum// number of bananas that can be transferred// to A distance using memoizationint recBananaCnt(int A, int B, int C){ // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A][B] != -1) { return dp[A][B]; } // Stores the maximum count of bananas int maxCount = INT_MIN; // Stores the number of trips to transfer // B bananas using a camel of capacity C int tripCount = B % C == 0 ? ((2 * B) / C) - 1 : ((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (int i = 1; i <= A; i++) { // Recursive call over the // remaining path int curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A][B] = maxCount; } } // Return answer return maxCount;} // Function to find the maximum number of// bananas that can be transferredint maxBananaCnt(int A, int B, int C){ // Initialize dp array with -1 memset(dp, -1, sizeof(dp)); // Function Call return recBananaCnt(A, B, C);} // Driver Codeint main(){ int A = 1000; int B = 3000; int C = 1000; cout << maxBananaCnt(A, B, C); return 0;}", "e": 28037, "s": 26214, "text": null }, { "code": "// Java program of the above approachpublic class GFG { // Stores the overlapping state final static int dp[][] = new int[1001][3001]; // Recursive function to find the maximum // number of bananas that can be transferred // to A distance using memoization static int recBananaCnt(int A, int B, int C) { // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A][B] != -1) { return dp[A][B]; } // Stores the maximum count of bananas int maxCount = Integer.MIN_VALUE; // Stores the number of trips to transfer // B bananas using a camel of capacity C int tripCount = B % C == 0 ? ((2 * B) / C) - 1 : ((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (int i = 1; i <= A; i++) { // Recursive call over the // remaining path int curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A][B] = maxCount; } } // Return answer return maxCount; } // Function to find the maximum number of // bananas that can be transferred static int maxBananaCnt(int A, int B, int C) { // Initialize dp array with -1 for(int i = 0; i < 1001; i++) for (int j = 0; j < 3001; j++) dp[i][j] = -1; // Function Call return recBananaCnt(A, B, C); } // Driver Code public static void main (String[] args) { int A = 1000; int B = 3000; int C = 1000; System.out.println(maxBananaCnt(A, B, C)); }} // This code is contributed by AnkThon", "e": 30356, "s": 28037, "text": null }, { "code": "# Python program of the above approach# Stores the overlapping statedp = [[-1 for i in range(3001)] for j in range(1001)] # Recursive function to find the maximum# number of bananas that can be transferred# to A distance using memoizationdef recBananaCnt(A, B, C): # Base Case where count of bananas # is less that the given distance if (B <= A): return 0 # Base Case where count of bananas # is less that camel's capacity if (B <= C): return B - A # Base Case where distance = 0 if (A == 0): return B # If the current state is already # calculated if (dp[A][B] != -1): return dp[A][B] # Stores the maximum count of bananas maxCount = -2**32 # Stores the number of trips to transfer # B bananas using a camel of capacity C tripCount = ((2 * B) // C) - 1 if(B % C == 0 ) else ((2 * B) // C) + 1 # Loop to iterate over all the # breakpoints in range [1, A] for i in range(1,A+1): # Recursive call over the # remaining path curCount = recBananaCnt(A - i, B - tripCount * i, C) # Update the maxCount if (curCount > maxCount): maxCount = curCount # Memoize the current value dp[A][B] = maxCount # Return answer return maxCount # Function to find the maximum number of# bananas that can be transferreddef maxBananaCnt(A, B, C): # Function Call return recBananaCnt(A, B, C) # Driver CodeA = 1000B = 3000C = 1000print(maxBananaCnt(A, B, C)) # This code is contributed by shivanisinghss2110", "e": 31945, "s": 30356, "text": null }, { "code": "// C# program of the above approachusing System; public class GFG { // Stores the overlapping state static int[, ] dp = new int[1001, 3001]; // Recursive function to find the maximum // number of bananas that can be transferred // to A distance using memoization static int recBananaCnt(int A, int B, int C) { // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A, B] != -1) { return dp[A, B]; } // Stores the maximum count of bananas int maxCount = Int32.MinValue; // Stores the number of trips to transfer // B bananas using a camel of capacity C int tripCount = B % C == 0 ? ((2 * B) / C) - 1 : ((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (int i = 1; i <= A; i++) { // Recursive call over the // remaining path int curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A, B] = maxCount; } } // Return answer return maxCount; } // Function to find the maximum number of // bananas that can be transferred static int maxBananaCnt(int A, int B, int C) { // Initialize dp array with -1 for (int i = 0; i < 1001; i++) for (int j = 0; j < 3001; j++) dp[i, j] = -1; // Function Call return recBananaCnt(A, B, C); } // Driver Code public static void Main(string[] args) { int A = 1000; int B = 3000; int C = 1000; Console.WriteLine(maxBananaCnt(A, B, C)); }} // This code is contributed by ukasp.", "e": 34183, "s": 31945, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Stores the overlapping state // Initialize dp array with -1 let dp = new Array(1001); for (let i = 0; i < dp.length; i++) { dp[i] = (new Array(3001).fill(-1)) } // Recursive function to find the maximum // number of bananas that can be transferred // to A distance using memoization function recBananaCnt(A, B, C) { // Base Case where count of bananas // is less that the given distance if (B <= A) { return 0; } // Base Case where count of bananas // is less that camel's capacity if (B <= C) { return B - A; } // Base Case where distance = 0 if (A == 0) { return B; } // If the current state is already // calculated if (dp[A][B] != -1) { return dp[A][B]; } // Stores the maximum count of bananas let maxCount = Number.MIN_VALUE; // Stores the number of trips to transfer // B bananas using a camel of capacity C let tripCount = B % C == 0 ? Math.floor((2 * B) / C) - 1 : Math.floor((2 * B) / C) + 1; // Loop to iterate over all the // breakpoints in range [1, A] for (let i = 1; i <= A; i++) { // Recursive call over the // remaining path let curCount = recBananaCnt(A - i, B - tripCount * i, C); // Update the maxCount if (curCount > maxCount) { maxCount = curCount; // Memoize the current value dp[A][B] = maxCount; } } // Return answer return maxCount; } // Function to find the maximum number of // bananas that can be transferred function maxBananaCnt(A, B, C) { // Function Call return recBananaCnt(A, B, C); } // Driver Code let A = 1000; let B = 3000; let C = 1000; document.write(maxBananaCnt(A, B, C)); // This code is contributed by Potta Lokesh </script>", "e": 36526, "s": 34183, "text": null }, { "code": null, "e": 36530, "s": 36526, "text": "533" }, { "code": null, "e": 36581, "s": 36532, "text": "Time Complexity: O(A*A*B)Auxiliary Space: O(A*B)" }, { "code": null, "e": 36597, "s": 36583, "text": "lokeshpotta20" }, { "code": null, "e": 36605, "s": 36597, "text": "ankthon" }, { "code": null, "e": 36611, "s": 36605, "text": "ukasp" }, { "code": null, "e": 36630, "s": 36611, "text": "shivanisinghss2110" }, { "code": null, "e": 36647, "s": 36630, "text": "arorakashish0911" }, { "code": null, "e": 36659, "s": 36647, "text": "nayanmathur" }, { "code": null, "e": 36666, "s": 36659, "text": "Google" }, { "code": null, "e": 36674, "s": 36666, "text": "Puzzles" }, { "code": null, "e": 36694, "s": 36674, "text": "Dynamic Programming" }, { "code": null, "e": 36707, "s": 36694, "text": "Mathematical" }, { "code": null, "e": 36715, "s": 36707, "text": "Puzzles" }, { "code": null, "e": 36725, "s": 36715, "text": "Recursion" }, { "code": null, "e": 36732, "s": 36725, "text": "Google" }, { "code": null, "e": 36752, "s": 36732, "text": "Dynamic Programming" }, { "code": null, "e": 36765, "s": 36752, "text": "Mathematical" }, { "code": null, "e": 36775, "s": 36765, "text": "Recursion" }, { "code": null, "e": 36783, "s": 36775, "text": "Puzzles" }, { "code": null, "e": 36881, "s": 36783, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36890, "s": 36881, "text": "Comments" }, { "code": null, "e": 36903, "s": 36890, "text": "Old Comments" }, { "code": null, "e": 36963, "s": 36903, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 37019, "s": 36963, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 37040, "s": 37019, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 37091, "s": 37040, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 37109, "s": 37091, "text": "Gold Mine Problem" }, { "code": null, "e": 37124, "s": 37109, "text": "C++ Data Types" }, { "code": null, "e": 37184, "s": 37124, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37227, "s": 37184, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 37251, "s": 37227, "text": "Merge two sorted arrays" } ]
Java Program to Find Area of circle Using Method Overloading - GeeksforGeeks
04 Dec, 2020 A circle is a simple shape consisting of all the points in the plane that are equidistant from a point known as the center of the circle. In this article, we will learn how to find the area of the circle using the method overloading. Terminology: Method Overloading: Method overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both. Area: A quantity that representhe extent of a 2-dimensional figure or shape in the plane is known as an area. Radius: The line segment from the center to any point of the circle is known as radius. Diameter: The line segment whose endpoints lie on the circle and passed through the center is known as the diameter of the circle. It is also known as the largest distance between any two points on the circle. The area of the circle is the product of the square of the radius of the circle and the value of PI. We can simply calculate the area of the circle using the following formula: Using the radius of the circle: Formula: Area of the circle: A = π * r2 Here, r is the radius of the circle. Using the diameter of the circle: Formula: Area of the circle: A = (π / 4) * d2 Here, r is the radius of the circle. Note: The value of PI in java is 3.141592653589793. Below is the implementation of the above approach: Example 1: Java // Java program to find the area of// the circle using Method Overloading import java.io.*; class Circle { static final double PI = Math.PI; // Overloaded Area() function to // calculate the area of the circle. // It takes one double parameter void Area(double r) { double A = PI * r * r; System.out.println("Area of the circle is :" + A); } // Overloaded Area() function to // calculate the area of the circle. // It takes one float parameter void Area(float r) { double A = PI * r * r; System.out.println("Area of the circle is :" + A); }} class GFG { // Driver code public static void main(String[] args) { // Creating object of Circle class Circle obj = new Circle(); // Calling function obj.Area(5); obj.Area(2.5); }} Area of the circle is :78.53981633974483 Area of the circle is :19.634954084936208 Example 2: Java // Java program to find the area of// the circle when the diameter is given// using Method Overloading import java.io.*; class Circle { static final double PI = Math.PI; // Overloaded Area() function to // calculate the area of the circle. // It takes one double parameter void Area(double D) { double A = (PI / 4) * D * D; System.out.println("Area of the circle is :" + A); } // Overloaded Area() function to // calculate the area of the circle. // It takes one float parameter void Area(float D) { double A = (PI / 4) * D * D; System.out.println("Area of the circle is :" + A); }} class GFG { // Driver code public static void main(String[] args) { // Creating object of Circle class Circle obj = new Circle(); // Calling function obj.Area(10); obj.Area(20.4); }} Area of the circle is :78.53981633974483 Area of the circle is :326.851299679482 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java LinkedList in Java Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24382, "s": 24354, "text": "\n04 Dec, 2020" }, { "code": null, "e": 24616, "s": 24382, "text": "A circle is a simple shape consisting of all the points in the plane that are equidistant from a point known as the center of the circle. In this article, we will learn how to find the area of the circle using the method overloading." }, { "code": null, "e": 24629, "s": 24616, "text": "Terminology:" }, { "code": null, "e": 24844, "s": 24629, "text": "Method Overloading: Method overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both. " }, { "code": null, "e": 24954, "s": 24844, "text": "Area: A quantity that representhe extent of a 2-dimensional figure or shape in the plane is known as an area." }, { "code": null, "e": 25042, "s": 24954, "text": "Radius: The line segment from the center to any point of the circle is known as radius." }, { "code": null, "e": 25252, "s": 25042, "text": "Diameter: The line segment whose endpoints lie on the circle and passed through the center is known as the diameter of the circle. It is also known as the largest distance between any two points on the circle." }, { "code": null, "e": 25429, "s": 25252, "text": "The area of the circle is the product of the square of the radius of the circle and the value of PI. We can simply calculate the area of the circle using the following formula:" }, { "code": null, "e": 25461, "s": 25429, "text": "Using the radius of the circle:" }, { "code": null, "e": 25470, "s": 25461, "text": "Formula:" }, { "code": null, "e": 25502, "s": 25470, "text": "Area of the circle: A = π * r2" }, { "code": null, "e": 25539, "s": 25502, "text": "Here, r is the radius of the circle." }, { "code": null, "e": 25573, "s": 25539, "text": "Using the diameter of the circle:" }, { "code": null, "e": 25582, "s": 25573, "text": "Formula:" }, { "code": null, "e": 25620, "s": 25582, "text": "Area of the circle: A = (π / 4) * d2" }, { "code": null, "e": 25657, "s": 25620, "text": "Here, r is the radius of the circle." }, { "code": null, "e": 25710, "s": 25657, "text": "Note: The value of PI in java is 3.141592653589793. " }, { "code": null, "e": 25761, "s": 25710, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25772, "s": 25761, "text": "Example 1:" }, { "code": null, "e": 25777, "s": 25772, "text": "Java" }, { "code": "// Java program to find the area of// the circle using Method Overloading import java.io.*; class Circle { static final double PI = Math.PI; // Overloaded Area() function to // calculate the area of the circle. // It takes one double parameter void Area(double r) { double A = PI * r * r; System.out.println(\"Area of the circle is :\" + A); } // Overloaded Area() function to // calculate the area of the circle. // It takes one float parameter void Area(float r) { double A = PI * r * r; System.out.println(\"Area of the circle is :\" + A); }} class GFG { // Driver code public static void main(String[] args) { // Creating object of Circle class Circle obj = new Circle(); // Calling function obj.Area(5); obj.Area(2.5); }}", "e": 26633, "s": 25777, "text": null }, { "code": null, "e": 26716, "s": 26633, "text": "Area of the circle is :78.53981633974483\nArea of the circle is :19.634954084936208" }, { "code": null, "e": 26727, "s": 26716, "text": "Example 2:" }, { "code": null, "e": 26732, "s": 26727, "text": "Java" }, { "code": "// Java program to find the area of// the circle when the diameter is given// using Method Overloading import java.io.*; class Circle { static final double PI = Math.PI; // Overloaded Area() function to // calculate the area of the circle. // It takes one double parameter void Area(double D) { double A = (PI / 4) * D * D; System.out.println(\"Area of the circle is :\" + A); } // Overloaded Area() function to // calculate the area of the circle. // It takes one float parameter void Area(float D) { double A = (PI / 4) * D * D; System.out.println(\"Area of the circle is :\" + A); }} class GFG { // Driver code public static void main(String[] args) { // Creating object of Circle class Circle obj = new Circle(); // Calling function obj.Area(10); obj.Area(20.4); }}", "e": 27631, "s": 26732, "text": null }, { "code": null, "e": 27712, "s": 27631, "text": "Area of the circle is :78.53981633974483\nArea of the circle is :326.851299679482" }, { "code": null, "e": 27719, "s": 27712, "text": "Picked" }, { "code": null, "e": 27724, "s": 27719, "text": "Java" }, { "code": null, "e": 27738, "s": 27724, "text": "Java Programs" }, { "code": null, "e": 27743, "s": 27738, "text": "Java" }, { "code": null, "e": 27841, "s": 27743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27850, "s": 27841, "text": "Comments" }, { "code": null, "e": 27863, "s": 27850, "text": "Old Comments" }, { "code": null, "e": 27882, "s": 27863, "text": "Interfaces in Java" }, { "code": null, "e": 27900, "s": 27882, "text": "ArrayList in Java" }, { "code": null, "e": 27932, "s": 27900, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27952, "s": 27932, "text": "Stack Class in Java" }, { "code": null, "e": 27971, "s": 27952, "text": "LinkedList in Java" }, { "code": null, "e": 27999, "s": 27971, "text": "Initializing a List in Java" }, { "code": null, "e": 28043, "s": 27999, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28069, "s": 28043, "text": "Java Programming Examples" }, { "code": null, "e": 28103, "s": 28069, "text": "Convert Double to Integer in Java" } ]
C++ 'a.out' not recognised as a command
Having entered following command from linux terminal − $ g++ helloworld.cpp The a.out file should be created in the current working directory if the compilation is successful. Check if a.out is created. To execute enter following from command line − $ ./a.out In most cases, output of your source program is displayed. However, as in your case, error message indicating a.out is not executable is appearing. See the properties of a.out and make it executable (if not already) by following command − $ chmod +x a.out You may require sudo privilege for this. In all probability this should work. all the best
[ { "code": null, "e": 1117, "s": 1062, "text": "Having entered following command from linux terminal −" }, { "code": null, "e": 1138, "s": 1117, "text": "$ g++ helloworld.cpp" }, { "code": null, "e": 1265, "s": 1138, "text": "The a.out file should be created in the current working directory if the compilation is successful. Check if a.out is created." }, { "code": null, "e": 1312, "s": 1265, "text": "To execute enter following from command line −" }, { "code": null, "e": 1322, "s": 1312, "text": "$ ./a.out" }, { "code": null, "e": 1561, "s": 1322, "text": "In most cases, output of your source program is displayed. However, as in your case, error message indicating a.out is not executable is appearing. See the properties of a.out and make it executable (if not already) by following command −" }, { "code": null, "e": 1578, "s": 1561, "text": "$ chmod +x a.out" }, { "code": null, "e": 1669, "s": 1578, "text": "You may require sudo privilege for this. In all probability this should work. all the best" } ]
Convert PDF to Image in Python Using PyMuPDF | by Ednalyn C. De Dios | Towards Data Science
Recently, I was playing around with Amazon Textract when I ran into a little problem. Textract’s synchronous operation requires that the input document is in an image format. I had a bunch (hundreds) of PDFs to process; how was I supposed to convert each of them to PNGs without breaking a sweat? PyMuPDF to the rescue! Let’s fire up a terminal and type in the following: pip install PyMuPDF Then, let’s start a Jupyter Notebook and type in the following code: Don’t forget to change the source path on line #8 (pdfs) and the destination path on line #15 (pngs). And that’s it! Thanks for stopping by and reading my post. I hope PyMuPDF can help you as much as it helped me! In my subsequent post, I will attempt to port this code over to AWS... maybe. Stay tuned! If you want to learn more about my journey from slacker to data scientist, check out the article below: towardsdatascience.com And if you’re thinking about switching gears and venture into data science, start thinking about rebranding now: towardsdatascience.com You can reach me on Twitter or LinkedIn.
[ { "code": null, "e": 468, "s": 171, "text": "Recently, I was playing around with Amazon Textract when I ran into a little problem. Textract’s synchronous operation requires that the input document is in an image format. I had a bunch (hundreds) of PDFs to process; how was I supposed to convert each of them to PNGs without breaking a sweat?" }, { "code": null, "e": 491, "s": 468, "text": "PyMuPDF to the rescue!" }, { "code": null, "e": 543, "s": 491, "text": "Let’s fire up a terminal and type in the following:" }, { "code": null, "e": 563, "s": 543, "text": "pip install PyMuPDF" }, { "code": null, "e": 632, "s": 563, "text": "Then, let’s start a Jupyter Notebook and type in the following code:" }, { "code": null, "e": 734, "s": 632, "text": "Don’t forget to change the source path on line #8 (pdfs) and the destination path on line #15 (pngs)." }, { "code": null, "e": 749, "s": 734, "text": "And that’s it!" }, { "code": null, "e": 924, "s": 749, "text": "Thanks for stopping by and reading my post. I hope PyMuPDF can help you as much as it helped me! In my subsequent post, I will attempt to port this code over to AWS... maybe." }, { "code": null, "e": 936, "s": 924, "text": "Stay tuned!" }, { "code": null, "e": 1040, "s": 936, "text": "If you want to learn more about my journey from slacker to data scientist, check out the article below:" }, { "code": null, "e": 1063, "s": 1040, "text": "towardsdatascience.com" }, { "code": null, "e": 1176, "s": 1063, "text": "And if you’re thinking about switching gears and venture into data science, start thinking about rebranding now:" }, { "code": null, "e": 1199, "s": 1176, "text": "towardsdatascience.com" } ]
Get the count of the number of documents in a MongoDB Collection?
To get the count of the number of documents in a collection MongoDB, you can use the below syntax − db.getCollectionNames().map(function(anyVariableName) { return { "yourVariableName": yourVariableName, "count": db[yourVariableName].count() } }); Here, we are using ‘test’ database. Let us implement the above syntax to get the count of the number of documents in a MongoDB collection − > db.getCollectionNames().map(function(ColName) { ... return { "ColName": ColName, "TotalDocument": db[ColName].count() } ... }); This will produce the following output − [ { "ColName" : "ConvertStringToDateDemo", "TotalDocument" : 4 }, { "ColName" : "Employee_Information", "TotalDocument" : 2 }, { "ColName" : "IdUpdateDemo", "TotalDocument" : 3 }, { "ColName" : "IndexingDemo", "TotalDocument" : 1 }, { "ColName" : "NotAndDemo", "TotalDocument" : 5 }, { "ColName" : "ProductsInformation", "TotalDocument" : 2 }, { "ColName" : "addCurrentDateTimeDemo", "TotalDocument" : 4 }, { "ColName" : "addFieldDemo", "TotalDocument" : 1 }, { "ColName" : "addNewFieldToEveryDocument", "TotalDocument" : 4 }, { "ColName" : "addingNewPropertyDemo", "TotalDocument" : 3 }, { "ColName" : "aggregateSumDemo", "TotalDocument" : 4 }, { "ColName" : "aggregationFrameworkWithOrMatchDemo", "TotalDocument" : 6 }, { "ColName" : "aggregationSortDemo", "TotalDocument" : 6 }, { "ColName" : "andOrDemo", "TotalDocument" : 2 }, { "ColName" : "arrayInnerElementsDemo", "TotalDocument" : 1 }, { "ColName" : "arrayLengthGreaterThanOne", "TotalDocument" : 3 }, { "ColName" : "arrayOfArraysDemo", "TotalDocument" : 2 }, { "ColName" : "averageAggregationDemo", "TotalDocument" : 5 }, { "ColName" : "avoidDuplicateEntriesDemo", "TotalDocument" : 2 }, { "ColName" : "caseInsensitiveDemo", "TotalDocument" : 13 }, { "ColName" : "caseInsesitiveDemo", "TotalDocument" : 3 }, { "ColName" : "castingDemo", "TotalDocument" : 6 }, { "ColName" : "changeDataType", "TotalDocument" : 1 }, { "ColName" : "changeIntegerToStringDemo", "TotalDocument" : 4 }, { "ColName" : "changeType", "TotalDocument" : 1 }, { "ColName" : "charactersAllowedDemo", "TotalDocument" : 2 }, { "ColName" : "charactersDemo", "TotalDocument" : 3 }, { "ColName" : "check", "TotalDocument" : 1 }, { "ColName" : "checkDemo", "TotalDocument" : 2 }, { "ColName" : "checkFieldContainsStringDemo", "TotalDocument" : 6 }, { "ColName" : "checkFieldExistsOrNotDemo", "TotalDocument" : 4 }, { "ColName" : "checkIfFieldIsNumberDemo", "TotalDocument" : 4 }, { "ColName" : "checkSequenceDemo", "TotalDocument" : 3 }, { "ColName" : "cloneObjectDemo", "TotalDocument" : 5 }, { "ColName" : "collectionOnDifferentDocumentDemo", "TotalDocument" : 3 }, { "ColName" : "combinationOfArrayDemo", "TotalDocument" : 3 }, { "ColName" : "comparingFieldDemo", "TotalDocument" : 4 }, { "ColName" : "comparingTwoFieldsDemo", "TotalDocument" : 4 }, { "ColName" : "componentOfDateDemo", "TotalDocument" : 1 }, { "ColName" : "concatStringAndIntDemo", "TotalDocument" : 5 }, { "ColName" : "concatenateStringsDemo", "TotalDocument" : 5 }, { "ColName" : "conditionalSumDemo", "TotalDocument" : 8 }, { "ColName" : "conditionalUpdatesDemo", "TotalDocument" : 3 }, { "ColName" : "conditionallyUpsertDemo", "TotalDocument" : 3 }, { "ColName" : "convertStringToNumberDemo", "TotalDocument" : 3 }, { "ColName" : "convertingISODateToNumerical", "TotalDocument" : 3 }, { "ColName" : "copyThisCollectionToSampleDatabaseDemo", "TotalDocument" : 3 }, { "ColName" : "countDemo", "TotalDocument" : 4 }, { "ColName" : "countNumberOfDocumentsDemo", "TotalDocument" : 3 }, { "ColName" : "countPerformanceDemo", "TotalDocument" : 7 }, { "ColName" : "createSequenceDemo", "TotalDocument" : 1 }, { "ColName" : "creatingUniqueIndexDemo", "TotalDocument" : 3 }, { "ColName" : "dateDemo", "TotalDocument" : 1 }, { "ColName" : "dateTimeValueLessThanNowDemo", "TotalDocument" : 4 }, { "ColName" : "deleteAllElementsInArrayDemo", "TotalDocument" : 2 }, { "ColName" : "deleteDocumentsDemo", "TotalDocument" : 2 }, { "ColName" : "deleteFieldDemo", "TotalDocument" : 3 }, { "ColName" : "deleteRecordDemo", "TotalDocument" : 4 }, { "ColName" : "deletingDocumentDemo", "TotalDocument" : 3 }, { "ColName" : "demo.insertCollection", "TotalDocument" : 1 }, { "ColName" : "determineFieldExistsDemo", "TotalDocument" : 4 }, { "ColName" : "distinctAggregation", "TotalDocument" : 3 }, { "ColName" : "distinctCountValuesDemo", "TotalDocument" : 2 }, { "ColName" : "distinctRecordDemo", "TotalDocument" : 7 }, { "ColName" : "distinctWithMultipleKeysDemo", "TotalDocument" : 5 }, { "ColName" : "doubleNestedArrayDemo", "TotalDocument" : 2 }, { "ColName" : "emailUniqueDemo", "TotalDocument" : 2 }, { "ColName" : "embeddedCollectionDemo", "TotalDocument" : 0 }, { "ColName" : "embeddedDocumentDemo", "TotalDocument" : 0 }, { "ColName" : "employeeInformation", "TotalDocument" : 5 }, { "ColName" : "equivalentForSelectColumn1Column2Demo", "TotalDocument" : 3 }, { "ColName" : "exactMatchArrayDemo", "TotalDocument" : 2 }, { "ColName" : "existsDemo", "TotalDocument" : 1 }, { "ColName" : "existsReturnDemo", "TotalDocument" : 1 }, { "ColName" : "extractSubArrayDemo", "TotalDocument" : 1 }, { "ColName" : "fieldIsNullOrNotSetDemo", "TotalDocument" : 5 }, { "ColName" : "filterArray", "TotalDocument" : 1 }, { "ColName" : "findADocumentWithCondition", "TotalDocument" : 1 }, { "ColName" : "findAllDuplicateKeyDocumentDemo", "TotalDocument" : 7 }, { "ColName" : "findAllNonDistinctDemo", "TotalDocument" : 8 }, { "ColName" : "findByFieldName", "TotalDocument" : 2 }, { "ColName" : "findByMultipleArrayDemo", "TotalDocument" : 4 }, { "ColName" : "findDocumentDoNotHaveCertainFields", "TotalDocument" : 3 }, { "ColName" : "findDocumentNonExistenceFieldDemo", "TotalDocument" : 2 }, { "ColName" : "findDocumentWithObjectIdDemo", "TotalDocument" : 3 }, { "ColName" : "findDuplicateByKeyDemo", "TotalDocument" : 6 }, { "ColName" : "findDuplicateRecordsDemo", "TotalDocument" : 6 }, { "ColName" : "findMinValueDemo", "TotalDocument" : 5 }, { "ColName" : "findMultipleWordsDemo", "TotalDocument" : 6 }, { "ColName" : "findRecordByIdDemo", "TotalDocument" : 4 }, { "ColName" : "findSpecificValue", "TotalDocument" : 2 }, { "ColName" : "findValueInArrayWithMultipleCriteriaDemo", "TotalDocument" : 2 }, { "ColName" : "firstDocumentDemo", "TotalDocument" : 3 }, { "ColName" : "firstElementOfArray", "TotalDocument" : 2 }, { "ColName" : "firstItemInArrayToNewFieldDemo", "TotalDocument" : 2 }, { "ColName" : "firstLevelArrayDemo", "TotalDocument" : 2 }, { "ColName" : "flightInformation", "TotalDocument" : 2 }, { "ColName" : "foo2", "TotalDocument" : 2 }, { "ColName" : "getAllValue", "TotalDocument" : 2 }, { "ColName" : "getDistinctListOfSubDocumentFieldDemo", "TotalDocument" : 3 }, { "ColName" : "getDistinctWithSortedDataDemo", "TotalDocument" : 7 }, { "ColName" : "getDocuementsByTagsDemo", "TotalDocument" : 3 }, { "ColName" : "getError", "TotalDocument" : 1 }, { "ColName" : "getFirstElementInArrayDemo", "TotalDocument" : 3 }, { "ColName" : "getFirstItemDemo", "TotalDocument" : 4 }, { "ColName" : "getIndexDemo", "TotalDocument" : 1 }, { "ColName" : "getIndexSizeDemo", "TotalDocument" : 4 }, { "ColName" : "getLastNRecordsDemo", "TotalDocument" : 11 }, { "ColName" : "getLastXRecordsDemo", "TotalDocument" : 11 }, { "ColName" : "getNThElementDemo", "TotalDocument" : 2 }, { "ColName" : "getOldestAndYoungestPostDemo", "TotalDocument" : 4 }, { "ColName" : "getParticularElementFromArrayDemo", "TotalDocument" : 2 }, { "ColName" : "getPartuclarElement", "TotalDocument" : 1 }, { "ColName" : "getSizeDemo", "TotalDocument" : 1 }, { "ColName" : "getSizeOfArray", "TotalDocument" : 3 }, { "ColName" : "gettingHighestValueDemo", "TotalDocument" : 9 }, { "ColName" : "groupByDateDemo", "TotalDocument" : 6 }, { "ColName" : "handlingAndEmptyDataDemo", "TotalDocument" : 3 }, { "ColName" : "hashDemo", "TotalDocument" : 2 }, { "ColName" : "hideidDemo", "TotalDocument" : 3 }, { "ColName" : "highestNumericValueDemo", "TotalDocument" : 1 }, { "ColName" : "highestNumericValueOfAColumnDemo", "TotalDocument" : 4 }, { "ColName" : "identifyLastDocuementDemo", "TotalDocument" : 6 }, { "ColName" : "improveQueryDemo", "TotalDocument" : 1 }, { "ColName" : "incrementInNestedArrayDemo", "TotalDocument" : 1 }, { "ColName" : "incrementValueDemo", "TotalDocument" : 1 }, { "ColName" : "incrementValueInNestedArrayDemo", "TotalDocument" : 0 }, { "ColName" : "indexDemo", "TotalDocument" : 3 }, { "ColName" : "indexOptimizationDemo", "TotalDocument" : 3 }, { "ColName" : "indexOrQueryDemo", "TotalDocument" : 0 }, { "ColName" : "indexTimeDemo", "TotalDocument" : 0 }, { "ColName" : "index_Demo", "TotalDocument" : 2 }, { "ColName" : "indexingDemo", "TotalDocument" : 3 }, { "ColName" : "insertDemo", "TotalDocument" : 1 }, { "ColName" : "insertFieldWithCurrentDateDemo", "TotalDocument" : 3 }, { "ColName" : "insertIfNotExistsDemo", "TotalDocument" : 4 }, { "ColName" : "insertIntegerDemo", "TotalDocument" : 3 }, { "ColName" : "insertOneRecordDemo", "TotalDocument" : 3 }, { "ColName" : "likeDemo", "TotalDocument" : 5 }, { "ColName" : "limitAnArrayDemo", "TotalDocument" : 1 }, { "ColName" : "listAllValuesOfCeratinFieldsDemo", "TotalDocument" : 4 }, { "ColName" : "loopThroughCollectionDemo", "TotalDocument" : 4 }, { "ColName" : "matchBetweenFieldsDemo", "TotalDocument" : 2 }, { "ColName" : "mongoExportDemo", "TotalDocument" : 1 }, { "ColName" : "multipleElementMatchDemo", "TotalDocument" : 2 }, { "ColName" : "multipleIndexesDemo", "TotalDocument" : 0 }, { "ColName" : "multipleOrDemo", "TotalDocument" : 4 }, { "ColName" : "my-collection", "TotalDocument" : 1 }, { "ColName" : "nanDemo", "TotalDocument" : 4 }, { "ColName" : "nestedArrayDemo", "TotalDocument" : 3 }, { "ColName" : "nestedIndexDemo", "TotalDocument" : 1 }, { "ColName" : "nestedObjectDemo", "TotalDocument" : 1 }, { "ColName" : "nestedQueryDemo", "TotalDocument" : 2 }, { "ColName" : "newProperty", "TotalDocument" : 2 }, { "ColName" : "new_Collection", "TotalDocument" : 3 }, { "ColName" : "noAutoCommandForIndexDemo", "TotalDocument" : 4 }, { "ColName" : "notEqaulToDemo", "TotalDocument" : 4 }, { "ColName" : "notEqaultToDemo", "TotalDocument" : 0 }, { "ColName" : "notLikeOpeartorDemo", "TotalDocument" : 5 }, { "ColName" : "numberofKeysInADocumentDemo", "TotalDocument" : 1 }, { "ColName" : "objectInAnArrayDemo", "TotalDocument" : 2 }, { "ColName" : "objectidToStringDemo", "TotalDocument" : 4 }, { "ColName" : "onlyInsertIfValueIsUniqueDemo", "TotalDocument" : 4 }, { "ColName" : "orConditionDemo", "TotalDocument" : 6 }, { "ColName" : "orDemo", "TotalDocument" : 6 }, { "ColName" : "orderDocsDemo", "TotalDocument" : 7 }, { "ColName" : "paginationDemo", "TotalDocument" : 5 }, { "ColName" : "performRegex", "TotalDocument" : 2 }, { "ColName" : "preventObjectIdDemo", "TotalDocument" : 1 }, { "ColName" : "priceStoredAsStringDemo", "TotalDocument" : 8 }, { "ColName" : "priceStoredDemo", "TotalDocument" : 7 }, { "ColName" : "pullAndAddToSetDemo", "TotalDocument" : 1 }, { "ColName" : "pushObjectDemo", "TotalDocument" : 1 }, { "ColName" : "queryArrayElementsDemo", "TotalDocument" : 3 }, { "ColName" : "queryByKeyDemo", "TotalDocument" : 1 }, { "ColName" : "queryBySubFieldDemo", "TotalDocument" : 2 }, { "ColName" : "queryForBooleanFieldsDemo", "TotalDocument" : 5 }, { "ColName" : "queryInSameDocumentsDemo", "TotalDocument" : 2 }, { "ColName" : "queryLengthDemo", "TotalDocument" : 5 }, { "ColName" : "queryToEmbeddedDocument", "TotalDocument" : 1 }, { "ColName" : "queryingMongoDbCaseInsensitiveDemo", "TotalDocument" : 4 }, { "ColName" : "readSpecificKeyValueDemo", "TotalDocument" : 1 }, { "ColName" : "regExpOnIntegerDemo", "TotalDocument" : 5 }, { "ColName" : "regexSearchDemo", "TotalDocument" : 5 }, { "ColName" : "removeAllDocumentsExceptOneDemo", "TotalDocument" : 1 }, { "ColName" : "removeArrayDemo", "TotalDocument" : 1 }, { "ColName" : "removeArrayElement", "TotalDocument" : 1 }, { "ColName" : "removeArrayElementByItsIndexDemo", "TotalDocument" : 1 }, { "ColName" : "removeArrayElements", "TotalDocument" : 1 }, { "ColName" : "removeDocumentOnBasisOfId", "TotalDocument" : 4 }, { "ColName" : "removeDocumentsExceptOneFromCollection", "TotalDocument" : 1 }, { "ColName" : "removeDuplicateDocumentDemo", "TotalDocument" : 4 }, { "ColName" : "removeDuplicateDocuments", "TotalDocument" : 3 }, { "ColName" : "removeDuplicatesDemo", "TotalDocument" : 1 }, { "ColName" : "removeElementFromDoublyNestedArrayDemo", "TotalDocument" : 2 }, { "ColName" : "removeFieldCompletlyDemo", "TotalDocument" : 3 }, { "ColName" : "removeIdDemo", "TotalDocument" : 4 }, { "ColName" : "removeMultipleDocumentsDemo", "TotalDocument" : 3 }, { "ColName" : "removeObject", "TotalDocument" : 1 }, { "ColName" : "removeRecordDemo", "TotalDocument" : 5 }, { "ColName" : "removingidElementDemo", "TotalDocument" : 5 }, { "ColName" : "renameFieldDemo", "TotalDocument" : 5 }, { "ColName" : "renameIdDemo", "TotalDocument" : 3 }, { "ColName" : "renamingColumnNameDemo", "TotalDocument" : 3 }, { "ColName" : "replaceSpecificArrayValueDemo", "TotalDocument" : 1 }, { "ColName" : "retrieveDocumentsWithEndsWithParticularCharacterDemo", "TotalDocument" : 5 }, { "ColName" : "retrieveFirstDocumentDemo", "TotalDocument" : 4 }, { "ColName" : "retrieveValueFromAKeyDemo", "TotalDocument" : 3 }, { "ColName" : "retunFieldInFindDemo", "TotalDocument" : 4 }, { "ColName" : "returnOnlyValueOfFieldDemo", "TotalDocument" : 4 }, { "ColName" : "returnQueryFromDate", "TotalDocument" : 4 }, { "ColName" : "reverseRegexDemo", "TotalDocument" : 2 }, { "ColName" : "s", "TotalDocument" : 2 }, { "ColName" : "saveStudentInformation", "TotalDocument" : 4 }, { "ColName" : "searchArrayDemo", "TotalDocument" : 2 }, { "ColName" : "searchByPropertyName", "TotalDocument" : 5 }, { "ColName" : "searchDocumentDemo", "TotalDocument" : 10 }, { "ColName" : "searchDocumentWithSpecialCharactersDemo", "TotalDocument" : 4 }, { "ColName" : "searchForNestedKeysDemo", "TotalDocument" : 3 }, { "ColName" : "searchMultipleFieldsDemo", "TotalDocument" : 3 }, { "ColName" : "secondDocumentDemo", "TotalDocument" : 3 }, { "ColName" : "selectFieldAsAnotherNameDemo", "TotalDocument" : 4 }, { "ColName" : "selectInWhereIdDemo", "TotalDocument" : 6 }, { "ColName" : "selectMongoDBDocumentsWithSomeCondition", "TotalDocument" : 7 }, { "ColName" : "selectRecordsHavingKeyDemo", "TotalDocument" : 4 }, { "ColName" : "selectSingleFieldDemo", "TotalDocument" : 12 }, { "ColName" : "setMaxDemo", "TotalDocument" : 0 }, { "ColName" : "singleFieldDemo", "TotalDocument" : 4 }, { "ColName" : "singlePropertyIdDemo", "TotalDocument" : 5 }, { "ColName" : "sortDemo", "TotalDocument" : 6 }, { "ColName" : "sortInnerArrayDemo", "TotalDocument" : 1 }, { "ColName" : "sortingDemo", "TotalDocument" : 8 }, { "ColName" : "sourceCollection", "TotalDocument" : 2 }, { "ColName" : "sqlLikeDemo", "TotalDocument" : 7 }, { "ColName" : "storeQueryResultDemo", "TotalDocument" : 4 }, { "ColName" : "stringFieldLengthDemo", "TotalDocument" : 7 }, { "ColName" : "stringToDateDataTypeDemo", "TotalDocument" : 3 }, { "ColName" : "stringToObjectIdDemo", "TotalDocument" : 1 }, { "ColName" : "subsetOfAnArrayDemo", "TotalDocument" : 1 }, { "ColName" : "test.js", "TotalDocument" : 1 }, { "ColName" : "toLowerDemo", "TotalDocument" : 4 }, { "ColName" : "topLevelDocumentDemo", "TotalDocument" : 1 }, { "ColName" : "translateDefinitionDemo", "TotalDocument" : 5 }, { "ColName" : "twoRandomDocumentDemo", "TotalDocument" : 6 }, { "ColName" : "twoSeparateArraysDemo", "TotalDocument" : 3 }, { "ColName" : "unconditionalUpdatesDemo", "TotalDocument" : 4 }, { "ColName" : "uniqueArrayDemo", "TotalDocument" : 4 }, { "ColName" : "uniqueIndexOnArrayDemo", "TotalDocument" : 3 }, { "ColName" : "unprettyJsonDemo", "TotalDocument" : 2 }, { "ColName" : "unsetAnAttributeDemo", "TotalDocument" : 1 }, { "ColName" : "unwindOperatorDemo", "TotalDocument" : 1 }, { "ColName" : "updateDemo", "TotalDocument" : 3 }, { "ColName" : "updateExactField", "TotalDocument" : 1 }, { "ColName" : "updateIdDemo", "TotalDocument" : 3 }, { "ColName" : "updateListOfKeyValuesDemo", "TotalDocument" : 1 }, { "ColName" : "updateManyDocumentsDemo", "TotalDocument" : 4 }, { "ColName" : "updateNestedValueDemo", "TotalDocument" : 1 }, { "ColName" : "updateObjects", "TotalDocument" : 1 }, { "ColName" : "updateOnlySpecificFieldDemo", "TotalDocument" : 3 }, { "ColName" : "updatingEmbeddedDocumentPropertyDemo", "TotalDocument" : 2 }, { "ColName" : "userStatus", "TotalDocument" : 5 } ]
[ { "code": null, "e": 1162, "s": 1062, "text": "To get the count of the number of documents in a collection MongoDB, you can use the below syntax −" }, { "code": null, "e": 1312, "s": 1162, "text": "db.getCollectionNames().map(function(anyVariableName) {\n return { \"yourVariableName\": yourVariableName, \"count\": db[yourVariableName].count() }\n});" }, { "code": null, "e": 1348, "s": 1312, "text": "Here, we are using ‘test’ database." }, { "code": null, "e": 1452, "s": 1348, "text": "Let us implement the above syntax to get the count of the number of documents in a MongoDB collection −" }, { "code": null, "e": 1582, "s": 1452, "text": "> db.getCollectionNames().map(function(ColName) {\n... return { \"ColName\": ColName, \"TotalDocument\": db[ColName].count() }\n... });" }, { "code": null, "e": 1623, "s": 1582, "text": "This will produce the following output −" }, { "code": null, "e": 22234, "s": 1623, "text": "[\n {\n \"ColName\" : \"ConvertStringToDateDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"Employee_Information\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"IdUpdateDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"IndexingDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"NotAndDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"ProductsInformation\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"addCurrentDateTimeDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"addFieldDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"addNewFieldToEveryDocument\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"addingNewPropertyDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"aggregateSumDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"aggregationFrameworkWithOrMatchDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"aggregationSortDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"andOrDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"arrayInnerElementsDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"arrayLengthGreaterThanOne\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"arrayOfArraysDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"averageAggregationDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"avoidDuplicateEntriesDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"caseInsensitiveDemo\",\n \"TotalDocument\" : 13\n },\n {\n \"ColName\" : \"caseInsesitiveDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"castingDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"changeDataType\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"changeIntegerToStringDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"changeType\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"charactersAllowedDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"charactersDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"check\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"checkDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"checkFieldContainsStringDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"checkFieldExistsOrNotDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"checkIfFieldIsNumberDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"checkSequenceDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"cloneObjectDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"collectionOnDifferentDocumentDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"combinationOfArrayDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"comparingFieldDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"comparingTwoFieldsDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"componentOfDateDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"concatStringAndIntDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"concatenateStringsDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"conditionalSumDemo\",\n \"TotalDocument\" : 8\n },\n {\n \"ColName\" : \"conditionalUpdatesDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"conditionallyUpsertDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"convertStringToNumberDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"convertingISODateToNumerical\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"copyThisCollectionToSampleDatabaseDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"countDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"countNumberOfDocumentsDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"countPerformanceDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"createSequenceDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"creatingUniqueIndexDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"dateDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"dateTimeValueLessThanNowDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"deleteAllElementsInArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"deleteDocumentsDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"deleteFieldDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"deleteRecordDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"deletingDocumentDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"demo.insertCollection\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"determineFieldExistsDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"distinctAggregation\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"distinctCountValuesDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"distinctRecordDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"distinctWithMultipleKeysDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"doubleNestedArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"emailUniqueDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"embeddedCollectionDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"embeddedDocumentDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"employeeInformation\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"equivalentForSelectColumn1Column2Demo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"exactMatchArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"existsDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"existsReturnDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"extractSubArrayDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"fieldIsNullOrNotSetDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"filterArray\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"findADocumentWithCondition\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"findAllDuplicateKeyDocumentDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"findAllNonDistinctDemo\",\n \"TotalDocument\" : 8\n },\n {\n \"ColName\" : \"findByFieldName\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"findByMultipleArrayDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"findDocumentDoNotHaveCertainFields\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"findDocumentNonExistenceFieldDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"findDocumentWithObjectIdDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"findDuplicateByKeyDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"findDuplicateRecordsDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"findMinValueDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"findMultipleWordsDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"findRecordByIdDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"findSpecificValue\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"findValueInArrayWithMultipleCriteriaDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"firstDocumentDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"firstElementOfArray\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"firstItemInArrayToNewFieldDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"firstLevelArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"flightInformation\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"foo2\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"getAllValue\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"getDistinctListOfSubDocumentFieldDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"getDistinctWithSortedDataDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"getDocuementsByTagsDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"getError\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"getFirstElementInArrayDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"getFirstItemDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"getIndexDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"getIndexSizeDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"getLastNRecordsDemo\",\n \"TotalDocument\" : 11\n },\n {\n \"ColName\" : \"getLastXRecordsDemo\",\n \"TotalDocument\" : 11\n },\n {\n \"ColName\" : \"getNThElementDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"getOldestAndYoungestPostDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"getParticularElementFromArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"getPartuclarElement\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"getSizeDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"getSizeOfArray\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"gettingHighestValueDemo\",\n \"TotalDocument\" : 9\n },\n {\n \"ColName\" : \"groupByDateDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"handlingAndEmptyDataDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"hashDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"hideidDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"highestNumericValueDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"highestNumericValueOfAColumnDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"identifyLastDocuementDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"improveQueryDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"incrementInNestedArrayDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"incrementValueDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"incrementValueInNestedArrayDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"indexDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"indexOptimizationDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"indexOrQueryDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"indexTimeDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"index_Demo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"indexingDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"insertDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"insertFieldWithCurrentDateDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"insertIfNotExistsDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"insertIntegerDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"insertOneRecordDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"likeDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"limitAnArrayDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"listAllValuesOfCeratinFieldsDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"loopThroughCollectionDemo\",\n \"TotalDocument\" : 4\n },\n { \n \"ColName\" : \"matchBetweenFieldsDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"mongoExportDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"multipleElementMatchDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"multipleIndexesDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"multipleOrDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"my-collection\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"nanDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"nestedArrayDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"nestedIndexDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"nestedObjectDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"nestedQueryDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"newProperty\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"new_Collection\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"noAutoCommandForIndexDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"notEqaulToDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"notEqaultToDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"notLikeOpeartorDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"numberofKeysInADocumentDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"objectInAnArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"objectidToStringDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"onlyInsertIfValueIsUniqueDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"orConditionDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"orDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"orderDocsDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"paginationDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"performRegex\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"preventObjectIdDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"priceStoredAsStringDemo\",\n \"TotalDocument\" : 8\n },\n {\n \"ColName\" : \"priceStoredDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"pullAndAddToSetDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"pushObjectDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"queryArrayElementsDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"queryByKeyDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"queryBySubFieldDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"queryForBooleanFieldsDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"queryInSameDocumentsDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"queryLengthDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"queryToEmbeddedDocument\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"queryingMongoDbCaseInsensitiveDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"readSpecificKeyValueDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"regExpOnIntegerDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"regexSearchDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"removeAllDocumentsExceptOneDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeArrayDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeArrayElement\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeArrayElementByItsIndexDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeArrayElements\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeDocumentOnBasisOfId\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"removeDocumentsExceptOneFromCollection\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeDuplicateDocumentDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"removeDuplicateDocuments\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"removeDuplicatesDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeElementFromDoublyNestedArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"removeFieldCompletlyDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"removeIdDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"removeMultipleDocumentsDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"removeObject\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"removeRecordDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"removingidElementDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"renameFieldDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"renameIdDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"renamingColumnNameDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"replaceSpecificArrayValueDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"retrieveDocumentsWithEndsWithParticularCharacterDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"retrieveFirstDocumentDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"retrieveValueFromAKeyDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"retunFieldInFindDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"returnOnlyValueOfFieldDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"returnQueryFromDate\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"reverseRegexDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"s\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"saveStudentInformation\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"searchArrayDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"searchByPropertyName\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"searchDocumentDemo\",\n \"TotalDocument\" : 10\n },\n {\n \"ColName\" : \"searchDocumentWithSpecialCharactersDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"searchForNestedKeysDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"searchMultipleFieldsDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"secondDocumentDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"selectFieldAsAnotherNameDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"selectInWhereIdDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"selectMongoDBDocumentsWithSomeCondition\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"selectRecordsHavingKeyDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"selectSingleFieldDemo\",\n \"TotalDocument\" : 12\n },\n {\n \"ColName\" : \"setMaxDemo\",\n \"TotalDocument\" : 0\n },\n {\n \"ColName\" : \"singleFieldDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"singlePropertyIdDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"sortDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"sortInnerArrayDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"sortingDemo\",\n \"TotalDocument\" : 8\n },\n {\n \"ColName\" : \"sourceCollection\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"sqlLikeDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"storeQueryResultDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"stringFieldLengthDemo\",\n \"TotalDocument\" : 7\n },\n {\n \"ColName\" : \"stringToDateDataTypeDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"stringToObjectIdDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"subsetOfAnArrayDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"test.js\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"toLowerDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"topLevelDocumentDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"translateDefinitionDemo\",\n \"TotalDocument\" : 5\n },\n {\n \"ColName\" : \"twoRandomDocumentDemo\",\n \"TotalDocument\" : 6\n },\n {\n \"ColName\" : \"twoSeparateArraysDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"unconditionalUpdatesDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"uniqueArrayDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"uniqueIndexOnArrayDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"unprettyJsonDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"unsetAnAttributeDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"unwindOperatorDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"updateDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"updateExactField\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"updateIdDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"updateListOfKeyValuesDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"updateManyDocumentsDemo\",\n \"TotalDocument\" : 4\n },\n {\n \"ColName\" : \"updateNestedValueDemo\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"updateObjects\",\n \"TotalDocument\" : 1\n },\n {\n \"ColName\" : \"updateOnlySpecificFieldDemo\",\n \"TotalDocument\" : 3\n },\n {\n \"ColName\" : \"updatingEmbeddedDocumentPropertyDemo\",\n \"TotalDocument\" : 2\n },\n {\n \"ColName\" : \"userStatus\",\n \"TotalDocument\" : 5\n }\n]" } ]
How to get a particular date in Java 8?
The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth, etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives. Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock. The of() method of java.time.LocalDate class accepts three integer parameters representing and year, a month of an year, day of a month and, returns the instance of the LocalDate object from the given details. Following Java program reads year, month and day values from the user and creates a Date object of the given date using the classes and methods java.time package of Java8. import java.time.LocalDate; import java.util.Scanner; public class LocalDateJava8 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the year: "); int year = sc.nextInt(); System.out.println("Enter the month: "); int month = sc.nextInt(); System.out.println("Enter the day: "); int day = sc.nextInt(); //Getting the current date value LocalDate givenDate = LocalDate.of(year, month, day); System.out.println("Date: "+givenDate); } } Enter the year: 2019 Enter the month: 07 Enter the day: 24 Date: 2019-07-24
[ { "code": null, "e": 1389, "s": 1062, "text": "The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth, etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives." }, { "code": null, "e": 1573, "s": 1389, "text": "Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock." }, { "code": null, "e": 1783, "s": 1573, "text": "The of() method of java.time.LocalDate class accepts three integer parameters representing and year, a month of an year, day of a month and, returns the instance of the LocalDate object from the given details." }, { "code": null, "e": 1955, "s": 1783, "text": "Following Java program reads year, month and day values from the user and creates a Date object of the given date using the classes and methods java.time package of Java8." }, { "code": null, "e": 2509, "s": 1955, "text": "import java.time.LocalDate;\nimport java.util.Scanner;\npublic class LocalDateJava8 {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the year: \");\n int year = sc.nextInt();\n System.out.println(\"Enter the month: \");\n int month = sc.nextInt();\n System.out.println(\"Enter the day: \");\n int day = sc.nextInt();\n //Getting the current date value\n LocalDate givenDate = LocalDate.of(year, month, day);\n System.out.println(\"Date: \"+givenDate);\n }\n}" }, { "code": null, "e": 2585, "s": 2509, "text": "Enter the year:\n2019\nEnter the month:\n07\nEnter the day:\n24\nDate: 2019-07-24" } ]
How to catch TypeError Exception in Python?
TypeErrors are caused by combining the wrong type of objects, or calling a function with the wrong type of object. import sys try : ny = 'Statue of Liberty' my_list = [3, 4, 5, 8, 9] print my_list + ny except TypeError as e: print e print sys.exc_type can only concatenate list (not ""str") to list <type 'exceptions.TypeError'>
[ { "code": null, "e": 1177, "s": 1062, "text": "TypeErrors are caused by combining the wrong type of objects, or calling a function with the wrong type of object." }, { "code": null, "e": 1315, "s": 1177, "text": "import sys\ntry :\nny = 'Statue of Liberty'\nmy_list = [3, 4, 5, 8, 9]\nprint my_list + ny\nexcept TypeError as e:\nprint e\nprint sys.exc_type" }, { "code": null, "e": 1392, "s": 1315, "text": "can only concatenate list (not \"\"str\") to list\n<type 'exceptions.TypeError'>" } ]
In 12 minutes: Stocks Analysis with Pandas and Scikit-Learn | by Vincent Tatan | Towards Data Science
One day, a friend of mine told me that the key to financial freedom is investing in stocks. While it is greatly true during the market boom, it still remains an attractive options today to trade stocks part time. Given the easy access to online trading platform, there are many self made value investors or housewife traders. There are even success stories and advertisements which boast “Get Rich Quick Scheme” to learn how to invest in stocks with a staggering return of 40% and even more. Investing has become the boon for the working professionals today. The question now are: Which stocks? How do you analyse stocks? What are the returns and risks of this stocks compared to its competitors? The objective for this publication is for you to understand one way on analyzing stocks using quick and dirty Python Code. Just spend 12 minutes to read this article — or even better, contribute. Then you could get a quick glimpse to code your first financial analysis. To start learning and analyzing stocks, we will start off by taking a quick look at the historical stocks prices. This will be done by extracting latest stocks data from pandas web-data reader and Yahoo Finance. Then we will try to view the data through exploratory analysis such as correlation heatmap, matplotlib visualization, and prediction analysis using Linear Analysis and K Nearest Neighbor (KNN). Pandas web data reader is an extension of pandas library to communicate with most updated financial data. This will include sources as: Yahoo Finance, Google Finance, Enigma, etc. We will extract Apple Stocks Price using the following codes: import pandas as pdimport datetimeimport pandas_datareader.data as webfrom pandas import Series, DataFramestart = datetime.datetime(2010, 1, 1)end = datetime.datetime(2017, 1, 11)df = web.DataReader("AAPL", 'yahoo', start, end)df.tail() This piece of code will pull 7 years data from January 2010 until January 2017. Feel free to tweak the start and end date as you see necessary. For the rest of analysis, we will use the Closing Price which remarks the final price in which the stocks are traded by the end of the day. In this analysis, we analyse stocks using two key measurements: Rolling Mean and Return Rate. Rolling mean/Moving Average (MA) smooths out price data by creating a constantly updated average price. This is useful to cut down “noise” in our price chart. Furthermore, this Moving Average could act as “Resistance” meaning from the downtrend and uptrend of stocks you could expect it will follow the trend and less likely to deviate outside its resistance point. www.investopedia.com Let’s start code out the Rolling Mean: close_px = df['Adj Close']mavg = close_px.rolling(window=100).mean() This will calculate the Moving Average for the last 100 windows (100 days) of stocks closing price and take the average for each of the window’s moving average. As you could see, The Moving Average steadily rises over the window and does not follow the jagged line of stocks price chart. For better understanding, let’s plot it out with Matplotlib. We will overlay the Moving Average with our Stocks Price Chart. %matplotlib inlineimport matplotlib.pyplot as pltfrom matplotlib import style# Adjusting the size of matplotlibimport matplotlib as mplmpl.rc('figure', figsize=(8, 7))mpl.__version__# Adjusting the style of matplotlibstyle.use('ggplot')close_px.plot(label='AAPL')mavg.plot(label='mavg')plt.legend() The Moving Average makes the line smooth and showcase the increasing or decreasing trend of stocks price. In this chart, the Moving Average showcases increasing trend the upturn or downturn of stocks price. Logically, you should buy when the stocks are experiencing downturn and sell when the stocks are experiencing upturn. Expected Return measures the mean, or expected value, of the probability distribution of investment returns. The expected return of a portfolio is calculated by multiplying the weight of each asset by its expected return and adding the values for each investment — Investopedia. Following is the formula you could refer to: Based on the formula, we could plot our returns as following. rets = close_px / close_px.shift(1) - 1rets.plot(label='return') Logically, our ideal stocks should return as high and stable as possible. If you are risk averse(like me), you might want to avoid this stocks as you saw the 10% drop in 2013. This decision is heavily subjected to your general sentiment of the stocks and competitor analysis. In this segment, we are going to analyse on how one company performs in relative with its competitor. Let’s assume we are interested in technology companies and want to compare the big guns: Apple, GE, Google, IBM, and Microsoft. dfcomp = web.DataReader(['AAPL', 'GE', 'GOOG', 'IBM', 'MSFT'],'yahoo',start=start,end=end)['Adj Close'] This will return you a slick table of closing prices among the stocks prices from Yahoo Finance. Neat!! We can analyse the competition by running the percentage change and correlation function in pandas. Percentage change will find how much the price changes compared to the previous day which defines returns. Knowing the correlation will help us see whether the returns are affected by other stocks’ returns retscomp = dfcomp.pct_change()corr = retscomp.corr() Let’s plot Apple and GE with ScatterPlot to view their return distributions. plt.scatter(retscomp.AAPL, retscomp.GE)plt.xlabel(‘Returns AAPL’)plt.ylabel(‘Returns GE’) We can see here that there are slight positive correlations among GE returns and Apple returns. It seems like that the higher the Apple returns, the higher GE returns as well for most cases. Let us further improve our analysis by plotting the scatter_matrix to visualize possible correlations among competing stocks. At the diagonal point, we will run Kernel Density Estimate (KDE). KDE is a fundamental data smoothing problem where inferences about the population are made, based on a finite data sample. It helps generate estimations of the overall distributions. en.wikipedia.org pd.scatter_matrix(retscomp, diagonal='kde', figsize=(10, 10)); From here we could see most of the distributions among stocks which approximately positive correlations. To prove the positive correlations, we will use heat maps to visualize the correlation ranges among the competing stocks. Notice that the lighter the color, the more correlated the two stocks are. plt.imshow(corr, cmap='hot', interpolation='none')plt.colorbar()plt.xticks(range(len(corr)), corr.columns)plt.yticks(range(len(corr)), corr.columns); From the Scatter Matrix and Heatmap, we can find great correlations among the competing stocks. However, this might not show causality, and could just show the trend in the technology industry rather than show how competing stocks affect each other. Apart from correlation, we also analyse each stock’s risks and returns. In this case we are extracting the average of returns (Return Rate) and the standard deviation of returns (Risk). plt.scatter(retscomp.mean(), retscomp.std())plt.xlabel('Expected returns')plt.ylabel('Risk')for label, x, y in zip(retscomp.columns, retscomp.mean(), retscomp.std()): plt.annotate( label, xy = (x, y), xytext = (20, -20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) Now you could view this neat chart of risk and return comparisons for competing stocks. Logically, you would like to minimize the risk and maximize returns. Therefore, you would want to draw the line for your risk-return tolerance (The red line). You would then create the rules to buy those stocks under the red line (MSFT, GE, and IBM) and sell those stocks above the red line (AAPL and GOOG). This red line showcases your expected value threshold and your baseline for buy/sell decision. We will use these three machine learning models to predict our stocks: Simple Linear Analysis, Quadratic Discriminant Analysis (QDA), and K Nearest Neighbor (KNN). But first, let us engineer some features: High Low Percentage and Percentage Change. dfreg = df.loc[:,[‘Adj Close’,’Volume’]]dfreg[‘HL_PCT’] = (df[‘High’] — df[‘Low’]) / df[‘Close’] * 100.0dfreg[‘PCT_change’] = (df[‘Close’] — df[‘Open’]) / df[‘Open’] * 100.0 We will clean up and process the data using the following steps before putting them into the prediction models: Drop missing valueSeparating the label here, we want to predict the AdjCloseScale the X so that everyone can have the same distribution for linear regressionFinally We want to find Data Series of late X and early X (train) for model generation and evaluationSeparate label and identify it as ySeparation of training and testing of model by cross validation train test split Drop missing value Separating the label here, we want to predict the AdjClose Scale the X so that everyone can have the same distribution for linear regression Finally We want to find Data Series of late X and early X (train) for model generation and evaluation Separate label and identify it as y Separation of training and testing of model by cross validation train test split Please refer the preparation codes below. # Drop missing valuedfreg.fillna(value=-99999, inplace=True)# We want to separate 1 percent of the data to forecastforecast_out = int(math.ceil(0.01 * len(dfreg)))# Separating the label here, we want to predict the AdjCloseforecast_col = 'Adj Close'dfreg['label'] = dfreg[forecast_col].shift(-forecast_out)X = np.array(dfreg.drop(['label'], 1))# Scale the X so that everyone can have the same distribution for linear regressionX = preprocessing.scale(X)# Finally We want to find Data Series of late X and early X (train) for model generation and evaluationX_lately = X[-forecast_out:]X = X[:-forecast_out]# Separate label and identify it as yy = np.array(dfreg['label'])y = y[:-forecast_out] But first, let’s insert the following imports for our Scikit-Learn: from sklearn.linear_model import LinearRegressionfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.linear_model import Ridgefrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.pipeline import make_pipeline Simple Linear Analysis shows a linear relationship between two or more variables. When we draw this relationship within two variables, we get a straight line. Quadratic Discriminant Analysis would be similar to Simple Linear Analysis, except that the model allowed polynomial (e.g: x squared) and would produce curves. Linear Regression predicts dependent variables (y) as the outputs given independent variables (x) as the inputs. During the plotting, this will give us a straight line as shown below: This is an amazing publication which showed a very comprehensive review of Linear Regression. Please refer to the link below for the view. towardsdatascience.com We will plug and play the existing Scikit-Learn library and train the model by selecting our X and y train sets. The code will be as following. # Linear regressionclfreg = LinearRegression(n_jobs=-1)clfreg.fit(X_train, y_train)# Quadratic Regression 2clfpoly2 = make_pipeline(PolynomialFeatures(2), Ridge())clfpoly2.fit(X_train, y_train)# Quadratic Regression 3clfpoly3 = make_pipeline(PolynomialFeatures(3), Ridge())clfpoly3.fit(X_train, y_train) This KNN uses feature similarity to predict values of data points. This ensures that the new point assigned is similar to the points in the data set. To find out similarity, we will extract the points to release the minimum distance (e.g: Euclidean Distance). Please refer to this link for further details on the model. This is really useful to improve your understanding. www.analyticsvidhya.com # KNN Regressionclfknn = KNeighborsRegressor(n_neighbors=2)clfknn.fit(X_train, y_train) A simple quick and dirty way to evaluate is to use the score method in each trained model. The score method finds the mean accuracy of self.predict(X) with y of the test data set. confidencereg = clfreg.score(X_test, y_test)confidencepoly2 = clfpoly2.score(X_test,y_test)confidencepoly3 = clfpoly3.score(X_test,y_test)confidenceknn = clfknn.score(X_test, y_test)# results('The linear regression confidence is ', 0.96399641826551985)('The quadratic regression 2 confidence is ', 0.96492624557970319)('The quadratic regression 3 confidence is ', 0.9652082834532858)('The knn regression confidence is ', 0.92844658034790639) This shows an enormous accuracy score (>0.95) for most of the models. However this does not mean we can blindly place our stocks. There are still many issues to consider, especially with different companies that have different price trajectories over time. For sanity testing, let us print some of the stocks forecast. forecast_set = clf.predict(X_lately)dfreg['Forecast'] = np.nan#result(array([ 115.44941187, 115.20206522, 116.78688393, 116.70244946, 116.58503739, 115.98769407, 116.54315699, 117.40012338, 117.21473053, 116.57244657, 116.048717 , 116.26444966, 115.78374093, 116.50647805, 117.92064806, 118.75581186, 118.82688731, 119.51873699]), 0.96234891774075604, 18) Based on the forecast, we will visualize the plot with our existing historical data. This will help us visualize how the model fares to predict future stocks pricing. last_date = dfreg.iloc[-1].namelast_unix = last_datenext_unix = last_unix + datetime.timedelta(days=1)for i in forecast_set: next_date = next_unix next_unix += datetime.timedelta(days=1) dfreg.loc[next_date] = [np.nan for _ in range(len(dfreg.columns)-1)]+[i]dfreg['Adj Close'].tail(500).plot()dfreg['Forecast'].tail(500).plot()plt.legend(loc=4)plt.xlabel('Date')plt.ylabel('Price')plt.show() As we can see the blue color showcased the forecast on the stocks price based on regression. The forecast predicted that there would be a downturn for not too long, then it will recover. Therefore, we could buy the stocks during downturn and sell during upturn. To further analyse the stocks, here are some ideas on how you could contribute. These ideas would be useful to get a more comprehensive analysis on stocks. Feel free to let me know should there be more clarifications needed. Analyse economic qualitative factors such as news (news sourcing and sentimental analysis) Analyse economic quantitative factors such as HPI of a certain country, economic inequality among origin of company The purpose for this Proof Of Concepts (POC) was created as a part of investments side project that the I am currently managing. The goal of this application is to help you retrieve and display the right financial insights quickly about a certain company stocks price and predicting its value. In the POC, I used Pandas- Web Datareader to find the stocks prices , Scikit-Learn to predict and generate machine learning models, and finally Python as the scripting language. The Github Python Notebook Code is located below. github.com Feel free to clone the repository and contribute whenever you have time. In lieu with today’s topics about stocks analysis. You could also visit my Value Investing Publication where I talked about scraping stocks financial information and displaying it in an easy to read dashboard which processes stocks valuation based on Value Investing methodology. Please visit it and contribute :). towardsdatascience.com Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. I would like to thank you my fellow Accountancy and Finance friends who gave me constructive feedback on this publication. I really enjoyed learning that you gained much values from this publication of mine. Whew... That’s it, about my idea which I formulated into writings. I really hope this has been a great read for you guys. With that, I hope my idea could be a source of inspiration for you to develop and innovate. Please reach out to me via my LinkedIn and subscribe to my Youtube Channel If you like it, please give me Claps. Comment out below to suggest and feedback. Happy coding :) Disclaimer: This disclaimer informs readers that the views, thoughts, and opinions expressed in the text belong solely to the author, and not necessarily to the author’s employer, organization, committee or other group or individual. References are picked up from the list and any similarities with other works are purely coincidental This article was made purely as the author’s side project and in no way driven by any other hidden agenda.
[ { "code": null, "e": 731, "s": 172, "text": "One day, a friend of mine told me that the key to financial freedom is investing in stocks. While it is greatly true during the market boom, it still remains an attractive options today to trade stocks part time. Given the easy access to online trading platform, there are many self made value investors or housewife traders. There are even success stories and advertisements which boast “Get Rich Quick Scheme” to learn how to invest in stocks with a staggering return of 40% and even more. Investing has become the boon for the working professionals today." }, { "code": null, "e": 869, "s": 731, "text": "The question now are: Which stocks? How do you analyse stocks? What are the returns and risks of this stocks compared to its competitors?" }, { "code": null, "e": 1139, "s": 869, "text": "The objective for this publication is for you to understand one way on analyzing stocks using quick and dirty Python Code. Just spend 12 minutes to read this article — or even better, contribute. Then you could get a quick glimpse to code your first financial analysis." }, { "code": null, "e": 1545, "s": 1139, "text": "To start learning and analyzing stocks, we will start off by taking a quick look at the historical stocks prices. This will be done by extracting latest stocks data from pandas web-data reader and Yahoo Finance. Then we will try to view the data through exploratory analysis such as correlation heatmap, matplotlib visualization, and prediction analysis using Linear Analysis and K Nearest Neighbor (KNN)." }, { "code": null, "e": 1725, "s": 1545, "text": "Pandas web data reader is an extension of pandas library to communicate with most updated financial data. This will include sources as: Yahoo Finance, Google Finance, Enigma, etc." }, { "code": null, "e": 1787, "s": 1725, "text": "We will extract Apple Stocks Price using the following codes:" }, { "code": null, "e": 2024, "s": 1787, "text": "import pandas as pdimport datetimeimport pandas_datareader.data as webfrom pandas import Series, DataFramestart = datetime.datetime(2010, 1, 1)end = datetime.datetime(2017, 1, 11)df = web.DataReader(\"AAPL\", 'yahoo', start, end)df.tail()" }, { "code": null, "e": 2308, "s": 2024, "text": "This piece of code will pull 7 years data from January 2010 until January 2017. Feel free to tweak the start and end date as you see necessary. For the rest of analysis, we will use the Closing Price which remarks the final price in which the stocks are traded by the end of the day." }, { "code": null, "e": 2402, "s": 2308, "text": "In this analysis, we analyse stocks using two key measurements: Rolling Mean and Return Rate." }, { "code": null, "e": 2768, "s": 2402, "text": "Rolling mean/Moving Average (MA) smooths out price data by creating a constantly updated average price. This is useful to cut down “noise” in our price chart. Furthermore, this Moving Average could act as “Resistance” meaning from the downtrend and uptrend of stocks you could expect it will follow the trend and less likely to deviate outside its resistance point." }, { "code": null, "e": 2789, "s": 2768, "text": "www.investopedia.com" }, { "code": null, "e": 2828, "s": 2789, "text": "Let’s start code out the Rolling Mean:" }, { "code": null, "e": 2897, "s": 2828, "text": "close_px = df['Adj Close']mavg = close_px.rolling(window=100).mean()" }, { "code": null, "e": 3185, "s": 2897, "text": "This will calculate the Moving Average for the last 100 windows (100 days) of stocks closing price and take the average for each of the window’s moving average. As you could see, The Moving Average steadily rises over the window and does not follow the jagged line of stocks price chart." }, { "code": null, "e": 3310, "s": 3185, "text": "For better understanding, let’s plot it out with Matplotlib. We will overlay the Moving Average with our Stocks Price Chart." }, { "code": null, "e": 3609, "s": 3310, "text": "%matplotlib inlineimport matplotlib.pyplot as pltfrom matplotlib import style# Adjusting the size of matplotlibimport matplotlib as mplmpl.rc('figure', figsize=(8, 7))mpl.__version__# Adjusting the style of matplotlibstyle.use('ggplot')close_px.plot(label='AAPL')mavg.plot(label='mavg')plt.legend()" }, { "code": null, "e": 3715, "s": 3609, "text": "The Moving Average makes the line smooth and showcase the increasing or decreasing trend of stocks price." }, { "code": null, "e": 3934, "s": 3715, "text": "In this chart, the Moving Average showcases increasing trend the upturn or downturn of stocks price. Logically, you should buy when the stocks are experiencing downturn and sell when the stocks are experiencing upturn." }, { "code": null, "e": 4213, "s": 3934, "text": "Expected Return measures the mean, or expected value, of the probability distribution of investment returns. The expected return of a portfolio is calculated by multiplying the weight of each asset by its expected return and adding the values for each investment — Investopedia." }, { "code": null, "e": 4258, "s": 4213, "text": "Following is the formula you could refer to:" }, { "code": null, "e": 4320, "s": 4258, "text": "Based on the formula, we could plot our returns as following." }, { "code": null, "e": 4385, "s": 4320, "text": "rets = close_px / close_px.shift(1) - 1rets.plot(label='return')" }, { "code": null, "e": 4661, "s": 4385, "text": "Logically, our ideal stocks should return as high and stable as possible. If you are risk averse(like me), you might want to avoid this stocks as you saw the 10% drop in 2013. This decision is heavily subjected to your general sentiment of the stocks and competitor analysis." }, { "code": null, "e": 4891, "s": 4661, "text": "In this segment, we are going to analyse on how one company performs in relative with its competitor. Let’s assume we are interested in technology companies and want to compare the big guns: Apple, GE, Google, IBM, and Microsoft." }, { "code": null, "e": 4995, "s": 4891, "text": "dfcomp = web.DataReader(['AAPL', 'GE', 'GOOG', 'IBM', 'MSFT'],'yahoo',start=start,end=end)['Adj Close']" }, { "code": null, "e": 5099, "s": 4995, "text": "This will return you a slick table of closing prices among the stocks prices from Yahoo Finance. Neat!!" }, { "code": null, "e": 5405, "s": 5099, "text": "We can analyse the competition by running the percentage change and correlation function in pandas. Percentage change will find how much the price changes compared to the previous day which defines returns. Knowing the correlation will help us see whether the returns are affected by other stocks’ returns" }, { "code": null, "e": 5458, "s": 5405, "text": "retscomp = dfcomp.pct_change()corr = retscomp.corr()" }, { "code": null, "e": 5535, "s": 5458, "text": "Let’s plot Apple and GE with ScatterPlot to view their return distributions." }, { "code": null, "e": 5625, "s": 5535, "text": "plt.scatter(retscomp.AAPL, retscomp.GE)plt.xlabel(‘Returns AAPL’)plt.ylabel(‘Returns GE’)" }, { "code": null, "e": 5816, "s": 5625, "text": "We can see here that there are slight positive correlations among GE returns and Apple returns. It seems like that the higher the Apple returns, the higher GE returns as well for most cases." }, { "code": null, "e": 6191, "s": 5816, "text": "Let us further improve our analysis by plotting the scatter_matrix to visualize possible correlations among competing stocks. At the diagonal point, we will run Kernel Density Estimate (KDE). KDE is a fundamental data smoothing problem where inferences about the population are made, based on a finite data sample. It helps generate estimations of the overall distributions." }, { "code": null, "e": 6208, "s": 6191, "text": "en.wikipedia.org" }, { "code": null, "e": 6271, "s": 6208, "text": "pd.scatter_matrix(retscomp, diagonal='kde', figsize=(10, 10));" }, { "code": null, "e": 6376, "s": 6271, "text": "From here we could see most of the distributions among stocks which approximately positive correlations." }, { "code": null, "e": 6573, "s": 6376, "text": "To prove the positive correlations, we will use heat maps to visualize the correlation ranges among the competing stocks. Notice that the lighter the color, the more correlated the two stocks are." }, { "code": null, "e": 6723, "s": 6573, "text": "plt.imshow(corr, cmap='hot', interpolation='none')plt.colorbar()plt.xticks(range(len(corr)), corr.columns)plt.yticks(range(len(corr)), corr.columns);" }, { "code": null, "e": 6973, "s": 6723, "text": "From the Scatter Matrix and Heatmap, we can find great correlations among the competing stocks. However, this might not show causality, and could just show the trend in the technology industry rather than show how competing stocks affect each other." }, { "code": null, "e": 7159, "s": 6973, "text": "Apart from correlation, we also analyse each stock’s risks and returns. In this case we are extracting the average of returns (Return Rate) and the standard deviation of returns (Risk)." }, { "code": null, "e": 7617, "s": 7159, "text": "plt.scatter(retscomp.mean(), retscomp.std())plt.xlabel('Expected returns')plt.ylabel('Risk')for label, x, y in zip(retscomp.columns, retscomp.mean(), retscomp.std()): plt.annotate( label, xy = (x, y), xytext = (20, -20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))" }, { "code": null, "e": 8108, "s": 7617, "text": "Now you could view this neat chart of risk and return comparisons for competing stocks. Logically, you would like to minimize the risk and maximize returns. Therefore, you would want to draw the line for your risk-return tolerance (The red line). You would then create the rules to buy those stocks under the red line (MSFT, GE, and IBM) and sell those stocks above the red line (AAPL and GOOG). This red line showcases your expected value threshold and your baseline for buy/sell decision." }, { "code": null, "e": 8357, "s": 8108, "text": "We will use these three machine learning models to predict our stocks: Simple Linear Analysis, Quadratic Discriminant Analysis (QDA), and K Nearest Neighbor (KNN). But first, let us engineer some features: High Low Percentage and Percentage Change." }, { "code": null, "e": 8531, "s": 8357, "text": "dfreg = df.loc[:,[‘Adj Close’,’Volume’]]dfreg[‘HL_PCT’] = (df[‘High’] — df[‘Low’]) / df[‘Close’] * 100.0dfreg[‘PCT_change’] = (df[‘Close’] — df[‘Open’]) / df[‘Open’] * 100.0" }, { "code": null, "e": 8643, "s": 8531, "text": "We will clean up and process the data using the following steps before putting them into the prediction models:" }, { "code": null, "e": 9017, "s": 8643, "text": "Drop missing valueSeparating the label here, we want to predict the AdjCloseScale the X so that everyone can have the same distribution for linear regressionFinally We want to find Data Series of late X and early X (train) for model generation and evaluationSeparate label and identify it as ySeparation of training and testing of model by cross validation train test split" }, { "code": null, "e": 9036, "s": 9017, "text": "Drop missing value" }, { "code": null, "e": 9095, "s": 9036, "text": "Separating the label here, we want to predict the AdjClose" }, { "code": null, "e": 9177, "s": 9095, "text": "Scale the X so that everyone can have the same distribution for linear regression" }, { "code": null, "e": 9279, "s": 9177, "text": "Finally We want to find Data Series of late X and early X (train) for model generation and evaluation" }, { "code": null, "e": 9315, "s": 9279, "text": "Separate label and identify it as y" }, { "code": null, "e": 9396, "s": 9315, "text": "Separation of training and testing of model by cross validation train test split" }, { "code": null, "e": 9438, "s": 9396, "text": "Please refer the preparation codes below." }, { "code": null, "e": 10130, "s": 9438, "text": "# Drop missing valuedfreg.fillna(value=-99999, inplace=True)# We want to separate 1 percent of the data to forecastforecast_out = int(math.ceil(0.01 * len(dfreg)))# Separating the label here, we want to predict the AdjCloseforecast_col = 'Adj Close'dfreg['label'] = dfreg[forecast_col].shift(-forecast_out)X = np.array(dfreg.drop(['label'], 1))# Scale the X so that everyone can have the same distribution for linear regressionX = preprocessing.scale(X)# Finally We want to find Data Series of late X and early X (train) for model generation and evaluationX_lately = X[-forecast_out:]X = X[:-forecast_out]# Separate label and identify it as yy = np.array(dfreg['label'])y = y[:-forecast_out]" }, { "code": null, "e": 10198, "s": 10130, "text": "But first, let’s insert the following imports for our Scikit-Learn:" }, { "code": null, "e": 10429, "s": 10198, "text": "from sklearn.linear_model import LinearRegressionfrom sklearn.neighbors import KNeighborsRegressorfrom sklearn.linear_model import Ridgefrom sklearn.preprocessing import PolynomialFeaturesfrom sklearn.pipeline import make_pipeline" }, { "code": null, "e": 10748, "s": 10429, "text": "Simple Linear Analysis shows a linear relationship between two or more variables. When we draw this relationship within two variables, we get a straight line. Quadratic Discriminant Analysis would be similar to Simple Linear Analysis, except that the model allowed polynomial (e.g: x squared) and would produce curves." }, { "code": null, "e": 10932, "s": 10748, "text": "Linear Regression predicts dependent variables (y) as the outputs given independent variables (x) as the inputs. During the plotting, this will give us a straight line as shown below:" }, { "code": null, "e": 11071, "s": 10932, "text": "This is an amazing publication which showed a very comprehensive review of Linear Regression. Please refer to the link below for the view." }, { "code": null, "e": 11094, "s": 11071, "text": "towardsdatascience.com" }, { "code": null, "e": 11238, "s": 11094, "text": "We will plug and play the existing Scikit-Learn library and train the model by selecting our X and y train sets. The code will be as following." }, { "code": null, "e": 11542, "s": 11238, "text": "# Linear regressionclfreg = LinearRegression(n_jobs=-1)clfreg.fit(X_train, y_train)# Quadratic Regression 2clfpoly2 = make_pipeline(PolynomialFeatures(2), Ridge())clfpoly2.fit(X_train, y_train)# Quadratic Regression 3clfpoly3 = make_pipeline(PolynomialFeatures(3), Ridge())clfpoly3.fit(X_train, y_train)" }, { "code": null, "e": 11802, "s": 11542, "text": "This KNN uses feature similarity to predict values of data points. This ensures that the new point assigned is similar to the points in the data set. To find out similarity, we will extract the points to release the minimum distance (e.g: Euclidean Distance)." }, { "code": null, "e": 11915, "s": 11802, "text": "Please refer to this link for further details on the model. This is really useful to improve your understanding." }, { "code": null, "e": 11939, "s": 11915, "text": "www.analyticsvidhya.com" }, { "code": null, "e": 12027, "s": 11939, "text": "# KNN Regressionclfknn = KNeighborsRegressor(n_neighbors=2)clfknn.fit(X_train, y_train)" }, { "code": null, "e": 12207, "s": 12027, "text": "A simple quick and dirty way to evaluate is to use the score method in each trained model. The score method finds the mean accuracy of self.predict(X) with y of the test data set." }, { "code": null, "e": 12649, "s": 12207, "text": "confidencereg = clfreg.score(X_test, y_test)confidencepoly2 = clfpoly2.score(X_test,y_test)confidencepoly3 = clfpoly3.score(X_test,y_test)confidenceknn = clfknn.score(X_test, y_test)# results('The linear regression confidence is ', 0.96399641826551985)('The quadratic regression 2 confidence is ', 0.96492624557970319)('The quadratic regression 3 confidence is ', 0.9652082834532858)('The knn regression confidence is ', 0.92844658034790639)" }, { "code": null, "e": 12906, "s": 12649, "text": "This shows an enormous accuracy score (>0.95) for most of the models. However this does not mean we can blindly place our stocks. There are still many issues to consider, especially with different companies that have different price trajectories over time." }, { "code": null, "e": 12968, "s": 12906, "text": "For sanity testing, let us print some of the stocks forecast." }, { "code": null, "e": 13366, "s": 12968, "text": "forecast_set = clf.predict(X_lately)dfreg['Forecast'] = np.nan#result(array([ 115.44941187, 115.20206522, 116.78688393, 116.70244946, 116.58503739, 115.98769407, 116.54315699, 117.40012338, 117.21473053, 116.57244657, 116.048717 , 116.26444966, 115.78374093, 116.50647805, 117.92064806, 118.75581186, 118.82688731, 119.51873699]), 0.96234891774075604, 18)" }, { "code": null, "e": 13533, "s": 13366, "text": "Based on the forecast, we will visualize the plot with our existing historical data. This will help us visualize how the model fares to predict future stocks pricing." }, { "code": null, "e": 13935, "s": 13533, "text": "last_date = dfreg.iloc[-1].namelast_unix = last_datenext_unix = last_unix + datetime.timedelta(days=1)for i in forecast_set: next_date = next_unix next_unix += datetime.timedelta(days=1) dfreg.loc[next_date] = [np.nan for _ in range(len(dfreg.columns)-1)]+[i]dfreg['Adj Close'].tail(500).plot()dfreg['Forecast'].tail(500).plot()plt.legend(loc=4)plt.xlabel('Date')plt.ylabel('Price')plt.show()" }, { "code": null, "e": 14197, "s": 13935, "text": "As we can see the blue color showcased the forecast on the stocks price based on regression. The forecast predicted that there would be a downturn for not too long, then it will recover. Therefore, we could buy the stocks during downturn and sell during upturn." }, { "code": null, "e": 14422, "s": 14197, "text": "To further analyse the stocks, here are some ideas on how you could contribute. These ideas would be useful to get a more comprehensive analysis on stocks. Feel free to let me know should there be more clarifications needed." }, { "code": null, "e": 14513, "s": 14422, "text": "Analyse economic qualitative factors such as news (news sourcing and sentimental analysis)" }, { "code": null, "e": 14629, "s": 14513, "text": "Analyse economic quantitative factors such as HPI of a certain country, economic inequality among origin of company" }, { "code": null, "e": 14923, "s": 14629, "text": "The purpose for this Proof Of Concepts (POC) was created as a part of investments side project that the I am currently managing. The goal of this application is to help you retrieve and display the right financial insights quickly about a certain company stocks price and predicting its value." }, { "code": null, "e": 15151, "s": 14923, "text": "In the POC, I used Pandas- Web Datareader to find the stocks prices , Scikit-Learn to predict and generate machine learning models, and finally Python as the scripting language. The Github Python Notebook Code is located below." }, { "code": null, "e": 15162, "s": 15151, "text": "github.com" }, { "code": null, "e": 15235, "s": 15162, "text": "Feel free to clone the repository and contribute whenever you have time." }, { "code": null, "e": 15550, "s": 15235, "text": "In lieu with today’s topics about stocks analysis. You could also visit my Value Investing Publication where I talked about scraping stocks financial information and displaying it in an easy to read dashboard which processes stocks valuation based on Value Investing methodology. Please visit it and contribute :)." }, { "code": null, "e": 15573, "s": 15550, "text": "towardsdatascience.com" }, { "code": null, "e": 15873, "s": 15573, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 16081, "s": 15873, "text": "I would like to thank you my fellow Accountancy and Finance friends who gave me constructive feedback on this publication. I really enjoyed learning that you gained much values from this publication of mine." }, { "code": null, "e": 16295, "s": 16081, "text": "Whew... That’s it, about my idea which I formulated into writings. I really hope this has been a great read for you guys. With that, I hope my idea could be a source of inspiration for you to develop and innovate." }, { "code": null, "e": 16370, "s": 16295, "text": "Please reach out to me via my LinkedIn and subscribe to my Youtube Channel" }, { "code": null, "e": 16408, "s": 16370, "text": "If you like it, please give me Claps." }, { "code": null, "e": 16451, "s": 16408, "text": "Comment out below to suggest and feedback." }, { "code": null, "e": 16467, "s": 16451, "text": "Happy coding :)" }, { "code": null, "e": 16802, "s": 16467, "text": "Disclaimer: This disclaimer informs readers that the views, thoughts, and opinions expressed in the text belong solely to the author, and not necessarily to the author’s employer, organization, committee or other group or individual. References are picked up from the list and any similarities with other works are purely coincidental" } ]
An Introductory Example of Bayesian Optimization in Python with Hyperopt | by Will Koehrsen | Towards Data Science
Although finding the minimum of a function might seem mundane, it’s a critical problem that extends to many domains. For example, optimizing the hyperparameters of a machine learning model is just a minimization problem: it means searching for the hyperparameters with the lowest validation loss. Bayesian optimization is a probabilistic model based approach for finding the minimum of any function that returns a real-value metric. This function may be as simple as f(x) = x2, or it can be as complex as the validation error of a deep neural network with respect to hundreds of model architecture and hyperparameter choices. Recent results suggest Bayesian hyperparameter optimization of machine learning models is more efficient than manual, random, or grid search with: Better overall performance on the test set Less time required for optimization Clearly, a method this powerful has to be extremely hard to use right? Fortunately, there are a number of Python libraries such as Hyperopt that allow for simple applications of Bayesian optimization. In fact, we can do basic Bayesian optimization in one line! If you can understand everything in the above code, then you can probably stop reading and start using this method. If you want a little more explanation, in this article, we’ll go through the basic structure of a Hyperopt program so later we can expand this framework to more complex problems, such as machine learning hyperparameter optimization. The code for this article is available in a Jupyter Notebook on GitHub. Optimization is finding the input value or set of values to an objective function that yields the lowest output value, called a “loss”. The objective function f(x) = x2 has a single input and is a 1-D optimization problem. Typically, in machine learning, our objective function is many-dimensional because it takes in a set of model hyperparameters. For simple functions in low dimensions, we can find the minimum loss by trying many input values and seeing which one yields the lowest loss. We could create a grid of input values and try all of them — grid search — or randomly pick some values — random search. As long as evaluations of the objective function (“evals”) are cheap, these uninformed methods might be adequate. However, for complex objective functions like the 5-fold cross validation error of a neural network, each eval of the objective function means training the network 5 times! For models that take days to train, we want a way to limit calls to the evaluation function. Random search is actually more efficient than grid search for problems with high dimensions, but is still an uniformed method where the search does not use previous results to pick the next input values to try. Let’s see if you’re smarter than random search. Say we have the following results from training a random forest for a regression task: If you were picking the next number of trees to evaluate, where would you concentrate? Clearly, the best option is around 100 trees because a smaller number of trees has tended to yield a lower loss. You’ve basically just done Bayesian optimization in your head: using the previous results, you formed a probabilistic model of the objective function which said that a smaller number of trees is likely to result in a lower error. Bayesian optimization, also called Sequential Model-Based Optimization (SMBO), implements this idea by building a probability model of the objective function that maps input values to a probability of a loss: p (loss | input values). The probability model, also called the surrogate or response surface, is easier to optimize than the actual objective function. Bayesian methods select the next values to evaluate by applying a criteria (usually Expected Improvement) to the surrogate. The concept is to limit evals of the objective function by spending more time choosing the next values to try. Bayesian Reasoning means updating a model based on new evidence, and, with each eval, the surrogate is re-calculated to incorporate the latest information. The longer the algorithm runs, the closer the surrogate function comes to resembling the actual objective function. Bayesian Optimization methods differ in how they construct the surrogate function: common choices include Gaussian Processes, Random Forest Regression, and, the choice in Hyperopt, the Tree Parzen Estimator (TPE). The details of these methods can be a little tough to understand (I wrote a high-level overview here), and it’s also difficult to figure out which works the best: if you read articles by the designers of the algorithms, each claim their method is superior! However, the particular algorithms does not matter as much as upgrading from random/grid search to Bayesian Optimization. Using any library (Spearmint, Hyperopt, SMAC) will be fine for getting started! With that in mind, let’s see how to put Bayesian optimization into practice. Formulating an optimization problem in Hyperopt requires four parts: Objective Function: takes in an input and returns a loss to minimizeDomain space: the range of input values to evaluateOptimization Algorithm: the method used to construct the surrogate function and choose the next values to evaluateResults: score, value pairs that the algorithm uses to build the model Objective Function: takes in an input and returns a loss to minimize Domain space: the range of input values to evaluate Optimization Algorithm: the method used to construct the surrogate function and choose the next values to evaluate Results: score, value pairs that the algorithm uses to build the model Once we know how to specify these four parts, they can be applied to any optimization problem. For now, we will walk through a basic problem. The objective function can be any function that returns a real value that we want to minimize. (If we have a value that we want to maximize, such as accuracy, then we just have our function return the negative of that metric.) Here we will use polynomial function with the code and graph shown below: This problem is 1-D because we are optimizing over a single value, x. In Hyperopt, the objective function can take in any number of inputs but must return a single loss to minimize. The domain space is the input values over which we want to search. As a first try, we can use a uniform distribution over the range that our function is defined: from hyperopt import hp# Create the domain spacespace = hp.uniform('x', -5, 6) To visualize the domain, we can draw samples from the space and plot the histogram: If we have an idea where the best values are, then we can make a smarter domain that places more probability in higher scoring regions. (See the notebook for an example of using a normal distribution on this problem.) While this is technically the most difficult concept, in Hyperopt creating an optimization algorithm only requires one line. We are using the Tree-structured Parzen Estimator model, and we can have Hyperopt configure it for us using the suggest method. from hyperopt import tpe# Create the algorithmtpe_algo = tpe.suggest There’s a lot of theory going on behind the scenes we don’t have to worry about! In the notebook, we also use a random search algorithm for comparison. This is not strictly necessary as Hyperopt keeps track of the results for the algorithm internally. However, if we want to inspect the progression of the alogorithm, we need to create a Trials object that will record the values and the scores: from hyperopt import Trials# Create a trials objecttpe_trials = Trials() Now that the problem is defined, we can minimize our objective function! To do so, we use the fmin function that takes the four parts above, as well as a maximum number of trials: {'x': 4.878208088771056} For this run, the algorithm found the best value of x (the one which minimizes the loss) in just under 1000 trials. The best object only returns the input value that minimizes the function. While this is what we are looking for, it doesn’t give us much insight into the method. To get more details, we can get the results from the trials object: Visualizations are useful for an intuitive understanding of what is occurring. For example, let’s plot the values of x evaluated in order: Over time, the input values cluster around the optimal indicated by the red line. This is a simple problem, so the algorithm does not have much trouble finding the best value of x. To contrast with what a naive search looks like, if we run the same problem with random search we get the following figure: The random search basically tries values, well, at random! The differences between the values become even more apparent when we look at the histogram of values for x of the TPE algorithm and random search: Here we see the main benefit of Bayesian model-based optimization: more concentration on promising input values. When we are searching over dozens of parameters and each eval takes hours or days, reducing the number of evals is critical. Bayesian optimization minimizes the number of evals by reasoning based on previous results what input values should be tried in the future. (In this case, random search actually finds a value of x very close to the optimal because of the basic 1-D objective function and the number of evals.) Once we have mastered how to minimize a simple function, we can extend this to any problem where we need to optimize a function that returns a real value. For example, to tune the hyperparameters of a machine learning model requires only a few adjustments to the basic framework: the objective function must take in the model hyperparameters and return the validation loss, and the domain space will need to be specific to the model. For an idea what this looks like, I wrote a notebook where I tune the hyperparameters of a gradient boosting machine which will be the next article! Bayesian model-based optimization is intuitive: choose the next input values to evaluate based on the past results to concentrate the search on more promising values. The end outcome is a reduction in the total number of search iterations compared to uninformed random or grid search methods. Although this was only a simple example, we can take the concepts here and use them in a wide variety of useful situations. The takeaways from this article are: Bayesian Optimization is an efficient method for finding the minimum of a function that works by constructing a probabilistic (surrogate) model of the objective functionThe surrogate is informed by past search results and, by choosing the next values from this model, the search is concentrated on promising valuesThe overall outcome of these method is reduced search time and better valuesThese powerful techniques can be implemented easily in Python libraries like HyperoptThe Bayesian optimization framework can be extended to complex problems including hyperparameter tuning of machine learning models Bayesian Optimization is an efficient method for finding the minimum of a function that works by constructing a probabilistic (surrogate) model of the objective function The surrogate is informed by past search results and, by choosing the next values from this model, the search is concentrated on promising values The overall outcome of these method is reduced search time and better values These powerful techniques can be implemented easily in Python libraries like Hyperopt The Bayesian optimization framework can be extended to complex problems including hyperparameter tuning of machine learning models As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will.
[ { "code": null, "e": 469, "s": 172, "text": "Although finding the minimum of a function might seem mundane, it’s a critical problem that extends to many domains. For example, optimizing the hyperparameters of a machine learning model is just a minimization problem: it means searching for the hyperparameters with the lowest validation loss." }, { "code": null, "e": 798, "s": 469, "text": "Bayesian optimization is a probabilistic model based approach for finding the minimum of any function that returns a real-value metric. This function may be as simple as f(x) = x2, or it can be as complex as the validation error of a deep neural network with respect to hundreds of model architecture and hyperparameter choices." }, { "code": null, "e": 945, "s": 798, "text": "Recent results suggest Bayesian hyperparameter optimization of machine learning models is more efficient than manual, random, or grid search with:" }, { "code": null, "e": 988, "s": 945, "text": "Better overall performance on the test set" }, { "code": null, "e": 1024, "s": 988, "text": "Less time required for optimization" }, { "code": null, "e": 1285, "s": 1024, "text": "Clearly, a method this powerful has to be extremely hard to use right? Fortunately, there are a number of Python libraries such as Hyperopt that allow for simple applications of Bayesian optimization. In fact, we can do basic Bayesian optimization in one line!" }, { "code": null, "e": 1706, "s": 1285, "text": "If you can understand everything in the above code, then you can probably stop reading and start using this method. If you want a little more explanation, in this article, we’ll go through the basic structure of a Hyperopt program so later we can expand this framework to more complex problems, such as machine learning hyperparameter optimization. The code for this article is available in a Jupyter Notebook on GitHub." }, { "code": null, "e": 2606, "s": 1706, "text": "Optimization is finding the input value or set of values to an objective function that yields the lowest output value, called a “loss”. The objective function f(x) = x2 has a single input and is a 1-D optimization problem. Typically, in machine learning, our objective function is many-dimensional because it takes in a set of model hyperparameters. For simple functions in low dimensions, we can find the minimum loss by trying many input values and seeing which one yields the lowest loss. We could create a grid of input values and try all of them — grid search — or randomly pick some values — random search. As long as evaluations of the objective function (“evals”) are cheap, these uninformed methods might be adequate. However, for complex objective functions like the 5-fold cross validation error of a neural network, each eval of the objective function means training the network 5 times!" }, { "code": null, "e": 3045, "s": 2606, "text": "For models that take days to train, we want a way to limit calls to the evaluation function. Random search is actually more efficient than grid search for problems with high dimensions, but is still an uniformed method where the search does not use previous results to pick the next input values to try. Let’s see if you’re smarter than random search. Say we have the following results from training a random forest for a regression task:" }, { "code": null, "e": 3475, "s": 3045, "text": "If you were picking the next number of trees to evaluate, where would you concentrate? Clearly, the best option is around 100 trees because a smaller number of trees has tended to yield a lower loss. You’ve basically just done Bayesian optimization in your head: using the previous results, you formed a probabilistic model of the objective function which said that a smaller number of trees is likely to result in a lower error." }, { "code": null, "e": 4072, "s": 3475, "text": "Bayesian optimization, also called Sequential Model-Based Optimization (SMBO), implements this idea by building a probability model of the objective function that maps input values to a probability of a loss: p (loss | input values). The probability model, also called the surrogate or response surface, is easier to optimize than the actual objective function. Bayesian methods select the next values to evaluate by applying a criteria (usually Expected Improvement) to the surrogate. The concept is to limit evals of the objective function by spending more time choosing the next values to try." }, { "code": null, "e": 4558, "s": 4072, "text": "Bayesian Reasoning means updating a model based on new evidence, and, with each eval, the surrogate is re-calculated to incorporate the latest information. The longer the algorithm runs, the closer the surrogate function comes to resembling the actual objective function. Bayesian Optimization methods differ in how they construct the surrogate function: common choices include Gaussian Processes, Random Forest Regression, and, the choice in Hyperopt, the Tree Parzen Estimator (TPE)." }, { "code": null, "e": 5094, "s": 4558, "text": "The details of these methods can be a little tough to understand (I wrote a high-level overview here), and it’s also difficult to figure out which works the best: if you read articles by the designers of the algorithms, each claim their method is superior! However, the particular algorithms does not matter as much as upgrading from random/grid search to Bayesian Optimization. Using any library (Spearmint, Hyperopt, SMAC) will be fine for getting started! With that in mind, let’s see how to put Bayesian optimization into practice." }, { "code": null, "e": 5163, "s": 5094, "text": "Formulating an optimization problem in Hyperopt requires four parts:" }, { "code": null, "e": 5467, "s": 5163, "text": "Objective Function: takes in an input and returns a loss to minimizeDomain space: the range of input values to evaluateOptimization Algorithm: the method used to construct the surrogate function and choose the next values to evaluateResults: score, value pairs that the algorithm uses to build the model" }, { "code": null, "e": 5536, "s": 5467, "text": "Objective Function: takes in an input and returns a loss to minimize" }, { "code": null, "e": 5588, "s": 5536, "text": "Domain space: the range of input values to evaluate" }, { "code": null, "e": 5703, "s": 5588, "text": "Optimization Algorithm: the method used to construct the surrogate function and choose the next values to evaluate" }, { "code": null, "e": 5774, "s": 5703, "text": "Results: score, value pairs that the algorithm uses to build the model" }, { "code": null, "e": 5916, "s": 5774, "text": "Once we know how to specify these four parts, they can be applied to any optimization problem. For now, we will walk through a basic problem." }, { "code": null, "e": 6143, "s": 5916, "text": "The objective function can be any function that returns a real value that we want to minimize. (If we have a value that we want to maximize, such as accuracy, then we just have our function return the negative of that metric.)" }, { "code": null, "e": 6217, "s": 6143, "text": "Here we will use polynomial function with the code and graph shown below:" }, { "code": null, "e": 6399, "s": 6217, "text": "This problem is 1-D because we are optimizing over a single value, x. In Hyperopt, the objective function can take in any number of inputs but must return a single loss to minimize." }, { "code": null, "e": 6561, "s": 6399, "text": "The domain space is the input values over which we want to search. As a first try, we can use a uniform distribution over the range that our function is defined:" }, { "code": null, "e": 6640, "s": 6561, "text": "from hyperopt import hp# Create the domain spacespace = hp.uniform('x', -5, 6)" }, { "code": null, "e": 6724, "s": 6640, "text": "To visualize the domain, we can draw samples from the space and plot the histogram:" }, { "code": null, "e": 6942, "s": 6724, "text": "If we have an idea where the best values are, then we can make a smarter domain that places more probability in higher scoring regions. (See the notebook for an example of using a normal distribution on this problem.)" }, { "code": null, "e": 7195, "s": 6942, "text": "While this is technically the most difficult concept, in Hyperopt creating an optimization algorithm only requires one line. We are using the Tree-structured Parzen Estimator model, and we can have Hyperopt configure it for us using the suggest method." }, { "code": null, "e": 7264, "s": 7195, "text": "from hyperopt import tpe# Create the algorithmtpe_algo = tpe.suggest" }, { "code": null, "e": 7416, "s": 7264, "text": "There’s a lot of theory going on behind the scenes we don’t have to worry about! In the notebook, we also use a random search algorithm for comparison." }, { "code": null, "e": 7660, "s": 7416, "text": "This is not strictly necessary as Hyperopt keeps track of the results for the algorithm internally. However, if we want to inspect the progression of the alogorithm, we need to create a Trials object that will record the values and the scores:" }, { "code": null, "e": 7733, "s": 7660, "text": "from hyperopt import Trials# Create a trials objecttpe_trials = Trials()" }, { "code": null, "e": 7913, "s": 7733, "text": "Now that the problem is defined, we can minimize our objective function! To do so, we use the fmin function that takes the four parts above, as well as a maximum number of trials:" }, { "code": null, "e": 7938, "s": 7913, "text": "{'x': 4.878208088771056}" }, { "code": null, "e": 8284, "s": 7938, "text": "For this run, the algorithm found the best value of x (the one which minimizes the loss) in just under 1000 trials. The best object only returns the input value that minimizes the function. While this is what we are looking for, it doesn’t give us much insight into the method. To get more details, we can get the results from the trials object:" }, { "code": null, "e": 8423, "s": 8284, "text": "Visualizations are useful for an intuitive understanding of what is occurring. For example, let’s plot the values of x evaluated in order:" }, { "code": null, "e": 8604, "s": 8423, "text": "Over time, the input values cluster around the optimal indicated by the red line. This is a simple problem, so the algorithm does not have much trouble finding the best value of x." }, { "code": null, "e": 8728, "s": 8604, "text": "To contrast with what a naive search looks like, if we run the same problem with random search we get the following figure:" }, { "code": null, "e": 8934, "s": 8728, "text": "The random search basically tries values, well, at random! The differences between the values become even more apparent when we look at the histogram of values for x of the TPE algorithm and random search:" }, { "code": null, "e": 9312, "s": 8934, "text": "Here we see the main benefit of Bayesian model-based optimization: more concentration on promising input values. When we are searching over dozens of parameters and each eval takes hours or days, reducing the number of evals is critical. Bayesian optimization minimizes the number of evals by reasoning based on previous results what input values should be tried in the future." }, { "code": null, "e": 9465, "s": 9312, "text": "(In this case, random search actually finds a value of x very close to the optimal because of the basic 1-D objective function and the number of evals.)" }, { "code": null, "e": 9899, "s": 9465, "text": "Once we have mastered how to minimize a simple function, we can extend this to any problem where we need to optimize a function that returns a real value. For example, to tune the hyperparameters of a machine learning model requires only a few adjustments to the basic framework: the objective function must take in the model hyperparameters and return the validation loss, and the domain space will need to be specific to the model." }, { "code": null, "e": 10048, "s": 9899, "text": "For an idea what this looks like, I wrote a notebook where I tune the hyperparameters of a gradient boosting machine which will be the next article!" }, { "code": null, "e": 10465, "s": 10048, "text": "Bayesian model-based optimization is intuitive: choose the next input values to evaluate based on the past results to concentrate the search on more promising values. The end outcome is a reduction in the total number of search iterations compared to uninformed random or grid search methods. Although this was only a simple example, we can take the concepts here and use them in a wide variety of useful situations." }, { "code": null, "e": 10502, "s": 10465, "text": "The takeaways from this article are:" }, { "code": null, "e": 11108, "s": 10502, "text": "Bayesian Optimization is an efficient method for finding the minimum of a function that works by constructing a probabilistic (surrogate) model of the objective functionThe surrogate is informed by past search results and, by choosing the next values from this model, the search is concentrated on promising valuesThe overall outcome of these method is reduced search time and better valuesThese powerful techniques can be implemented easily in Python libraries like HyperoptThe Bayesian optimization framework can be extended to complex problems including hyperparameter tuning of machine learning models" }, { "code": null, "e": 11278, "s": 11108, "text": "Bayesian Optimization is an efficient method for finding the minimum of a function that works by constructing a probabilistic (surrogate) model of the objective function" }, { "code": null, "e": 11424, "s": 11278, "text": "The surrogate is informed by past search results and, by choosing the next values from this model, the search is concentrated on promising values" }, { "code": null, "e": 11501, "s": 11424, "text": "The overall outcome of these method is reduced search time and better values" }, { "code": null, "e": 11587, "s": 11501, "text": "These powerful techniques can be implemented easily in Python libraries like Hyperopt" }, { "code": null, "e": 11718, "s": 11587, "text": "The Bayesian optimization framework can be extended to complex problems including hyperparameter tuning of machine learning models" } ]
Function to add up all the natural numbers from 1 to num in JavaScript
We are required to write a JavaScript function that takes in a number, say num. Then our function should return the sum of all the natural numbers between 1 and num, including 1 and num. For example, if num is − const num = 5; Then the output should be − const output = 15; because, 1+2+3+4+5 = 15 We will use the below formula to solve this problem − Sum of all natural number upto n = ((n*(n+1))/2) The code for this will be − const num = 5; const sumUpto = num => { const res = (num * (num + 1)) / 2; return res; }; console.log(sumUpto(num)); console.log(sumUpto(7)); console.log(sumUpto(45)); console.log(sumUpto(2)); console.log(sumUpto(8)); console.log(sumUpto(99)); And the output in the console will be − 15 28 1035 3 36 4950
[ { "code": null, "e": 1142, "s": 1062, "text": "We are required to write a JavaScript function that takes in a number, say num." }, { "code": null, "e": 1249, "s": 1142, "text": "Then our function should return the sum of all the natural numbers between 1 and num, including 1 and num." }, { "code": null, "e": 1274, "s": 1249, "text": "For example, if num is −" }, { "code": null, "e": 1289, "s": 1274, "text": "const num = 5;" }, { "code": null, "e": 1317, "s": 1289, "text": "Then the output should be −" }, { "code": null, "e": 1336, "s": 1317, "text": "const output = 15;" }, { "code": null, "e": 1345, "s": 1336, "text": "because," }, { "code": null, "e": 1360, "s": 1345, "text": "1+2+3+4+5 = 15" }, { "code": null, "e": 1414, "s": 1360, "text": "We will use the below formula to solve this problem −" }, { "code": null, "e": 1449, "s": 1414, "text": "Sum of all natural number upto n =" }, { "code": null, "e": 1463, "s": 1449, "text": "((n*(n+1))/2)" }, { "code": null, "e": 1491, "s": 1463, "text": "The code for this will be −" }, { "code": null, "e": 1741, "s": 1491, "text": "const num = 5;\nconst sumUpto = num => {\n const res = (num * (num + 1)) / 2;\n return res;\n};\nconsole.log(sumUpto(num));\nconsole.log(sumUpto(7));\nconsole.log(sumUpto(45));\nconsole.log(sumUpto(2));\nconsole.log(sumUpto(8));\nconsole.log(sumUpto(99));" }, { "code": null, "e": 1781, "s": 1741, "text": "And the output in the console will be −" }, { "code": null, "e": 1802, "s": 1781, "text": "15\n28\n1035\n3\n36\n4950" } ]
Can we change method signature in overriding in Java?
No, while overriding a method of the super class we need to make sure that both methods have same name, same parameters and, same return type else they both will be treated as different methods. In short, if we change the signature, you cannot override the super class’s method if you try the method of the super class will be executed. Reason − If you change the signature both are considered as different methods and, since the copy of super class method is available at sub class object, it will be executed. Live Demo class Super { void sample(int a, int b) { System.out.println("Method of the Super class"); } } public class MethodOverriding extends Super { void sample(int a, float b) { System.out.println("Method of the Sub class"); } public static void main(String args[]) { MethodOverriding obj = new MethodOverriding(); obj.sample(20, 20); } } Method of the Super class
[ { "code": null, "e": 1257, "s": 1062, "text": "No, while overriding a method of the super class we need to make sure that both methods have same name, same parameters and, same return type else they both will be treated as different methods." }, { "code": null, "e": 1399, "s": 1257, "text": "In short, if we change the signature, you cannot override the super class’s method if you try the method of the super class will be executed." }, { "code": null, "e": 1574, "s": 1399, "text": "Reason − If you change the signature both are considered as different methods and, since the copy of super class method is available at sub class object, it will be executed." }, { "code": null, "e": 1585, "s": 1574, "text": " Live Demo" }, { "code": null, "e": 1959, "s": 1585, "text": "class Super {\n void sample(int a, int b) {\n System.out.println(\"Method of the Super class\");\n }\n}\npublic class MethodOverriding extends Super {\n void sample(int a, float b) {\n System.out.println(\"Method of the Sub class\");\n }\n public static void main(String args[]) {\n MethodOverriding obj = new MethodOverriding();\n obj.sample(20, 20);\n }\n}" }, { "code": null, "e": 1985, "s": 1959, "text": "Method of the Super class" } ]
How to enable or disable local user on Windows OS using PowerShell?
To disable the local user on the windows OS using PowerShell, we can use the Disable-Localuser command provided by the local user name. In the below example, we are going to disable the local user called TestUser. Disable-LocalUser -Name TestUser If we see the GUI, the user account is disabled. To enable the above user, we can use the Enable-LocalUser command. Enable-LocalUser -Name Testuser To run the above command on the remote computer, we can use the Invoke-Command method. We need to make sure local user account exist on the remote computer. Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{ Enable-Localuser -Name TestUser } Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{ Disable-Localuser -Name TestUser } If the PowerShell version 5.1 or higher doesn’t exist in your environment, you can use the command prompt to enable or disable the local user account with the Active switch. net user username [/ACTIVE: {YES | NO}] Disable local user example − net user testuser /active:no To disable the existing local user using the above command, we need to use Invoke-Command for remoting. Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{ Net user testuser /active:no } To enable the local user on the local system, net user testuser /active:yes On the remote system, Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{ Net user testuser /active:yes }
[ { "code": null, "e": 1276, "s": 1062, "text": "To disable the local user on the windows OS using PowerShell, we can use the Disable-Localuser command provided by the local user name. In the below example, we are going to disable the local user called TestUser." }, { "code": null, "e": 1309, "s": 1276, "text": "Disable-LocalUser -Name TestUser" }, { "code": null, "e": 1358, "s": 1309, "text": "If we see the GUI, the user account is disabled." }, { "code": null, "e": 1425, "s": 1358, "text": "To enable the above user, we can use the Enable-LocalUser command." }, { "code": null, "e": 1457, "s": 1425, "text": "Enable-LocalUser -Name Testuser" }, { "code": null, "e": 1614, "s": 1457, "text": "To run the above command on the remote computer, we can use the Invoke-Command method. We need to make sure local user account exist on the remote computer." }, { "code": null, "e": 1722, "s": 1614, "text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{\n Enable-Localuser -Name TestUser\n}" }, { "code": null, "e": 1831, "s": 1722, "text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{\n Disable-Localuser -Name TestUser\n}" }, { "code": null, "e": 2005, "s": 1831, "text": "If the PowerShell version 5.1 or higher doesn’t exist in your environment, you can use the command prompt to enable or disable the local user account with the Active switch." }, { "code": null, "e": 2045, "s": 2005, "text": "net user username [/ACTIVE: {YES | NO}]" }, { "code": null, "e": 2074, "s": 2045, "text": "Disable local user example −" }, { "code": null, "e": 2103, "s": 2074, "text": "net user testuser /active:no" }, { "code": null, "e": 2207, "s": 2103, "text": "To disable the existing local user using the above command, we need to use Invoke-Command for remoting." }, { "code": null, "e": 2312, "s": 2207, "text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{\n Net user testuser /active:no\n}" }, { "code": null, "e": 2358, "s": 2312, "text": "To enable the local user on the local system," }, { "code": null, "e": 2388, "s": 2358, "text": "net user testuser /active:yes" }, { "code": null, "e": 2410, "s": 2388, "text": "On the remote system," }, { "code": null, "e": 2516, "s": 2410, "text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{\n Net user testuser /active:yes\n}" } ]
C library function - fputc()
The C library function int fputc(int char, FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. Following is the declaration for fputc() function. int fputc(int char, FILE *stream) char − This is the character to be written. This is passed as its int promotion. char − This is the character to be written. This is passed as its int promotion. stream − This is the pointer to a FILE object that identifies the stream where the character is to be written. stream − This is the pointer to a FILE object that identifies the stream where the character is to be written. If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set. The following example shows the usage of fputc() function. #include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("file.txt", "w+"); for( ch = 33 ; ch <= 100; ch++ ) { fputc(ch, fp); } fclose(fp); return(0); } Let us compile and run the above program that will create a file file.txt in the current directory, which will have following content − !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd Now let's see the content of the above file using the following program − #include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); } Let us compile and run above program to produce the following result − !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2209, "s": 2007, "text": "The C library function int fputc(int char, FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream." }, { "code": null, "e": 2260, "s": 2209, "text": "Following is the declaration for fputc() function." }, { "code": null, "e": 2294, "s": 2260, "text": "int fputc(int char, FILE *stream)" }, { "code": null, "e": 2375, "s": 2294, "text": "char − This is the character to be written. This is passed as its int promotion." }, { "code": null, "e": 2456, "s": 2375, "text": "char − This is the character to be written. This is passed as its int promotion." }, { "code": null, "e": 2567, "s": 2456, "text": "stream − This is the pointer to a FILE object that identifies the stream where the character is to be written." }, { "code": null, "e": 2678, "s": 2567, "text": "stream − This is the pointer to a FILE object that identifies the stream where the character is to be written." }, { "code": null, "e": 2824, "s": 2678, "text": "If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set." }, { "code": null, "e": 2883, "s": 2824, "text": "The following example shows the usage of fputc() function." }, { "code": null, "e": 3071, "s": 2883, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int ch;\n\n fp = fopen(\"file.txt\", \"w+\");\n for( ch = 33 ; ch <= 100; ch++ ) {\n fputc(ch, fp);\n }\n fclose(fp);\n\n return(0);\n}" }, { "code": null, "e": 3207, "s": 3071, "text": "Let us compile and run the above program that will create a file file.txt in the current directory, which will have following content −" }, { "code": null, "e": 3277, "s": 3207, "text": "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcd\n" }, { "code": null, "e": 3351, "s": 3277, "text": "Now let's see the content of the above file using the following program −" }, { "code": null, "e": 3582, "s": 3351, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int c;\n\n fp = fopen(\"file.txt\",\"r\");\n while(1) {\n c = fgetc(fp);\n if( feof(fp) ) {\n break ;\n }\n printf(\"%c\", c);\n }\n fclose(fp);\n return(0);\n}" }, { "code": null, "e": 3653, "s": 3582, "text": "Let us compile and run above program to produce the following result −" }, { "code": null, "e": 3723, "s": 3653, "text": "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcd\n" }, { "code": null, "e": 3756, "s": 3723, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3771, "s": 3756, "text": " Nishant Malik" }, { "code": null, "e": 3806, "s": 3771, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3821, "s": 3806, "text": " Nishant Malik" }, { "code": null, "e": 3856, "s": 3821, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3870, "s": 3856, "text": " Asif Hussain" }, { "code": null, "e": 3903, "s": 3870, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3921, "s": 3903, "text": " Richa Maheshwari" }, { "code": null, "e": 3956, "s": 3921, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3975, "s": 3956, "text": " Vandana Annavaram" }, { "code": null, "e": 4008, "s": 3975, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4020, "s": 4008, "text": " Amit Diwan" }, { "code": null, "e": 4027, "s": 4020, "text": " Print" }, { "code": null, "e": 4038, "s": 4027, "text": " Add Notes" } ]
How to Justify Text in TextView on Android?
This example demonstrates how to Justify Text in TextView on Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns: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:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/tvJustified" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:padding="20sp" android:justificationMode="inter_word" android:text="The text in this TextView is justified. This feature is introduced in Android version >= 8.0. The text in this TextView is justified. This feature is introduced in Android version >= 8.0. The text in this TextView is justified. This feature is introduced in Android version >= 8.0." /> <TextView android:id="@+id/tvNotJustified" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:padding="20sp" android:text="The text in this TextView is not justified. No justification. The text in this TextView is not justified. No justification. The text in this TextView is not justified. No justification. " /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 3 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.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": 1132, "s": 1062, "text": "This example demonstrates how to Justify Text in TextView on Android." }, { "code": null, "e": 1262, "s": 1132, "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": 1328, "s": 1262, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2707, "s": 1328, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/tvJustified\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"20sp\"\n android:padding=\"20sp\"\n android:justificationMode=\"inter_word\"\n android:text=\"The text in this TextView is justified.\n This feature is introduced in Android version >= 8.0.\n The text in this TextView is justified.\n This feature is introduced in Android version >= 8.0.\n The text in this TextView is justified.\n This feature is introduced in Android version >= 8.0.\" />\n <TextView\n android:id=\"@+id/tvNotJustified\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"20sp\"\n android:padding=\"20sp\"\n android:text=\"The text in this TextView is not justified.\n No justification. The text in this TextView is not justified.\n No justification. The text in this\n TextView is not justified. No justification. \" />\n</LinearLayout>" }, { "code": null, "e": 2765, "s": 2707, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3086, "s": 2765, "text": "package com.example.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 3152, "s": 3086, "text": "Step 3 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3826, "s": 3152, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.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": 4171, "s": 3826, "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": 4212, "s": 4171, "text": "Click here to download the project code." } ]
PHP | MySQL ( Creating Table ) - GeeksforGeeks
21 Mar, 2018 What is a table?In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a MySQL Table Using MySQLi and PDOWe have already learned about creating databases in MySQL from PHP in this article. The steps to create table are similar to creating databases. The difference is instead of creating a new database we will connect to existing database and create a table in that database. To connect to an existing database we can pass an extra variable “database name” while connecting to MySQL. The CREATE TABLE statement is used to create a table in MySQL. In this article, a table named “employees”, with four columns: “id”, “firstname”, “lastname” and “email” will be created. The data types that will be used are : VARCHAR:Holds a variable length string that can contain letters, numbers, and special characters. The maximum size is specified in parenthesis.INT :he INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer value between -2147483648 to 2147483647. VARCHAR:Holds a variable length string that can contain letters, numbers, and special characters. The maximum size is specified in parenthesis. INT :he INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer value between -2147483648 to 2147483647. The attributes that are used along with data types in this article are: NOT NULL: Each row must contain a value for that column, null values are not allowed.PRIMARY KEY: Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number. NOT NULL: Each row must contain a value for that column, null values are not allowed. PRIMARY KEY: Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number. Creating tables in three different versions are described below: Creating table using MySQLi Object-oriented ProcedureSyntax :<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; // checking connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // sql code to create table $sql = "CREATE TABLE employees( id INT(2) PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50) )"; if ($conn->query($sql) === TRUE) { echo "Table employees created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?> Output : <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; // checking connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // sql code to create table $sql = "CREATE TABLE employees( id INT(2) PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50) )"; if ($conn->query($sql) === TRUE) { echo "Table employees created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?> Output : Creating table using MySQLi Procedural procedureSyntax :<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; // Checking connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // sql code to create table $sql = "CREATE TABLE employees ( id INT(2) PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50) )"; if (mysqli_query($conn, $sql)) { echo "Table employees created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); } mysqli_close($conn); ?> Output : <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; // Checking connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // sql code to create table $sql = "CREATE TABLE employees ( id INT(2) PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50) )"; if (mysqli_query($conn, $sql)) { echo "Table employees created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); } mysqli_close($conn); ?> Output : Creating table using PDO procedureSyntax :<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // setting the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // sql code to create table $sql = "CREATE TABLE employees ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50) )"; // using exec() because no results are returned $conn->exec($sql); echo "Table employees created successfully"; } catch(PDOException $e) { echo $sql . "" . $e->getMessage(); } $conn = null; ?> Output :My Personal Notes arrow_drop_upSave <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "newDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // setting the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // sql code to create table $sql = "CREATE TABLE employees ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50) )"; // using exec() because no results are returned $conn->exec($sql); echo "Table employees created successfully"; } catch(PDOException $e) { echo $sql . "" . $e->getMessage(); } $conn = null; ?> Output : mysql PHP SQL Technical Scripter Web technologies Questions SQL PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? Comparing two dates in PHP SQL | DDL, DQL, DML, DCL and TCL Commands SQL | WITH clause How to find Nth highest salary from a table SQL | ALTER (RENAME) SQL Trigger | Student Database
[ { "code": null, "e": 24344, "s": 24316, "text": "\n21 Mar, 2018" }, { "code": null, "e": 24633, "s": 24344, "text": "What is a table?In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows." }, { "code": null, "e": 25056, "s": 24633, "text": "Creating a MySQL Table Using MySQLi and PDOWe have already learned about creating databases in MySQL from PHP in this article. The steps to create table are similar to creating databases. The difference is instead of creating a new database we will connect to existing database and create a table in that database. To connect to an existing database we can pass an extra variable “database name” while connecting to MySQL." }, { "code": null, "e": 25119, "s": 25056, "text": "The CREATE TABLE statement is used to create a table in MySQL." }, { "code": null, "e": 25241, "s": 25119, "text": "In this article, a table named “employees”, with four columns: “id”, “firstname”, “lastname” and “email” will be created." }, { "code": null, "e": 25280, "s": 25241, "text": "The data types that will be used are :" }, { "code": null, "e": 25566, "s": 25280, "text": "VARCHAR:Holds a variable length string that can contain letters, numbers, and special characters. The maximum size is specified in parenthesis.INT :he INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer value between -2147483648 to 2147483647." }, { "code": null, "e": 25710, "s": 25566, "text": "VARCHAR:Holds a variable length string that can contain letters, numbers, and special characters. The maximum size is specified in parenthesis." }, { "code": null, "e": 25853, "s": 25710, "text": "INT :he INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer value between -2147483648 to 2147483647." }, { "code": null, "e": 25925, "s": 25853, "text": "The attributes that are used along with data types in this article are:" }, { "code": null, "e": 26129, "s": 25925, "text": "NOT NULL: Each row must contain a value for that column, null values are not allowed.PRIMARY KEY: Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number." }, { "code": null, "e": 26215, "s": 26129, "text": "NOT NULL: Each row must contain a value for that column, null values are not allowed." }, { "code": null, "e": 26334, "s": 26215, "text": "PRIMARY KEY: Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number." }, { "code": null, "e": 26399, "s": 26334, "text": "Creating tables in three different versions are described below:" }, { "code": null, "e": 27139, "s": 26399, "text": "Creating table using MySQLi Object-oriented ProcedureSyntax :<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n$dbname = \"newDB\";\n\n// checking connection\n$conn = new mysqli($servername, $username, $password, $dbname);\n// Check connection\nif ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n}\n\n// sql code to create table\n$sql = \"CREATE TABLE employees(\n id INT(2) PRIMARY KEY, \n firstname VARCHAR(30) NOT NULL,\n lastname VARCHAR(30) NOT NULL,\n email VARCHAR(50)\n )\";\n\nif ($conn->query($sql) === TRUE) {\n echo \"Table employees created successfully\";\n} else {\n echo \"Error creating table: \" . $conn->error;\n}\n\n$conn->close();\n?>\nOutput :" }, { "code": null, "e": 27810, "s": 27139, "text": "<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n$dbname = \"newDB\";\n\n// checking connection\n$conn = new mysqli($servername, $username, $password, $dbname);\n// Check connection\nif ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n}\n\n// sql code to create table\n$sql = \"CREATE TABLE employees(\n id INT(2) PRIMARY KEY, \n firstname VARCHAR(30) NOT NULL,\n lastname VARCHAR(30) NOT NULL,\n email VARCHAR(50)\n )\";\n\nif ($conn->query($sql) === TRUE) {\n echo \"Table employees created successfully\";\n} else {\n echo \"Error creating table: \" . $conn->error;\n}\n\n$conn->close();\n?>\n" }, { "code": null, "e": 27819, "s": 27810, "text": "Output :" }, { "code": null, "e": 28556, "s": 27819, "text": "Creating table using MySQLi Procedural procedureSyntax :<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n$dbname = \"newDB\";\n\n// Checking connection\n$conn = mysqli_connect($servername, $username, $password, $dbname);\n// Check connection\nif (!$conn) {\n die(\"Connection failed: \" . mysqli_connect_error());\n}\n\n// sql code to create table\n$sql = \"CREATE TABLE employees (\n id INT(2) PRIMARY KEY, \n firstname VARCHAR(30) NOT NULL,\n lastname VARCHAR(30) NOT NULL,\n email VARCHAR(50)\n )\";\n\nif (mysqli_query($conn, $sql)) {\n echo \"Table employees created successfully\";\n} else {\n echo \"Error creating table: \" . mysqli_error($conn);\n}\nmysqli_close($conn);\n?>\nOutput :" }, { "code": null, "e": 29229, "s": 28556, "text": "<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n$dbname = \"newDB\";\n\n// Checking connection\n$conn = mysqli_connect($servername, $username, $password, $dbname);\n// Check connection\nif (!$conn) {\n die(\"Connection failed: \" . mysqli_connect_error());\n}\n\n// sql code to create table\n$sql = \"CREATE TABLE employees (\n id INT(2) PRIMARY KEY, \n firstname VARCHAR(30) NOT NULL,\n lastname VARCHAR(30) NOT NULL,\n email VARCHAR(50)\n )\";\n\nif (mysqli_query($conn, $sql)) {\n echo \"Table employees created successfully\";\n} else {\n echo \"Error creating table: \" . mysqli_error($conn);\n}\nmysqli_close($conn);\n?>\n" }, { "code": null, "e": 29238, "s": 29229, "text": "Output :" }, { "code": null, "e": 30175, "s": 29238, "text": "Creating table using PDO procedureSyntax :<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n$dbname = \"newDB\";\n\ntry {\n $conn = new PDO(\"mysql:host=$servername;dbname=$dbname\", \n $username, $password);\n \n \n // setting the PDO error mode to exception\n $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n // sql code to create table\n $sql = \"CREATE TABLE employees (\n id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, \n firstname VARCHAR(30) NOT NULL,\n lastname VARCHAR(30) NOT NULL,\n email VARCHAR(50)\n )\";\n\n // using exec() because no results are returned\n $conn->exec($sql);\n echo \"Table employees created successfully\";\n }\ncatch(PDOException $e)\n {\n echo $sql . \"\" . $e->getMessage();\n }\n\n$conn = null;\n?>\nOutput :My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31027, "s": 30175, "text": "<?php\n$servername = \"localhost\";\n$username = \"username\";\n$password = \"password\";\n$dbname = \"newDB\";\n\ntry {\n $conn = new PDO(\"mysql:host=$servername;dbname=$dbname\", \n $username, $password);\n \n \n // setting the PDO error mode to exception\n $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n // sql code to create table\n $sql = \"CREATE TABLE employees (\n id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, \n firstname VARCHAR(30) NOT NULL,\n lastname VARCHAR(30) NOT NULL,\n email VARCHAR(50)\n )\";\n\n // using exec() because no results are returned\n $conn->exec($sql);\n echo \"Table employees created successfully\";\n }\ncatch(PDOException $e)\n {\n echo $sql . \"\" . $e->getMessage();\n }\n\n$conn = null;\n?>\n" }, { "code": null, "e": 31036, "s": 31027, "text": "Output :" }, { "code": null, "e": 31042, "s": 31036, "text": "mysql" }, { "code": null, "e": 31046, "s": 31042, "text": "PHP" }, { "code": null, "e": 31050, "s": 31046, "text": "SQL" }, { "code": null, "e": 31069, "s": 31050, "text": "Technical Scripter" }, { "code": null, "e": 31096, "s": 31069, "text": "Web technologies Questions" }, { "code": null, "e": 31100, "s": 31096, "text": "SQL" }, { "code": null, "e": 31104, "s": 31100, "text": "PHP" }, { "code": null, "e": 31202, "s": 31104, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31252, "s": 31202, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 31292, "s": 31252, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 31353, "s": 31292, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 31403, "s": 31353, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 31430, "s": 31403, "text": "Comparing two dates in PHP" }, { "code": null, "e": 31472, "s": 31430, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 31490, "s": 31472, "text": "SQL | WITH clause" }, { "code": null, "e": 31534, "s": 31490, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 31555, "s": 31534, "text": "SQL | ALTER (RENAME)" } ]
Associative Arrays in PHP - GeeksforGeeks
31 Jul, 2021 Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained. Example:Here array() function is used to create associative array. <?php /* First method to create an associate array. */$student_one = array("Maths"=>95, "Physics"=>90, "Chemistry"=>96, "English"=>93, "Computer"=>98); /* Second method to create an associate array. */$student_two["Maths"] = 95; $student_two["Physics"] = 90; $student_two["Chemistry"] = 96; $student_two["English"] = 93; $student_two["Computer"] = 98; /* Accessing the elements directly */echo "Marks for student one is:\n"; echo "Maths:" . $student_two["Maths"], "\n"; echo "Physics:" . $student_two["Physics"], "\n"; echo "Chemistry:" . $student_two["Chemistry"], "\n"; echo "English:" . $student_one["English"], "\n"; echo "Computer:" . $student_one["Computer"], "\n"; ?> Marks for student one is: Maths:95 Physics:90 Chemistry:96 English:93 Computer:98 Traversing the Associative Array:We can traverse associative arrays using loops. We can loop through the associative array in two ways. First by using for loop and secondly by using foreach. Example:Here array_keys() function is used to find indices names given to them and count() function is used to count number of indices in associative arrays. <?php /* Creating an associative array */$student_one = array("Maths"=>95, "Physics"=>90, "Chemistry"=>96, "English"=>93, "Computer"=>98); /* Looping through an array using foreach */echo "Looping using foreach: \n"; foreach ($student_one as $subject => $marks){ echo "Student one got ".$marks." in ".$subject."\n"; } /* Looping through an array using for */echo "\nLooping using for: \n"; $subject = array_keys($student_one); $marks = count($student_one); for($i=0; $i < $marks; ++$i) { echo $subject[$i] . ' ' . $student_one[$subject[$i]] . "\n"; } ?> Looping using foreach: Student one got 95 in Maths Student one got 90 in Physics Student one got 96 in Chemistry Student one got 93 in English Student one got 98 in Computer Looping using for: Maths 95 Physics 90 Chemistry 96 English 93 Computer 98 Creating an associative array of mixed types <?php /* Creating an associative array of mixed types */$arr["xyz"] = 95; $arr[100] = "abc"; $arr[11.25] = 100; $arr["abc"] = "pqr"; /* Looping through an array using foreach */foreach ($arr as $key => $val){ echo $key."==>".$val."\n"; } ?> xyz==>95 100==>abc 11==>100 abc==>pqr PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. PHP-array Picked PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? How to run JavaScript from PHP? Download file from URL using PHP Split a comma delimited string into an array in PHP How to fetch data from localserver database and display on HTML table using PHP ? How to Encrypt and Decrypt a PHP String ? How to declare a global variable in PHP? How to get parameters from a URL string in PHP?
[ { "code": null, "e": 24452, "s": 24424, "text": "\n31 Jul, 2021" }, { "code": null, "e": 24788, "s": 24452, "text": "Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained." }, { "code": null, "e": 24855, "s": 24788, "text": "Example:Here array() function is used to create associative array." }, { "code": "<?php /* First method to create an associate array. */$student_one = array(\"Maths\"=>95, \"Physics\"=>90, \"Chemistry\"=>96, \"English\"=>93, \"Computer\"=>98); /* Second method to create an associate array. */$student_two[\"Maths\"] = 95; $student_two[\"Physics\"] = 90; $student_two[\"Chemistry\"] = 96; $student_two[\"English\"] = 93; $student_two[\"Computer\"] = 98; /* Accessing the elements directly */echo \"Marks for student one is:\\n\"; echo \"Maths:\" . $student_two[\"Maths\"], \"\\n\"; echo \"Physics:\" . $student_two[\"Physics\"], \"\\n\"; echo \"Chemistry:\" . $student_two[\"Chemistry\"], \"\\n\"; echo \"English:\" . $student_one[\"English\"], \"\\n\"; echo \"Computer:\" . $student_one[\"Computer\"], \"\\n\"; ?> ", "e": 25579, "s": 24855, "text": null }, { "code": null, "e": 25662, "s": 25579, "text": "Marks for student one is:\nMaths:95\nPhysics:90\nChemistry:96\nEnglish:93\nComputer:98\n" }, { "code": null, "e": 25853, "s": 25662, "text": "Traversing the Associative Array:We can traverse associative arrays using loops. We can loop through the associative array in two ways. First by using for loop and secondly by using foreach." }, { "code": null, "e": 26011, "s": 25853, "text": "Example:Here array_keys() function is used to find indices names given to them and count() function is used to count number of indices in associative arrays." }, { "code": "<?php /* Creating an associative array */$student_one = array(\"Maths\"=>95, \"Physics\"=>90, \"Chemistry\"=>96, \"English\"=>93, \"Computer\"=>98); /* Looping through an array using foreach */echo \"Looping using foreach: \\n\"; foreach ($student_one as $subject => $marks){ echo \"Student one got \".$marks.\" in \".$subject.\"\\n\"; } /* Looping through an array using for */echo \"\\nLooping using for: \\n\"; $subject = array_keys($student_one); $marks = count($student_one); for($i=0; $i < $marks; ++$i) { echo $subject[$i] . ' ' . $student_one[$subject[$i]] . \"\\n\"; } ?> ", "e": 26633, "s": 26011, "text": null }, { "code": null, "e": 26886, "s": 26633, "text": "Looping using foreach: \nStudent one got 95 in Maths\nStudent one got 90 in Physics\nStudent one got 96 in Chemistry\nStudent one got 93 in English\nStudent one got 98 in Computer\n\nLooping using for: \nMaths 95\nPhysics 90\nChemistry 96\nEnglish 93\nComputer 98\n" }, { "code": null, "e": 26931, "s": 26886, "text": "Creating an associative array of mixed types" }, { "code": "<?php /* Creating an associative array of mixed types */$arr[\"xyz\"] = 95; $arr[100] = \"abc\"; $arr[11.25] = 100; $arr[\"abc\"] = \"pqr\"; /* Looping through an array using foreach */foreach ($arr as $key => $val){ echo $key.\"==>\".$val.\"\\n\"; } ?> ", "e": 27184, "s": 26931, "text": null }, { "code": null, "e": 27223, "s": 27184, "text": "xyz==>95\n100==>abc\n11==>100\nabc==>pqr\n" }, { "code": null, "e": 27392, "s": 27223, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 27402, "s": 27392, "text": "PHP-array" }, { "code": null, "e": 27409, "s": 27402, "text": "Picked" }, { "code": null, "e": 27413, "s": 27409, "text": "PHP" }, { "code": null, "e": 27417, "s": 27413, "text": "PHP" }, { "code": null, "e": 27515, "s": 27417, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27555, "s": 27515, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27600, "s": 27555, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27642, "s": 27600, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27674, "s": 27642, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 27707, "s": 27674, "text": "Download file from URL using PHP" }, { "code": null, "e": 27759, "s": 27707, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 27841, "s": 27759, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27883, "s": 27841, "text": "How to Encrypt and Decrypt a PHP String ?" }, { "code": null, "e": 27924, "s": 27883, "text": "How to declare a global variable in PHP?" } ]
How to create Animated Blur Navbar using CSS? - GeeksforGeeks
30 Sep, 2021 The Navbar is the main component of any website through which the user can navigate through all the components and sections of a site. That’s why it is really important to have a well-designed navigation bar or menu. So today we will be looking at a navbar in which all the elements get blur except the hovered-element. Approach: The approach is to use blur() function and hover selector to blur all the elements except the hovered one. HTML Code: Here, we have created a simple unordered list with 3 list-items. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Blurred Menu Design</title></head><body> <ul> <li>Home</li> <li>About</li> <li>Contact Us</li> </ul></body></html> CSS Code: For CSS, follow these steps. First we have applied some background and align over unordered list in the form of a navbar using flexbox. Then we have used hover on ul with blur of 2 px which makes every list-item blur when we hover on ul. Now we have used hover on li with blur set as 0 to unblur the hovered list-item. Now, for those who don’t get the concept of it try to visualize two boxes. The smaller one representing li which is wrapped inside the bigger box which is representing ul. Now our first hover selection on ul makes the whole of the li blur as we haven’t till enter the smaller box boundary and as we enter the boundary of the smaller box we activate the hover selection of li which makes the hovered list-item unblurred. CSS body{ background: green; font-family:Arial, Helvetica, sans-serif; } ul{ position: absolute; top:40%; left:40%; display: flex; } ul li{ list-style: none; position: relative; display: block; margin: 10px;}ul:hover li{ opacity: .2; filter: blur(2px);} ul li:hover{ opacity: 1; filter:blur(0px);} Complete Code: It is the combination of the above two codes. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Blured Menu Design</title><style> body{ background: green; font-family:Arial, Helvetica, sans-serif; } ul{ position: absolute; top:40%; left:40%; display: flex; } ul li{ list-style: none; position: relative; display: block; margin: 10px;}ul:hover li{ opacity: .2; filter: blur(2px);} ul li:hover{ opacity: 1; filter:blur(0px);} </style> </head><body> <ul> <li>Home</li> <li>About</li> <li>Contact Us</li> </ul></body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 CSS-Functions CSS-Misc CSS-Selectors CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24984, "s": 24956, "text": "\n30 Sep, 2021" }, { "code": null, "e": 25304, "s": 24984, "text": "The Navbar is the main component of any website through which the user can navigate through all the components and sections of a site. That’s why it is really important to have a well-designed navigation bar or menu. So today we will be looking at a navbar in which all the elements get blur except the hovered-element." }, { "code": null, "e": 25421, "s": 25304, "text": "Approach: The approach is to use blur() function and hover selector to blur all the elements except the hovered one." }, { "code": null, "e": 25497, "s": 25421, "text": "HTML Code: Here, we have created a simple unordered list with 3 list-items." }, { "code": null, "e": 25502, "s": 25497, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Blurred Menu Design</title></head><body> <ul> <li>Home</li> <li>About</li> <li>Contact Us</li> </ul></body></html>", "e": 25801, "s": 25502, "text": null }, { "code": null, "e": 25840, "s": 25801, "text": "CSS Code: For CSS, follow these steps." }, { "code": null, "e": 25947, "s": 25840, "text": "First we have applied some background and align over unordered list in the form of a navbar using flexbox." }, { "code": null, "e": 26049, "s": 25947, "text": "Then we have used hover on ul with blur of 2 px which makes every list-item blur when we hover on ul." }, { "code": null, "e": 26130, "s": 26049, "text": "Now we have used hover on li with blur set as 0 to unblur the hovered list-item." }, { "code": null, "e": 26550, "s": 26130, "text": "Now, for those who don’t get the concept of it try to visualize two boxes. The smaller one representing li which is wrapped inside the bigger box which is representing ul. Now our first hover selection on ul makes the whole of the li blur as we haven’t till enter the smaller box boundary and as we enter the boundary of the smaller box we activate the hover selection of li which makes the hovered list-item unblurred." }, { "code": null, "e": 26554, "s": 26550, "text": "CSS" }, { "code": "body{ background: green; font-family:Arial, Helvetica, sans-serif; } ul{ position: absolute; top:40%; left:40%; display: flex; } ul li{ list-style: none; position: relative; display: block; margin: 10px;}ul:hover li{ opacity: .2; filter: blur(2px);} ul li:hover{ opacity: 1; filter:blur(0px);}", "e": 26907, "s": 26554, "text": null }, { "code": null, "e": 26968, "s": 26907, "text": "Complete Code: It is the combination of the above two codes." }, { "code": null, "e": 26973, "s": 26968, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Blured Menu Design</title><style> body{ background: green; font-family:Arial, Helvetica, sans-serif; } ul{ position: absolute; top:40%; left:40%; display: flex; } ul li{ list-style: none; position: relative; display: block; margin: 10px;}ul:hover li{ opacity: .2; filter: blur(2px);} ul li:hover{ opacity: 1; filter:blur(0px);} </style> </head><body> <ul> <li>Home</li> <li>About</li> <li>Contact Us</li> </ul></body></html>", "e": 27648, "s": 26973, "text": null }, { "code": null, "e": 27656, "s": 27648, "text": "Output:" }, { "code": null, "e": 27795, "s": 27658, "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": 27812, "s": 27795, "text": "arorakashish0911" }, { "code": null, "e": 27826, "s": 27812, "text": "CSS-Functions" }, { "code": null, "e": 27835, "s": 27826, "text": "CSS-Misc" }, { "code": null, "e": 27849, "s": 27835, "text": "CSS-Selectors" }, { "code": null, "e": 27853, "s": 27849, "text": "CSS" }, { "code": null, "e": 27858, "s": 27853, "text": "HTML" }, { "code": null, "e": 27875, "s": 27858, "text": "Web Technologies" }, { "code": null, "e": 27880, "s": 27875, "text": "HTML" }, { "code": null, "e": 27978, "s": 27880, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28036, "s": 27978, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28073, "s": 28036, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28137, "s": 28073, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28178, "s": 28137, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28215, "s": 28178, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28275, "s": 28215, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28336, "s": 28275, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28389, "s": 28336, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28439, "s": 28389, "text": "How to Insert Form Data into Database using PHP ?" } ]
How to calculate population variance in R?
There is no function in R to calculate the population variance but we can use the population size and sample variance to find it. We know that the divisor in population variance is the population size and if we multiply the output of var(it calculates sample variance) function with (population size – 1)/population size then the output will be population variance. Live Demo set.seed(141) x1<-1:100 Sample_Variance<-var(x1) Sample_Variance [1] 841.6667 Population_Variance<-var(x1)*(99/100) Population_Variance [1] 833.25 Live Demo x2<-rnorm(500) Sample_Variance<-var(x2) Sample_Variance [1] 1.013514 Population_Variance<-var(x2)*(499/500) Population_Variance [1] 1.011487 Live Demo x3<-round(rnorm(500),0) Sample_Variance<-var(x3) Sample_Variance [1] 1.088401 Population_Variance<-var(x3)*(499/500) Population_Variance [1] 1.086224 Live Demo x4<-rpois(150,10) x4 [1] 15 13 11 4 10 9 13 12 8 12 7 13 10 18 8 11 15 8 9 14 7 14 8 11 7 [26] 6 10 12 7 15 13 12 13 11 9 7 15 11 17 10 17 11 9 10 17 11 4 11 11 9 [51] 11 10 11 10 16 11 6 4 9 5 5 6 6 6 10 10 10 13 10 6 10 9 7 11 13 [76] 12 7 5 10 7 7 10 7 10 10 14 11 11 9 6 13 9 5 11 13 11 10 10 6 15 [101] 7 12 7 9 13 6 9 13 13 11 11 16 5 12 14 10 10 10 13 7 4 16 6 13 6 [126] 4 9 7 9 7 8 12 12 10 10 9 8 4 10 8 9 7 13 7 11 9 8 8 10 12 Sample_Variance<-var(x4) Sample_Variance [1] 10.86694 Population_Variance<-var(x4)*(149/150) Population_Variance [1] 10.79449 Live Demo x5<-sample(1:100,120,replace=TRUE) x5 [1] 62 59 25 15 16 17 69 22 81 90 91 68 61 40 61 48 33 71 60 11 1 15 95 17 81 [26] 29 16 44 47 26 20 56 97 74 3 5 44 77 50 44 83 54 37 54 73 46 99 19 85 28 [51] 8 49 15 80 65 50 85 7 91 76 83 93 54 95 52 8 20 18 70 12 66 36 2 99 81 [76] 13 91 11 73 19 2 73 20 12 80 41 38 20 61 64 39 30 65 28 25 38 56 61 44 32 [101] 66 76 2 72 36 78 48 41 52 17 31 69 33 74 39 60 29 59 72 11 Sample_Variance<-var(x5) Sample_Variance [1] 892.7361 Population_Variance<-var(x5)*(119/120) Population_Variance [1] 885.2966 Live Demo x6<--sample(101:999,120) x6 [1] -919 -502 -343 -523 -867 -405 -368 -447 -286 -578 -147 -665 -823 -598 -260 [16] -740 -569 -661 -386 -267 -185 -114 -608 -711 -638 -992 -552 -795 -291 -152 [31] -154 -211 -721 -388 -283 -234 -525 -942 -599 -176 -239 -788 -579 -875 -883 [46] -856 -143 -304 -407 -448 -717 -524 -273 -235 -167 -158 -659 -432 -803 -624 [61] -187 -312 -225 -802 -439 -453 -637 -571 -768 -664 -473 -331 -806 -265 -173 [76] -748 -623 -671 -989 -888 -950 -589 -487 -526 -668 -760 -414 -622 -248 -276 [91] -139 -951 -630 -885 -440 -191 -491 -685 -653 -132 -742 -477 -181 -505 -759 [106] -974 -741 -548 -593 -240 -527 -914 -402 -127 -860 -336 -333 -794 -891 -311 Sample_Variance<-var(x6) Sample_Variance [1] 62657.78 Population_Variance<-var(x6)*(119/120) Population_Variance [1] 62135.63 Live Demo x7<-rexp(50,3.5) x7 [1] 0.205216964 0.133222130 0.488146733 0.244428905 0.833206350 0.069545948 [7] 0.195504191 0.539364253 1.099099582 1.835459402 0.170821138 0.342813864 [13] 0.108211014 0.392889843 0.069053900 0.083381383 0.282172880 1.299693448 [19] 0.033847926 0.248126373 0.537849065 0.508127648 0.148564885 0.047607303 [25] 0.247224701 0.171349073 0.089745700 0.157843010 0.870047906 0.790377494 [31] 0.285218089 0.107768506 0.806453962 0.565196530 0.283891426 0.129423319 [37] 0.116770751 0.238833628 0.379741206 0.009492331 0.343673059 0.072587659 [43] 0.076498866 0.504828741 0.313257385 0.427818704 0.372741859 0.210799536 [49] 0.155322546 0.504289020 Sample_Variance<-var(x7) Sample_Variance [1] 0.03401862 Population_Variance<-var(x7)*(49/50) Population_Variance [1] 0.03333825
[ { "code": null, "e": 1428, "s": 1062, "text": "There is no function in R to calculate the population variance but we can use the population size and sample variance to find it. We know that the divisor in population variance is the population size and if we multiply the output of var(it calculates sample variance) function with (population size – 1)/population size then the output will be population variance." }, { "code": null, "e": 1439, "s": 1428, "text": " Live Demo" }, { "code": null, "e": 1504, "s": 1439, "text": "set.seed(141)\nx1<-1:100\nSample_Variance<-var(x1)\nSample_Variance" }, { "code": null, "e": 1517, "s": 1504, "text": "[1] 841.6667" }, { "code": null, "e": 1575, "s": 1517, "text": "Population_Variance<-var(x1)*(99/100)\nPopulation_Variance" }, { "code": null, "e": 1586, "s": 1575, "text": "[1] 833.25" }, { "code": null, "e": 1597, "s": 1586, "text": " Live Demo" }, { "code": null, "e": 1653, "s": 1597, "text": "x2<-rnorm(500)\nSample_Variance<-var(x2)\nSample_Variance" }, { "code": null, "e": 1666, "s": 1653, "text": "[1] 1.013514" }, { "code": null, "e": 1725, "s": 1666, "text": "Population_Variance<-var(x2)*(499/500)\nPopulation_Variance" }, { "code": null, "e": 1738, "s": 1725, "text": "[1] 1.011487" }, { "code": null, "e": 1749, "s": 1738, "text": " Live Demo" }, { "code": null, "e": 1814, "s": 1749, "text": "x3<-round(rnorm(500),0) Sample_Variance<-var(x3)\nSample_Variance" }, { "code": null, "e": 1827, "s": 1814, "text": "[1] 1.088401" }, { "code": null, "e": 1886, "s": 1827, "text": "Population_Variance<-var(x3)*(499/500)\nPopulation_Variance" }, { "code": null, "e": 1899, "s": 1886, "text": "[1] 1.086224" }, { "code": null, "e": 1910, "s": 1899, "text": " Live Demo" }, { "code": null, "e": 1931, "s": 1910, "text": "x4<-rpois(150,10)\nx4" }, { "code": null, "e": 2348, "s": 1931, "text": "[1] 15 13 11 4 10 9 13 12 8 12 7 13 10 18 8 11 15 8 9 14 7 14 8 11 7\n[26] 6 10 12 7 15 13 12 13 11 9 7 15 11 17 10 17 11 9 10 17 11 4 11 11 9\n[51] 11 10 11 10 16 11 6 4 9 5 5 6 6 6 10 10 10 13 10 6 10 9 7 11 13\n[76] 12 7 5 10 7 7 10 7 10 10 14 11 11 9 6 13 9 5 11 13 11 10 10 6 15\n[101] 7 12 7 9 13 6 9 13 13 11 11 16 5 12 14 10 10 10 13 7 4 16 6 13 6\n[126] 4 9 7 9 7 8 12 12 10 10 9 8 4 10 8 9 7 13 7 11 9 8 8 10 12" }, { "code": null, "e": 2389, "s": 2348, "text": "Sample_Variance<-var(x4)\nSample_Variance" }, { "code": null, "e": 2402, "s": 2389, "text": "[1] 10.86694" }, { "code": null, "e": 2462, "s": 2402, "text": "Population_Variance<-var(x4)*(149/150)\n Population_Variance" }, { "code": null, "e": 2475, "s": 2462, "text": "[1] 10.79449" }, { "code": null, "e": 2486, "s": 2475, "text": " Live Demo" }, { "code": null, "e": 2524, "s": 2486, "text": "x5<-sample(1:100,120,replace=TRUE)\nx5" }, { "code": null, "e": 2900, "s": 2524, "text": "[1] 62 59 25 15 16 17 69 22 81 90 91 68 61 40 61 48 33 71 60 11 1 15 95 17 81\n[26] 29 16 44 47 26 20 56 97 74 3 5 44 77 50 44 83 54 37 54 73 46 99 19 85 28\n[51] 8 49 15 80 65 50 85 7 91 76 83 93 54 95 52 8 20 18 70 12 66 36 2 99 81\n[76] 13 91 11 73 19 2 73 20 12 80 41 38 20 61 64 39 30 65 28 25 38 56 61 44 32\n[101] 66 76 2 72 36 78 48 41 52 17 31 69 33 74 39 60 29 59 72 11" }, { "code": null, "e": 2941, "s": 2900, "text": "Sample_Variance<-var(x5)\nSample_Variance" }, { "code": null, "e": 2954, "s": 2941, "text": "[1] 892.7361" }, { "code": null, "e": 3013, "s": 2954, "text": "Population_Variance<-var(x5)*(119/120)\nPopulation_Variance" }, { "code": null, "e": 3026, "s": 3013, "text": "[1] 885.2966" }, { "code": null, "e": 3037, "s": 3026, "text": " Live Demo" }, { "code": null, "e": 3065, "s": 3037, "text": "x6<--sample(101:999,120)\nx6" }, { "code": null, "e": 3705, "s": 3065, "text": "[1] -919 -502 -343 -523 -867 -405 -368 -447 -286 -578 -147 -665 -823 -598 -260\n[16] -740 -569 -661 -386 -267 -185 -114 -608 -711 -638 -992 -552 -795 -291 -152\n[31] -154 -211 -721 -388 -283 -234 -525 -942 -599 -176 -239 -788 -579 -875 -883\n[46] -856 -143 -304 -407 -448 -717 -524 -273 -235 -167 -158 -659 -432 -803 -624\n[61] -187 -312 -225 -802 -439 -453 -637 -571 -768 -664 -473 -331 -806 -265 -173\n[76] -748 -623 -671 -989 -888 -950 -589 -487 -526 -668 -760 -414 -622 -248 -276\n[91] -139 -951 -630 -885 -440 -191 -491 -685 -653 -132 -742 -477 -181 -505 -759\n[106] -974 -741 -548 -593 -240 -527 -914 -402 -127 -860 -336 -333 -794 -891 -311" }, { "code": null, "e": 3746, "s": 3705, "text": "Sample_Variance<-var(x6)\nSample_Variance" }, { "code": null, "e": 3759, "s": 3746, "text": "[1] 62657.78" }, { "code": null, "e": 3818, "s": 3759, "text": "Population_Variance<-var(x6)*(119/120)\nPopulation_Variance" }, { "code": null, "e": 3831, "s": 3818, "text": "[1] 62135.63" }, { "code": null, "e": 3842, "s": 3831, "text": " Live Demo" }, { "code": null, "e": 3862, "s": 3842, "text": "x7<-rexp(50,3.5)\nx7" }, { "code": null, "e": 4505, "s": 3862, "text": "[1] 0.205216964 0.133222130 0.488146733 0.244428905 0.833206350 0.069545948\n[7] 0.195504191 0.539364253 1.099099582 1.835459402 0.170821138 0.342813864\n[13] 0.108211014 0.392889843 0.069053900 0.083381383 0.282172880 1.299693448\n[19] 0.033847926 0.248126373 0.537849065 0.508127648 0.148564885 0.047607303\n[25] 0.247224701 0.171349073 0.089745700 0.157843010 0.870047906 0.790377494\n[31] 0.285218089 0.107768506 0.806453962 0.565196530 0.283891426 0.129423319\n[37] 0.116770751 0.238833628 0.379741206 0.009492331 0.343673059 0.072587659\n[43] 0.076498866 0.504828741 0.313257385 0.427818704 0.372741859 0.210799536\n[49] 0.155322546 0.504289020" }, { "code": null, "e": 4546, "s": 4505, "text": "Sample_Variance<-var(x7)\nSample_Variance" }, { "code": null, "e": 4561, "s": 4546, "text": "[1] 0.03401862" }, { "code": null, "e": 4618, "s": 4561, "text": "Population_Variance<-var(x7)*(49/50)\nPopulation_Variance" }, { "code": null, "e": 4633, "s": 4618, "text": "[1] 0.03333825" } ]
Check if X can give change to every person in the Queue - GeeksforGeeks
27 May, 2021 Given an array of N integers where Ai denotes the currency of note that the i-th person has. The possible currencies are 5, 10, and 20. All the N people are standing in a queue waiting to buy an ice cream from X which costs Rs 5. Initially, X has an initial balance of 0. Check if X will be able to provide change for all people who are waiting to buy ice cream. Examples: Input:a[] = {5, 5, 5, 10, 20} Output: YES When the fourth person comes to buy an ice-cream, X has three Rs 5 change, hence X gives him 1, and now when the fifth person comes to buy the ice-cream, X has two Rs 5 and one Rs 10 note, hence he gives him one Rs 10 and one Rs 5 note. Input: a[] = {5, 10, 10, 20} Output: NO The approach is to keep track of the number of Rs 5 and Rs 10 currencies. Rs 20 currencies will not be used since it is the highest currency that a person can give and thus it cannot be given as a change. Initialize two variables to count Rs 5(fiveCount) and Rs 10(tenCount). If the person has a Rs 10 currency and fiveCount > 0, then decrease fiveCount and increase tenCount. If X does not have Rs 5, then X cannot give the person the required change. If the person has 5$ note, increase fiveCount by one. If the person has Rs 20, then three conditions will be: If fiveCount > 0 and tencount > 0, decrease both. Else if, fiveCount >= 3, decrease fivecount by three. Else, return false. If all the person in the queue gets the change, then print “YES” else print “NO”. Below is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program to check whether X can give change// to every person in the Queue#include <bits/stdc++.h>using namespace std; // Function to check if every person will// get the change from Xint isChangeable(int notes[], int n){ // To count the 5$ and 10& notes int fiveCount = 0; int tenCount = 0; // Serve the customer in order for (int i = 0; i < n; i++) { // Increase the number of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1;}// Driver Codeint main(){ // queue of customers with available notes. int a[] = { 5, 5, 5, 10, 20 }; int n = sizeof(a) / sizeof(a[0]); // Calling function if (isChangeable(a, n)) cout << "YES"; else cout << "NO"; return 0;} // Java program to check// whether X can give// change to every person// in the Queueimport java.io.*; class GFG{ // Function to check if// every person will// get the change from Xstatic int isChangeable(int notes[], int n){ // To count the 5$ // and 10& notes int fiveCount = 0; int tenCount = 0; // Serve the customer // in order for (int i = 0; i < n; i++) { // Increase the number // of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number // of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and // 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ // note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1;} // Driver Codepublic static void main (String[] args){ // queue of customers// with available notes.int a[] = {5, 5, 5, 10, 20};int n = a.length; // Calling functionif (isChangeable(a, n) > 0) System.out.print("YES");else System.out.print("NO");}} // This code is contributed// by anuj_67. # Python program to check whether X can# give change to every person in the Queue # Function to check if every person# will get the change from Xdef isChangeable(notes, n): # To count the 5$ and 10& notes fiveCount = 0 tenCount = 0 # Serve the customer in order for i in range(n): # Increase the number of 5$ note by one if (notes[i] == 5): fiveCount += 1 elif(notes[i] == 10): # decrease the number of note 5$ # and increase 10$ note by one if (fiveCount > 0): fiveCount -= 1 tenCount += 1 else: return 0 else: # decrease 5$ and 10$ note by one if (fiveCount > 0 and tenCount > 0): fiveCount -= 1 tenCount -= 1 # decrease 5$ note by three elif (fiveCount >= 3): fiveCount -= 3 else: return 0 return 1 # Driver Code # queue of customers with available notes.a = [5, 5, 5, 10, 20 ]n = len(a) # Calling functionif (isChangeable(a, n)): print("YES")else: print("NO") # This code is contributed by PrinciRaj1992 // C# program to check// whether X can give// change to every person// in the Queueusing System; class GFG{ // Function to check if// every person will// get the change from Xstatic int isChangeable(int []notes, int n){ // To count the 5$ // and 10& notes int fiveCount = 0; int tenCount = 0; // Serve the customer // in order for (int i = 0; i < n; i++) { // Increase the number // of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number // of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and // 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ // note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1;} // Driver Codepublic static void Main (){ // queue of customers// with available notes.int []a = {5, 5, 5, 10, 20};int n = a.Length; // Calling functionif (isChangeable(a, n) > 0) Console.WriteLine("YES");else Console.WriteLine("NO");}} // This code is contributed// by anuj_67. <script> // Javascript program to check // whether X can give // change to every person // in the Queue // Function to check if // every person will // get the change from X function isChangeable(notes, n) { // To count the 5$ // and 10& notes let fiveCount = 0; let tenCount = 0; // Serve the customer // in order for (let i = 0; i < n; i++) { // Increase the number // of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number // of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and // 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ // note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1; } // queue of customers // with available notes. let a = [5, 5, 5, 10, 20]; let n = a.length; // Calling function if (isChangeable(a, n) > 0) document.write("YES"); else document.write("NO"); </script> YES YouTubeGeeksforGeeks501K subscribersCheck if X can give change to every person in the Queue | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9Mx_FqPLrI0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> vt_m prasad gujar princiraj1992 suresh07 Amazon Constructive Algorithms C++ Amazon CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Iterators in C++ STL Sorting a vector in C++ Convert string to char array in C++ Inline Functions in C++ List in C++ Standard Template Library (STL) new and delete operators in C++ for dynamic memory Destructors in C++
[ { "code": null, "e": 24122, "s": 24094, "text": "\n27 May, 2021" }, { "code": null, "e": 24485, "s": 24122, "text": "Given an array of N integers where Ai denotes the currency of note that the i-th person has. The possible currencies are 5, 10, and 20. All the N people are standing in a queue waiting to buy an ice cream from X which costs Rs 5. Initially, X has an initial balance of 0. Check if X will be able to provide change for all people who are waiting to buy ice cream." }, { "code": null, "e": 24497, "s": 24485, "text": "Examples: " }, { "code": null, "e": 24777, "s": 24497, "text": "Input:a[] = {5, 5, 5, 10, 20} Output: YES When the fourth person comes to buy an ice-cream, X has three Rs 5 change, hence X gives him 1, and now when the fifth person comes to buy the ice-cream, X has two Rs 5 and one Rs 10 note, hence he gives him one Rs 10 and one Rs 5 note. " }, { "code": null, "e": 24818, "s": 24777, "text": "Input: a[] = {5, 10, 10, 20} Output: NO " }, { "code": null, "e": 25383, "s": 24818, "text": "The approach is to keep track of the number of Rs 5 and Rs 10 currencies. Rs 20 currencies will not be used since it is the highest currency that a person can give and thus it cannot be given as a change. Initialize two variables to count Rs 5(fiveCount) and Rs 10(tenCount). If the person has a Rs 10 currency and fiveCount > 0, then decrease fiveCount and increase tenCount. If X does not have Rs 5, then X cannot give the person the required change. If the person has 5$ note, increase fiveCount by one. If the person has Rs 20, then three conditions will be: " }, { "code": null, "e": 25433, "s": 25383, "text": "If fiveCount > 0 and tencount > 0, decrease both." }, { "code": null, "e": 25487, "s": 25433, "text": "Else if, fiveCount >= 3, decrease fivecount by three." }, { "code": null, "e": 25507, "s": 25487, "text": "Else, return false." }, { "code": null, "e": 25590, "s": 25507, "text": "If all the person in the queue gets the change, then print “YES” else print “NO”. " }, { "code": null, "e": 25639, "s": 25590, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 25643, "s": 25639, "text": "C++" }, { "code": null, "e": 25648, "s": 25643, "text": "Java" }, { "code": null, "e": 25656, "s": 25648, "text": "Python3" }, { "code": null, "e": 25659, "s": 25656, "text": "C#" }, { "code": null, "e": 25670, "s": 25659, "text": "Javascript" }, { "code": "// C++ program to check whether X can give change// to every person in the Queue#include <bits/stdc++.h>using namespace std; // Function to check if every person will// get the change from Xint isChangeable(int notes[], int n){ // To count the 5$ and 10& notes int fiveCount = 0; int tenCount = 0; // Serve the customer in order for (int i = 0; i < n; i++) { // Increase the number of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1;}// Driver Codeint main(){ // queue of customers with available notes. int a[] = { 5, 5, 5, 10, 20 }; int n = sizeof(a) / sizeof(a[0]); // Calling function if (isChangeable(a, n)) cout << \"YES\"; else cout << \"NO\"; return 0;}", "e": 27047, "s": 25670, "text": null }, { "code": "// Java program to check// whether X can give// change to every person// in the Queueimport java.io.*; class GFG{ // Function to check if// every person will// get the change from Xstatic int isChangeable(int notes[], int n){ // To count the 5$ // and 10& notes int fiveCount = 0; int tenCount = 0; // Serve the customer // in order for (int i = 0; i < n; i++) { // Increase the number // of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number // of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and // 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ // note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1;} // Driver Codepublic static void main (String[] args){ // queue of customers// with available notes.int a[] = {5, 5, 5, 10, 20};int n = a.length; // Calling functionif (isChangeable(a, n) > 0) System.out.print(\"YES\");else System.out.print(\"NO\");}} // This code is contributed// by anuj_67.", "e": 28618, "s": 27047, "text": null }, { "code": "# Python program to check whether X can# give change to every person in the Queue # Function to check if every person# will get the change from Xdef isChangeable(notes, n): # To count the 5$ and 10& notes fiveCount = 0 tenCount = 0 # Serve the customer in order for i in range(n): # Increase the number of 5$ note by one if (notes[i] == 5): fiveCount += 1 elif(notes[i] == 10): # decrease the number of note 5$ # and increase 10$ note by one if (fiveCount > 0): fiveCount -= 1 tenCount += 1 else: return 0 else: # decrease 5$ and 10$ note by one if (fiveCount > 0 and tenCount > 0): fiveCount -= 1 tenCount -= 1 # decrease 5$ note by three elif (fiveCount >= 3): fiveCount -= 3 else: return 0 return 1 # Driver Code # queue of customers with available notes.a = [5, 5, 5, 10, 20 ]n = len(a) # Calling functionif (isChangeable(a, n)): print(\"YES\")else: print(\"NO\") # This code is contributed by PrinciRaj1992", "e": 29855, "s": 28618, "text": null }, { "code": "// C# program to check// whether X can give// change to every person// in the Queueusing System; class GFG{ // Function to check if// every person will// get the change from Xstatic int isChangeable(int []notes, int n){ // To count the 5$ // and 10& notes int fiveCount = 0; int tenCount = 0; // Serve the customer // in order for (int i = 0; i < n; i++) { // Increase the number // of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number // of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and // 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ // note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1;} // Driver Codepublic static void Main (){ // queue of customers// with available notes.int []a = {5, 5, 5, 10, 20};int n = a.Length; // Calling functionif (isChangeable(a, n) > 0) Console.WriteLine(\"YES\");else Console.WriteLine(\"NO\");}} // This code is contributed// by anuj_67.", "e": 31409, "s": 29855, "text": null }, { "code": "<script> // Javascript program to check // whether X can give // change to every person // in the Queue // Function to check if // every person will // get the change from X function isChangeable(notes, n) { // To count the 5$ // and 10& notes let fiveCount = 0; let tenCount = 0; // Serve the customer // in order for (let i = 0; i < n; i++) { // Increase the number // of 5$ note by one if (notes[i] == 5) fiveCount++; else if (notes[i] == 10) { // decrease the number // of note 5$ and // increase 10$ note by one if (fiveCount > 0) { fiveCount--; tenCount++; } else return 0; } else { // decrease 5$ and // 10$ note by one if (fiveCount > 0 && tenCount > 0) { fiveCount--; tenCount--; } // decrease 5$ // note by three else if (fiveCount >= 3) { fiveCount -= 3; } else return 0; } } return 1; } // queue of customers // with available notes. let a = [5, 5, 5, 10, 20]; let n = a.length; // Calling function if (isChangeable(a, n) > 0) document.write(\"YES\"); else document.write(\"NO\"); </script>", "e": 33100, "s": 31409, "text": null }, { "code": null, "e": 33104, "s": 33100, "text": "YES" }, { "code": null, "e": 33960, "s": 33106, "text": "YouTubeGeeksforGeeks501K subscribersCheck if X can give change to every person in the Queue | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:15•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9Mx_FqPLrI0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 33965, "s": 33960, "text": "vt_m" }, { "code": null, "e": 33978, "s": 33965, "text": "prasad gujar" }, { "code": null, "e": 33992, "s": 33978, "text": "princiraj1992" }, { "code": null, "e": 34001, "s": 33992, "text": "suresh07" }, { "code": null, "e": 34008, "s": 34001, "text": "Amazon" }, { "code": null, "e": 34032, "s": 34008, "text": "Constructive Algorithms" }, { "code": null, "e": 34036, "s": 34032, "text": "C++" }, { "code": null, "e": 34043, "s": 34036, "text": "Amazon" }, { "code": null, "e": 34047, "s": 34043, "text": "CPP" }, { "code": null, "e": 34145, "s": 34047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34154, "s": 34145, "text": "Comments" }, { "code": null, "e": 34167, "s": 34154, "text": "Old Comments" }, { "code": null, "e": 34195, "s": 34167, "text": "Operator Overloading in C++" }, { "code": null, "e": 34215, "s": 34195, "text": "Polymorphism in C++" }, { "code": null, "e": 34248, "s": 34215, "text": "Friend class and function in C++" }, { "code": null, "e": 34269, "s": 34248, "text": "Iterators in C++ STL" }, { "code": null, "e": 34293, "s": 34269, "text": "Sorting a vector in C++" }, { "code": null, "e": 34329, "s": 34293, "text": "Convert string to char array in C++" }, { "code": null, "e": 34353, "s": 34329, "text": "Inline Functions in C++" }, { "code": null, "e": 34397, "s": 34353, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 34448, "s": 34397, "text": "new and delete operators in C++ for dynamic memory" } ]
3 Ways to Convert Python App into APK | by Kaustubh Gupta | Towards Data Science
In August 2020, I started a medium blog series called Building Android App in Python, where I explained the usage of Kivy and Kivymd. These libraries allow you to create cross-platform apps using Python. In that series, I described how android apps are configured in Python, it’s limitations, and various key elements that build up an android app. At the end of the series (3rd part), I mentioned that I will convert an app into APK and deploy it on a cloud platform. Here is the article about the same! Here I will discuss three ways in which this conversion can be performed. If you haven’t followed this series or you are unaware of this library then I highly recommend you that check out the first part of the series: towardsdatascience.com The Python apps build with Kivy cannot be directly transferred to android phones as these devices only support APK (Android Application Package) and we need to package them properly. This conversion process is only possible on a Linux system (for now) as the main components of this conversion, buildozer and python-for-android are currently supported on Linux based systems only. This adds up a challenge for budding developers who generally who use a windows machine for all the coding purpose. Other challenges include failed app conversions, app crashing on the start, or not able to connect to the internet. While some issues need extra attention from your side, I will provide you 3 different ways to successfully convert the Python app to APK. Before moving ahead, let’s look at the flow of the conversion: Making sure that the app entry point file is named as main.pyInstalling the dependencies.Initialize the buildozerEdit the specs fileStart the process Making sure that the app entry point file is named as main.py Installing the dependencies. Initialize the buildozer Edit the specs file Start the process We will see 1,2 and 4 steps in detail in upcoming sections as they don’t require any explicit change but it is necessary to understand how to configure the buildozer specs properly. The buildozer spec file is automatically generated while initializing the buildozer. The file contains the whole configuration and the app is built following this only. There are a few lines that need to be modified in that file before proceeding with the next steps (There are a total of 339 lines in the actual file): Give your app a suitable title, a package name which can simply be the lower case, concatenated version of the title, package domain which can start with com or org, then list the requirements of your app and finally uncomment the internet permissions line in case your app requires it. A small piece of advice, use kivy and kivymd defined modules to avoid any app crashing error. The first very obvious way is to set up a virtual machine, spin up a Linux distribution, and install all the dependencies. This way is a little tricky because: Not all of us have high-performance machines that can handle virtualization. To run a virtual machine, at least 4GB of RAM would be required to be allotted to this virtual system to properly fire up the machine.The process of configuring the system which involves installing the Linux, setting up the dependencies, transferring the data from the host system to the virtual machine is time-consuming. Not all of us have high-performance machines that can handle virtualization. To run a virtual machine, at least 4GB of RAM would be required to be allotted to this virtual system to properly fire up the machine. The process of configuring the system which involves installing the Linux, setting up the dependencies, transferring the data from the host system to the virtual machine is time-consuming. You can set up the virtual box and install any Linux distribution in that. The kivy developers have simplified to install all the dependencies at one go by running a bash script that installs python and other requirements to build the app. In the terminal, wget https://github.com/HeaTTheatR/KivyMD-data/raw/master/install-kivy-buildozer-dependencies.shchmod +x install-kivy-buildozer-dependencies.sh./install-kivy-buildozer-dependencies.sh After the script is done installing, navigate to your app directory and run: buildzoer init This will create the buildozer spec file which consists of all configurations you can modify. After you are done editing this file, run: buildozer android debug For the first time, this command will take longer than usual to execute (14–19 minutes) and after that, you will have a bin folder in the app directory with the APK. Transfer the app to any android device and see if works! If you opt this way then you will have a configured VM that can be used for other apps to be converted to APKs in less time. You can also run these installations in WSL (Windows Subsystem Linux) in Windows 10 if you don’t want to opt for a virtual box setup. The conversion requires a Linux environment and Google provides it for free! If you belong to Data Science or Deep learning background then you must be aware of this platform. It provides you a virtual machine with 75GB space, 12GB RAM, and around 12GB GPU power! You can use this platform to perform model training, checking logs, or running Python codes. As this is a Linux based system, now the only thing required is to install the dependencies and initiate the process. You can directly use my colab notebook where you just need to run all the cells, that’s it! !pip install buildozer !pip install cython==0.29.19 !sudo apt-get install -y \ python3-pip \ build-essential \ git \ python3 \ python3-dev \ ffmpeg \ libsdl2-dev \ libsdl2-image-dev \ libsdl2-mixer-dev \ libsdl2-ttf-dev \ libportmidi-dev \ libswscale-dev \ libavformat-dev \ libavcodec-dev \ zlib1g-dev !sudo apt-get install -y \ libgstreamer1.0 \ gstreamer1.0-plugins-base \ gstreamer1.0-plugins-good !sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libncursesw5-dev libffi-dev uuid-dev libffi6 !sudo apt-get install libffi-dev !buildozer init !buildozer -v android debug !buildozer android clean Before running the cells, make sure to upload your app code to the colab notebook and after running the bulldozer init command, make sure to edit the specs file generated and nothing else! This is the easiest and most convenient way to build apps without the need for an actual system! But can we go even more simple? Let’s see Ahh, it also provides a Linux system but only when the process is getting executed. Don’t know much about this? After you are done with this article make sure to check out this article! towardsdatascience.com Github Actions are the piece of software that lets you build, test, and deploy your code right from your GitHub repository. You can schedule jobs for various events occurring in your GitHub repository such as pushing new code, commits, or opening an issue. You can schedule either on basis of these events or use a corn job to set a timer. These GitHub actions run on a Linux system and therefore you can configure the various parameters for the conversion. The best part is that the developers of Kivy are kind enough that they have created this action too! You just need to include this workflow in your .github/workflows/<any name>.yml file: In this method, you need to place the buildozer spec file also with your app files. You can find any spec file online and after that just copy-paste that, edit it, upload the files to the repository and then add this workflow. After you run this workflow, your app will be created as an artifact that can be easily downloaded. You can also configure it to upload the APKs on another branch of the repository. Check out the official GitHub page for all the configurable parameters. I have prepared two apps for this article. One of them is a Machine Learning Deployment which predicts a song genre based on the given parameters. The second one is a very basic authentication app we build in the second part of the series. Here is the video where I am running these apps on my personal Android phone: The source code for both the apps (Python file, APK, and buildozer spec) can be found at this GitHub repository. If you don’t want to use the APK generated into your devices then you simply host them online using a free service called Appetize.io which allows you to run android apps in browsers! In this article, we saw how to configure the deployment file needed to convert the Python file into APK. Then we saw 3 different ways to do this conversion. A local machine is the best option but if don’t want to mess with your system then I would suggest Google Colab as it has great processing power. If you are looking for CI/CD type solution then GitHub actions will suit your requirements. With this, we come to an end of this article as well as the development series. If you don’t want to miss such articles then make sure to follow me on medium to receive all the notifications. With that said, Sayonara! You can connect with me here: www.linkedin.com My other popular articles:
[ { "code": null, "e": 893, "s": 171, "text": "In August 2020, I started a medium blog series called Building Android App in Python, where I explained the usage of Kivy and Kivymd. These libraries allow you to create cross-platform apps using Python. In that series, I described how android apps are configured in Python, it’s limitations, and various key elements that build up an android app. At the end of the series (3rd part), I mentioned that I will convert an app into APK and deploy it on a cloud platform. Here is the article about the same! Here I will discuss three ways in which this conversion can be performed. If you haven’t followed this series or you are unaware of this library then I highly recommend you that check out the first part of the series:" }, { "code": null, "e": 916, "s": 893, "text": "towardsdatascience.com" }, { "code": null, "e": 1667, "s": 916, "text": "The Python apps build with Kivy cannot be directly transferred to android phones as these devices only support APK (Android Application Package) and we need to package them properly. This conversion process is only possible on a Linux system (for now) as the main components of this conversion, buildozer and python-for-android are currently supported on Linux based systems only. This adds up a challenge for budding developers who generally who use a windows machine for all the coding purpose. Other challenges include failed app conversions, app crashing on the start, or not able to connect to the internet. While some issues need extra attention from your side, I will provide you 3 different ways to successfully convert the Python app to APK." }, { "code": null, "e": 1730, "s": 1667, "text": "Before moving ahead, let’s look at the flow of the conversion:" }, { "code": null, "e": 1880, "s": 1730, "text": "Making sure that the app entry point file is named as main.pyInstalling the dependencies.Initialize the buildozerEdit the specs fileStart the process" }, { "code": null, "e": 1942, "s": 1880, "text": "Making sure that the app entry point file is named as main.py" }, { "code": null, "e": 1971, "s": 1942, "text": "Installing the dependencies." }, { "code": null, "e": 1996, "s": 1971, "text": "Initialize the buildozer" }, { "code": null, "e": 2016, "s": 1996, "text": "Edit the specs file" }, { "code": null, "e": 2034, "s": 2016, "text": "Start the process" }, { "code": null, "e": 2216, "s": 2034, "text": "We will see 1,2 and 4 steps in detail in upcoming sections as they don’t require any explicit change but it is necessary to understand how to configure the buildozer specs properly." }, { "code": null, "e": 2536, "s": 2216, "text": "The buildozer spec file is automatically generated while initializing the buildozer. The file contains the whole configuration and the app is built following this only. There are a few lines that need to be modified in that file before proceeding with the next steps (There are a total of 339 lines in the actual file):" }, { "code": null, "e": 2917, "s": 2536, "text": "Give your app a suitable title, a package name which can simply be the lower case, concatenated version of the title, package domain which can start with com or org, then list the requirements of your app and finally uncomment the internet permissions line in case your app requires it. A small piece of advice, use kivy and kivymd defined modules to avoid any app crashing error." }, { "code": null, "e": 3077, "s": 2917, "text": "The first very obvious way is to set up a virtual machine, spin up a Linux distribution, and install all the dependencies. This way is a little tricky because:" }, { "code": null, "e": 3477, "s": 3077, "text": "Not all of us have high-performance machines that can handle virtualization. To run a virtual machine, at least 4GB of RAM would be required to be allotted to this virtual system to properly fire up the machine.The process of configuring the system which involves installing the Linux, setting up the dependencies, transferring the data from the host system to the virtual machine is time-consuming." }, { "code": null, "e": 3689, "s": 3477, "text": "Not all of us have high-performance machines that can handle virtualization. To run a virtual machine, at least 4GB of RAM would be required to be allotted to this virtual system to properly fire up the machine." }, { "code": null, "e": 3878, "s": 3689, "text": "The process of configuring the system which involves installing the Linux, setting up the dependencies, transferring the data from the host system to the virtual machine is time-consuming." }, { "code": null, "e": 4135, "s": 3878, "text": "You can set up the virtual box and install any Linux distribution in that. The kivy developers have simplified to install all the dependencies at one go by running a bash script that installs python and other requirements to build the app. In the terminal," }, { "code": null, "e": 4319, "s": 4135, "text": "wget https://github.com/HeaTTheatR/KivyMD-data/raw/master/install-kivy-buildozer-dependencies.shchmod +x install-kivy-buildozer-dependencies.sh./install-kivy-buildozer-dependencies.sh" }, { "code": null, "e": 4396, "s": 4319, "text": "After the script is done installing, navigate to your app directory and run:" }, { "code": null, "e": 4411, "s": 4396, "text": "buildzoer init" }, { "code": null, "e": 4548, "s": 4411, "text": "This will create the buildozer spec file which consists of all configurations you can modify. After you are done editing this file, run:" }, { "code": null, "e": 4572, "s": 4548, "text": "buildozer android debug" }, { "code": null, "e": 4795, "s": 4572, "text": "For the first time, this command will take longer than usual to execute (14–19 minutes) and after that, you will have a bin folder in the app directory with the APK. Transfer the app to any android device and see if works!" }, { "code": null, "e": 5054, "s": 4795, "text": "If you opt this way then you will have a configured VM that can be used for other apps to be converted to APKs in less time. You can also run these installations in WSL (Windows Subsystem Linux) in Windows 10 if you don’t want to opt for a virtual box setup." }, { "code": null, "e": 5411, "s": 5054, "text": "The conversion requires a Linux environment and Google provides it for free! If you belong to Data Science or Deep learning background then you must be aware of this platform. It provides you a virtual machine with 75GB space, 12GB RAM, and around 12GB GPU power! You can use this platform to perform model training, checking logs, or running Python codes." }, { "code": null, "e": 5621, "s": 5411, "text": "As this is a Linux based system, now the only thing required is to install the dependencies and initiate the process. You can directly use my colab notebook where you just need to run all the cells, that’s it!" }, { "code": null, "e": 5645, "s": 5621, "text": "!pip install buildozer\n" }, { "code": null, "e": 5675, "s": 5645, "text": "!pip install cython==0.29.19\n" }, { "code": null, "e": 5987, "s": 5675, "text": "!sudo apt-get install -y \\\n python3-pip \\\n build-essential \\\n git \\\n python3 \\\n python3-dev \\\n ffmpeg \\\n libsdl2-dev \\\n libsdl2-image-dev \\\n libsdl2-mixer-dev \\\n libsdl2-ttf-dev \\\n libportmidi-dev \\\n libswscale-dev \\\n libavformat-dev \\\n libavcodec-dev \\\n zlib1g-dev\n" }, { "code": null, "e": 6099, "s": 5987, "text": "!sudo apt-get install -y \\\n libgstreamer1.0 \\\n gstreamer1.0-plugins-base \\\n gstreamer1.0-plugins-good\n" }, { "code": null, "e": 6312, "s": 6099, "text": "!sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libncursesw5-dev libffi-dev uuid-dev libffi6\n" }, { "code": null, "e": 6346, "s": 6312, "text": "!sudo apt-get install libffi-dev\n" }, { "code": null, "e": 6363, "s": 6346, "text": "!buildozer init\n" }, { "code": null, "e": 6392, "s": 6363, "text": "!buildozer -v android debug\n" }, { "code": null, "e": 6418, "s": 6392, "text": "!buildozer android clean\n" }, { "code": null, "e": 6610, "s": 6421, "text": "Before running the cells, make sure to upload your app code to the colab notebook and after running the bulldozer init command, make sure to edit the specs file generated and nothing else!" }, { "code": null, "e": 6749, "s": 6610, "text": "This is the easiest and most convenient way to build apps without the need for an actual system! But can we go even more simple? Let’s see" }, { "code": null, "e": 6935, "s": 6749, "text": "Ahh, it also provides a Linux system but only when the process is getting executed. Don’t know much about this? After you are done with this article make sure to check out this article!" }, { "code": null, "e": 6958, "s": 6935, "text": "towardsdatascience.com" }, { "code": null, "e": 7416, "s": 6958, "text": "Github Actions are the piece of software that lets you build, test, and deploy your code right from your GitHub repository. You can schedule jobs for various events occurring in your GitHub repository such as pushing new code, commits, or opening an issue. You can schedule either on basis of these events or use a corn job to set a timer. These GitHub actions run on a Linux system and therefore you can configure the various parameters for the conversion." }, { "code": null, "e": 7603, "s": 7416, "text": "The best part is that the developers of Kivy are kind enough that they have created this action too! You just need to include this workflow in your .github/workflows/<any name>.yml file:" }, { "code": null, "e": 8084, "s": 7603, "text": "In this method, you need to place the buildozer spec file also with your app files. You can find any spec file online and after that just copy-paste that, edit it, upload the files to the repository and then add this workflow. After you run this workflow, your app will be created as an artifact that can be easily downloaded. You can also configure it to upload the APKs on another branch of the repository. Check out the official GitHub page for all the configurable parameters." }, { "code": null, "e": 8402, "s": 8084, "text": "I have prepared two apps for this article. One of them is a Machine Learning Deployment which predicts a song genre based on the given parameters. The second one is a very basic authentication app we build in the second part of the series. Here is the video where I am running these apps on my personal Android phone:" }, { "code": null, "e": 8515, "s": 8402, "text": "The source code for both the apps (Python file, APK, and buildozer spec) can be found at this GitHub repository." }, { "code": null, "e": 8699, "s": 8515, "text": "If you don’t want to use the APK generated into your devices then you simply host them online using a free service called Appetize.io which allows you to run android apps in browsers!" }, { "code": null, "e": 9174, "s": 8699, "text": "In this article, we saw how to configure the deployment file needed to convert the Python file into APK. Then we saw 3 different ways to do this conversion. A local machine is the best option but if don’t want to mess with your system then I would suggest Google Colab as it has great processing power. If you are looking for CI/CD type solution then GitHub actions will suit your requirements. With this, we come to an end of this article as well as the development series." }, { "code": null, "e": 9312, "s": 9174, "text": "If you don’t want to miss such articles then make sure to follow me on medium to receive all the notifications. With that said, Sayonara!" }, { "code": null, "e": 9342, "s": 9312, "text": "You can connect with me here:" }, { "code": null, "e": 9359, "s": 9342, "text": "www.linkedin.com" } ]
C# Program to Print the Employees Whose ID is Greater Than 101 Using LINQ - GeeksforGeeks
18 Oct, 2021 LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will display the employee details whose ID greater than 101 using LINQ. Example: Input: List of employees: {{emp_id = 101, emp_name = "bobby", emp_age = 12}, {emp_id = 102, emp_name = "deepu", emp_age = 15}, {emp_id = 103, emp_name = "manoja", emp_age = 13}, {emp_id = 104, emp_name = "saroja", emp_age = 14}, {emp_id = 105, emp_name = "sravan", emp_age = 15}, {emp_id = 106, emp_name = "navya", emp_age = 12}, {emp_id = 107, emp_name = "majnu", emp_age = 12}, {emp_id = 108, emp_name = "vishnu", emp_age = 12}} Output: {{emp_id = 102, emp_name = "deepu", emp_age = 15}, {emp_id = 103, emp_name = "manoja", emp_age = 13}, {emp_id = 104, emp_name = "saroja", emp_age = 14}, {emp_id = 105, emp_name = "sravan", emp_age = 15}, {emp_id = 106, emp_name = "navya", emp_age = 12}, {emp_id = 107, emp_name = "majnu", emp_age = 12}, {emp_id = 108, emp_name = "vishnu", emp_age = 12}} Input: List of employees: {{emp_id = 101, emp_name = "bobby", emp_age = 12}, {emp_id = 102, emp_name = "deepu", emp_age = 15}, {emp_id = 103, emp_name = "manoja", emp_age = 13}} Output: {{emp_id = 102, emp_name = "deepu", emp_age = 15}, {emp_id = 103, emp_name = "manoja", emp_age = 13}} Approach: To display the employee details whose ID greater than 101 follow the following approach: Create a list of employees with three variables (Id, name and age)Iterate through the employee details by using where function and get the employee details by choosing employee id greater than 101Select the details which are greater than 101Call the ToString() methodDisplay the employee details Create a list of employees with three variables (Id, name and age) Iterate through the employee details by using where function and get the employee details by choosing employee id greater than 101 Select the details which are greater than 101 Call the ToString() method Display the employee details Example: C# // C# program to display the details of the employee// whose ID greater than 101 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; public class Employee{ // Declare 3 variables - id,age and nameint emp_id; int emp_age;string emp_name; // Get the to string method that returns// id , name and agepublic override string ToString(){ return emp_id + " " + emp_name + " " + emp_age;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp1 = new List<Employee>() { // Create 8 employee details new Employee{ emp_id = 101, emp_name = "bobby", emp_age = 12}, new Employee{ emp_id = 102, emp_name = "deepu", emp_age = 15}, new Employee{ emp_id = 103, emp_name = "manoja", emp_age = 13}, new Employee{ emp_id = 104, emp_name = "saroja", emp_age = 14}, new Employee{ emp_id = 105, emp_name = "sravan", emp_age = 15}, new Employee{ emp_id = 106, emp_name = "navya", emp_age = 12}, new Employee{ emp_id = 107, emp_name = "majnu", emp_age = 12}, new Employee{ emp_id = 108, emp_name = "vishnu", emp_age = 12}, }; // Iterate the Employee by selecting Employee // id greater than 101 // Using where clause IEnumerable<Employee> Query = from employee in emp1 where employee.emp_id > 101 select employee; // Display employee details Console.WriteLine("ID Name Age"); Console.WriteLine("+++++++++++++"); foreach (Employee e in Query) { // Call the to string method Console.WriteLine(e.ToString()); }}} Output: ID Name Age +++++++++++++ 102 deepu 15 103 manoja 13 104 saroja 14 105 sravan 15 106 navya 12 107 majnu 12 108 vishnu 12 CSharp LINQ CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | Inheritance C# | List Class Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Linked List Implementation in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n18 Oct, 2021" }, { "code": null, "e": 24732, "s": 24302, "text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will display the employee details whose ID greater than 101 using LINQ." }, { "code": null, "e": 24741, "s": 24732, "text": "Example:" }, { "code": null, "e": 25976, "s": 24741, "text": "Input:\nList of employees:\n {{emp_id = 101, emp_name = \"bobby\", emp_age = 12},\n {emp_id = 102, emp_name = \"deepu\", emp_age = 15},\n {emp_id = 103, emp_name = \"manoja\", emp_age = 13},\n {emp_id = 104, emp_name = \"saroja\", emp_age = 14},\n {emp_id = 105, emp_name = \"sravan\", emp_age = 15},\n {emp_id = 106, emp_name = \"navya\", emp_age = 12},\n {emp_id = 107, emp_name = \"majnu\", emp_age = 12},\n {emp_id = 108, emp_name = \"vishnu\", emp_age = 12}}\nOutput:\n {{emp_id = 102, emp_name = \"deepu\", emp_age = 15},\n {emp_id = 103, emp_name = \"manoja\", emp_age = 13},\n {emp_id = 104, emp_name = \"saroja\", emp_age = 14},\n {emp_id = 105, emp_name = \"sravan\", emp_age = 15},\n {emp_id = 106, emp_name = \"navya\", emp_age = 12},\n {emp_id = 107, emp_name = \"majnu\", emp_age = 12},\n {emp_id = 108, emp_name = \"vishnu\", emp_age = 12}}\n \nInput:\nList of employees:\n {{emp_id = 101, emp_name = \"bobby\", emp_age = 12},\n {emp_id = 102, emp_name = \"deepu\", emp_age = 15},\n {emp_id = 103, emp_name = \"manoja\", emp_age = 13}}\nOutput:\n {{emp_id = 102, emp_name = \"deepu\", emp_age = 15},\n {emp_id = 103, emp_name = \"manoja\", emp_age = 13}}" }, { "code": null, "e": 25986, "s": 25976, "text": "Approach:" }, { "code": null, "e": 26075, "s": 25986, "text": "To display the employee details whose ID greater than 101 follow the following approach:" }, { "code": null, "e": 26371, "s": 26075, "text": "Create a list of employees with three variables (Id, name and age)Iterate through the employee details by using where function and get the employee details by choosing employee id greater than 101Select the details which are greater than 101Call the ToString() methodDisplay the employee details" }, { "code": null, "e": 26438, "s": 26371, "text": "Create a list of employees with three variables (Id, name and age)" }, { "code": null, "e": 26569, "s": 26438, "text": "Iterate through the employee details by using where function and get the employee details by choosing employee id greater than 101" }, { "code": null, "e": 26615, "s": 26569, "text": "Select the details which are greater than 101" }, { "code": null, "e": 26642, "s": 26615, "text": "Call the ToString() method" }, { "code": null, "e": 26671, "s": 26642, "text": "Display the employee details" }, { "code": null, "e": 26680, "s": 26671, "text": "Example:" }, { "code": null, "e": 26683, "s": 26680, "text": "C#" }, { "code": "// C# program to display the details of the employee// whose ID greater than 101 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; public class Employee{ // Declare 3 variables - id,age and nameint emp_id; int emp_age;string emp_name; // Get the to string method that returns// id , name and agepublic override string ToString(){ return emp_id + \" \" + emp_name + \" \" + emp_age;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp1 = new List<Employee>() { // Create 8 employee details new Employee{ emp_id = 101, emp_name = \"bobby\", emp_age = 12}, new Employee{ emp_id = 102, emp_name = \"deepu\", emp_age = 15}, new Employee{ emp_id = 103, emp_name = \"manoja\", emp_age = 13}, new Employee{ emp_id = 104, emp_name = \"saroja\", emp_age = 14}, new Employee{ emp_id = 105, emp_name = \"sravan\", emp_age = 15}, new Employee{ emp_id = 106, emp_name = \"navya\", emp_age = 12}, new Employee{ emp_id = 107, emp_name = \"majnu\", emp_age = 12}, new Employee{ emp_id = 108, emp_name = \"vishnu\", emp_age = 12}, }; // Iterate the Employee by selecting Employee // id greater than 101 // Using where clause IEnumerable<Employee> Query = from employee in emp1 where employee.emp_id > 101 select employee; // Display employee details Console.WriteLine(\"ID Name Age\"); Console.WriteLine(\"+++++++++++++\"); foreach (Employee e in Query) { // Call the to string method Console.WriteLine(e.ToString()); }}}", "e": 28337, "s": 26683, "text": null }, { "code": null, "e": 28345, "s": 28337, "text": "Output:" }, { "code": null, "e": 28468, "s": 28345, "text": "ID Name Age\n+++++++++++++\n102 deepu 15\n103 manoja 13\n104 saroja 14\n105 sravan 15\n106 navya 12\n107 majnu 12\n108 vishnu 12" }, { "code": null, "e": 28480, "s": 28468, "text": "CSharp LINQ" }, { "code": null, "e": 28496, "s": 28480, "text": "CSharp-programs" }, { "code": null, "e": 28503, "s": 28496, "text": "Picked" }, { "code": null, "e": 28506, "s": 28503, "text": "C#" }, { "code": null, "e": 28604, "s": 28506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28613, "s": 28604, "text": "Comments" }, { "code": null, "e": 28626, "s": 28613, "text": "Old Comments" }, { "code": null, "e": 28649, "s": 28626, "text": "Extension Method in C#" }, { "code": null, "e": 28677, "s": 28649, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28717, "s": 28677, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28760, "s": 28717, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28777, "s": 28760, "text": "C# | Inheritance" }, { "code": null, "e": 28793, "s": 28777, "text": "C# | List Class" }, { "code": null, "e": 28815, "s": 28793, "text": "Partial Classes in C#" }, { "code": null, "e": 28855, "s": 28815, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28880, "s": 28855, "text": "Lambda Expressions in C#" } ]
How to add a number and a string in JavaScript?
In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place. In the following example, variables a,b,c and d are taken. For variable 'a', two numbers(5, 5) are added therefore it returned a number(10). But in case of variable 'b' a string and a number ('5', 5) are added therefore, since a string is involved, we get the result as '55', which is a string. since strings are involved, Variables 'c' and 'd' also return a string as shown in the output. Live Demo <html> <body> <script type="text/javascript"> var a = 5 + 5; var b = "5" + 5; var c = 5 + 5 + "5" + 5 var d = "Hello" + 5; document.write(a + "<br>" + b + "<br>" + c + "</br>" + d); document.write("</br>"); document.write(typeof(a)); document.write("</br>"); document.write(typeof(b)); document.write("</br>"); document.write(typeof(c)); document.write("</br>"); document.write(typeof(d)); </script> </body> </html> 10 55 1055 Hello5 number string string string
[ { "code": null, "e": 1218, "s": 1062, "text": "In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place." }, { "code": null, "e": 1612, "s": 1218, "text": "In the following example, variables a,b,c and d are taken. For variable 'a', two numbers(5, 5) are added therefore it returned a number(10). But in case of variable 'b' a string and a number ('5', 5) are added therefore, since a string is involved, we get the result as '55', which is a string. since strings are involved, Variables 'c' and 'd' also return a string as shown in the output. " }, { "code": null, "e": 1622, "s": 1612, "text": "Live Demo" }, { "code": null, "e": 2077, "s": 1622, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n var a = 5 + 5;\n var b = \"5\" + 5;\n var c = 5 + 5 + \"5\" + 5\n var d = \"Hello\" + 5;\n document.write(a + \"<br>\" + b + \"<br>\" + c + \"</br>\" + d);\n document.write(\"</br>\");\n document.write(typeof(a));\n document.write(\"</br>\");\n document.write(typeof(b));\n document.write(\"</br>\");\n document.write(typeof(c));\n document.write(\"</br>\");\n document.write(typeof(d));\n</script>\n</body>\n</html>" }, { "code": null, "e": 2123, "s": 2077, "text": "10\n55\n1055\nHello5\nnumber\nstring\nstring\nstring" } ]
How to crop the detected faces in OpenCV using C++?
We will know how to crop the detected faces in OpenCV. To crop detected faces, we need multiple matrices. The most appropriate way is to use an image array. In this program using the following two lines, we have declared two image matrices − Mat cropped_faces[4]; Mat faceROI[4]; The first matrix is to store the cropped images, and the second matrix is to define the region of interest. In the detection process, first, the program locates the faces and store them in vectors. In our program, the name of the vector is 'faces' Vectors can contain multiple elements. Using the following two lines, we identify the vectors and locate their position in the image and finally crop the face region in the 'faceROI[i]' matrices. faceROI[]=image_with_humanface(faces[i]); cropped_faces[i]=faceROI[i]; The first line locate the vector containing faces on image named 'image_with_humanface' and crop it and store it into the matrix named 'faceROI[i]'. In the second line, the cropped images are being passed to another matrix array. This matrix array has been used to show the cropped images. The following program crops the detected faces and show them in separate windows. #include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> //This header includes definition of 'rectangle()' function// #include<opencv2/objdetect/objdetect.hpp> //This header includes the definition of Cascade Classifier// #include<string> using namespace std; using namespace cv; int main(int argc, char** argv) { Mat image_with_humanface;//Declaring a matrix to load image with human faces// Mat cropped_faces[3];//Declaring an array of matrix of 4 elements to show the cropped faces// Mat faceROI[3];//Declaring an array of matrix of 4 elements to hold the cropped faces// image_with_humanface = imread("friends3.jpg");//loading an image that contains human face in it// namedWindow("Face1");//Declaring an window to show 1st cropped face// namedWindow("Face2");//Declaring an window to show 2nd cropped face// namedWindow("Face3");//Declaring an window to show 3rd cropped face// string trained_classifier_location = "C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";//Defining the location our XML Trained Classifier in a string// CascadeClassifier faceDetector;//Declaring an object named 'face detector' of CascadeClassifier class// faceDetector.load(trained_classifier_location);//loading the XML trained classifier in the object// vector<Rect>faces;//Declaring a rectangular vector named faces// vector<Rect>boundary;//Declaring a rectangular vector named rectangle// faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20, 20));//Detecting the faces in 'image_with_humanfaces' matrix// for (size_t i = 0; i < faces.size(); i++){ //Loop to draw rectangle around the faces// faceROI[i] = image_with_humanface(faces[i]); cropped_faces[i] = faceROI[i]; int x = faces[i].x;//Getting the initial row value of face rectangle's starting point// int y = faces[i].y;//Getting the initial column value of face rectangle's starting point// int h = y + faces[i].height;//Calculating the height of the rectangle// int w = x + faces[i].width;//Calculating the width of the rectangle// rectangle(image_with_humanface, Point(x, y), Point(w, h), Scalar(255, 0, 255), 2, 8, 0);//Drawing a rectangle using around the faces// } imshow("Face1", cropped_faces[0]);//Showing the 1st cropped face// imshow("Face2", cropped_faces[1]);//Showing the 2nd cropped face// imshow("Face3", cropped_faces[2]);//Showing the 3rd cropped face// waitKey(0);//To wait for a keystroke to terminate the program return 0; }
[ { "code": null, "e": 1304, "s": 1062, "text": "We will know how to crop the detected faces in OpenCV. To crop detected faces, we need multiple matrices. The most appropriate way is to use an image array. In this program using the following two lines, we have declared two image matrices −" }, { "code": null, "e": 1326, "s": 1304, "text": "Mat cropped_faces[4];" }, { "code": null, "e": 1342, "s": 1326, "text": "Mat faceROI[4];" }, { "code": null, "e": 1629, "s": 1342, "text": "The first matrix is to store the cropped images, and the second matrix is to define the region of interest. In the detection process, first, the program locates the faces and store them in vectors. In our program, the name of the vector is 'faces' Vectors can contain multiple elements." }, { "code": null, "e": 1786, "s": 1629, "text": "Using the following two lines, we identify the vectors and locate their position in the image and finally crop the face region in the 'faceROI[i]' matrices." }, { "code": null, "e": 1828, "s": 1786, "text": "faceROI[]=image_with_humanface(faces[i]);" }, { "code": null, "e": 1857, "s": 1828, "text": "cropped_faces[i]=faceROI[i];" }, { "code": null, "e": 2147, "s": 1857, "text": "The first line locate the vector containing faces on image named 'image_with_humanface' and crop it and store it into the matrix named 'faceROI[i]'. In the second line, the cropped images are being passed to another matrix array. This matrix array has been used to show the cropped images." }, { "code": null, "e": 2229, "s": 2147, "text": "The following program crops the detected faces and show them in separate windows." }, { "code": null, "e": 4824, "s": 2229, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\n//This header includes definition of 'rectangle()' function//\n#include<opencv2/objdetect/objdetect.hpp>\n//This header includes the definition of Cascade Classifier//\n#include<string>\nusing namespace std;\nusing namespace cv;\nint main(int argc, char** argv) {\n Mat image_with_humanface;//Declaring a matrix to load image with human faces//\n Mat cropped_faces[3];//Declaring an array of matrix of 4 elements to show the cropped faces//\n Mat faceROI[3];//Declaring an array of matrix of 4 elements to hold the cropped faces//\n image_with_humanface = imread(\"friends3.jpg\");//loading an image that contains human face in it//\n namedWindow(\"Face1\");//Declaring an window to show 1st cropped face//\n namedWindow(\"Face2\");//Declaring an window to show 2nd cropped face//\n namedWindow(\"Face3\");//Declaring an window to show 3rd cropped face// \n string trained_classifier_location = \"C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml\";//Defining the location our XML Trained Classifier in a string//\n CascadeClassifier faceDetector;//Declaring an object named 'face detector' of CascadeClassifier class//\n faceDetector.load(trained_classifier_location);//loading the XML trained classifier in the object//\n vector<Rect>faces;//Declaring a rectangular vector named faces//\n vector<Rect>boundary;//Declaring a rectangular vector named rectangle//\n faceDetector.detectMultiScale(image_with_humanface, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20, 20));//Detecting the faces in 'image_with_humanfaces' matrix//\n for (size_t i = 0; i < faces.size(); i++){ //Loop to draw rectangle around the faces//\n faceROI[i] = image_with_humanface(faces[i]);\n cropped_faces[i] = faceROI[i];\n int x = faces[i].x;//Getting the initial row value of face rectangle's starting point//\n int y = faces[i].y;//Getting the initial column value of face rectangle's starting point//\n int h = y + faces[i].height;//Calculating the height of the rectangle//\n int w = x + faces[i].width;//Calculating the width of the rectangle//\n rectangle(image_with_humanface, Point(x, y), Point(w, h), Scalar(255, 0, 255), 2, 8, 0);//Drawing a rectangle using around the faces//\n }\n imshow(\"Face1\", cropped_faces[0]);//Showing the 1st cropped face//\n imshow(\"Face2\", cropped_faces[1]);//Showing the 2nd cropped face//\n imshow(\"Face3\", cropped_faces[2]);//Showing the 3rd cropped face//\n waitKey(0);//To wait for a keystroke to terminate the program\n return 0;\n}" } ]
Ruby | Methods
06 May, 2022 Method is a collection of statements that perform some specific task and return the result. Methods are time savers and help the user to reuse the code without retyping the code. Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name. You can simply write the name of method whenever you call a method. Syntax: def method_name # Statement 1 # Statement 2 . . end Example: Ruby # Ruby program to illustrate the defining# and calling of method #!/usr/bin/ruby # Here geeks is the method namedef geeks # statements to be displayedputs "Welcome to GFG portal" # keyword to end methodend # calling of the methodgeeks Output: Welcome to GFG portal Passing parameters to methods: In Ruby, parameter passing is similar to other programming language’s parameter passing i.e simply write the parameters in the brackets (). Syntax: def method_name(var1, var2, var3) # Statement 1 # Statement 2 . . end Example: Ruby # Ruby program to illustrate the parameter# passing to methods #!/usr/bin/ruby # geeks is the method name# var1 and var2 are the parametersdef geeks (var1 = "GFG", var2 = "G4G") # statements to be executed puts "First parameter is #{var1}" puts "First parameter is #{var2}"end # calling method with parametersgeeks "GeeksforGeeks", "Sudo" puts "" puts "Without Parameters"puts "" # calling method without passing parametersgeeks Output: First parameter is GeeksforGeeks First parameter is Sudo Without Parameters First parameter is GFG First parameter is G4G Variable Number of Parameters: Ruby allows the programmer to define a method that can take the variable number of arguments. It is useful when the user doesn’t know the number of parameters to be passed while defining the method. Syntax: def method_name(*variable_name) # Statement 1 # Statement 2 . . end Example: Ruby # Ruby program to illustrate the method# that takes variables number of arguments #!/usr/bin/ruby # defining method geeks that can# take any number of argumentsdef geeks (*var) # to display the total number of parameters puts "Number of parameters is: #{var.length}" # using for loop for i in 0...var.length puts "Parameters are: #{var[i]}" endend # calling method by passing# variable number of argumentsgeeks "GFG", "G4G"geeks "GeeksforGeeks" Output: Number of parameters is: 2 Parameters are: GFG Parameters are: G4G Number of parameters is: 1 Parameters are: GeeksforGeeks Return statement in Methods: Return statement used to returns one or more values. By default, a method always returns the last statement that was evaluated in the body of the method. ‘return’ keyword is used to return the statements. Example: Ruby # Ruby program to illustrate method return statement #!/usr/bin/ruby # geeks is the method namedef num # variables of methoda = 10b = 39 sum = a + b # return the value of the sumreturn sum end # calling of num methodputs "The result is: #{num}" Output: The result is: 49 praveenkumarkp666 Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | unless Statement and unless Modifier Ruby | Hash delete() function Ruby | Data Types Ruby | String capitalize() Method Ruby For Beginners
[ { "code": null, "e": 53, "s": 25, "text": "\n06 May, 2022" }, { "code": null, "e": 569, "s": 53, "text": "Method is a collection of statements that perform some specific task and return the result. Methods are time savers and help the user to reuse the code without retyping the code. Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name. You can simply write the name of method whenever you call a method. " }, { "code": null, "e": 578, "s": 569, "text": "Syntax: " }, { "code": null, "e": 630, "s": 578, "text": "def method_name\n# Statement 1\n# Statement 2\n.\n.\nend" }, { "code": null, "e": 640, "s": 630, "text": "Example: " }, { "code": null, "e": 645, "s": 640, "text": "Ruby" }, { "code": "# Ruby program to illustrate the defining# and calling of method #!/usr/bin/ruby # Here geeks is the method namedef geeks # statements to be displayedputs \"Welcome to GFG portal\" # keyword to end methodend # calling of the methodgeeks", "e": 880, "s": 645, "text": null }, { "code": null, "e": 888, "s": 880, "text": "Output:" }, { "code": null, "e": 910, "s": 888, "text": "Welcome to GFG portal" }, { "code": null, "e": 1082, "s": 910, "text": "Passing parameters to methods: In Ruby, parameter passing is similar to other programming language’s parameter passing i.e simply write the parameters in the brackets (). " }, { "code": null, "e": 1090, "s": 1082, "text": "Syntax:" }, { "code": null, "e": 1160, "s": 1090, "text": "def method_name(var1, var2, var3)\n# Statement 1\n# Statement 2\n.\n.\nend" }, { "code": null, "e": 1170, "s": 1160, "text": "Example: " }, { "code": null, "e": 1175, "s": 1170, "text": "Ruby" }, { "code": "# Ruby program to illustrate the parameter# passing to methods #!/usr/bin/ruby # geeks is the method name# var1 and var2 are the parametersdef geeks (var1 = \"GFG\", var2 = \"G4G\") # statements to be executed puts \"First parameter is #{var1}\" puts \"First parameter is #{var2}\"end # calling method with parametersgeeks \"GeeksforGeeks\", \"Sudo\" puts \"\" puts \"Without Parameters\"puts \"\" # calling method without passing parametersgeeks", "e": 1618, "s": 1175, "text": null }, { "code": null, "e": 1626, "s": 1618, "text": "Output:" }, { "code": null, "e": 1750, "s": 1626, "text": "First parameter is GeeksforGeeks\nFirst parameter is Sudo\n\nWithout Parameters\n\nFirst parameter is GFG\nFirst parameter is G4G" }, { "code": null, "e": 1981, "s": 1750, "text": "Variable Number of Parameters: Ruby allows the programmer to define a method that can take the variable number of arguments. It is useful when the user doesn’t know the number of parameters to be passed while defining the method. " }, { "code": null, "e": 1989, "s": 1981, "text": "Syntax:" }, { "code": null, "e": 2057, "s": 1989, "text": "def method_name(*variable_name)\n# Statement 1\n# Statement 2\n.\n.\nend" }, { "code": null, "e": 2067, "s": 2057, "text": "Example: " }, { "code": null, "e": 2072, "s": 2067, "text": "Ruby" }, { "code": "# Ruby program to illustrate the method# that takes variables number of arguments #!/usr/bin/ruby # defining method geeks that can# take any number of argumentsdef geeks (*var) # to display the total number of parameters puts \"Number of parameters is: #{var.length}\" # using for loop for i in 0...var.length puts \"Parameters are: #{var[i]}\" endend # calling method by passing# variable number of argumentsgeeks \"GFG\", \"G4G\"geeks \"GeeksforGeeks\"", "e": 2541, "s": 2072, "text": null }, { "code": null, "e": 2549, "s": 2541, "text": "Output:" }, { "code": null, "e": 2673, "s": 2549, "text": "Number of parameters is: 2\nParameters are: GFG\nParameters are: G4G\nNumber of parameters is: 1\nParameters are: GeeksforGeeks" }, { "code": null, "e": 2908, "s": 2673, "text": "Return statement in Methods: Return statement used to returns one or more values. By default, a method always returns the last statement that was evaluated in the body of the method. ‘return’ keyword is used to return the statements. " }, { "code": null, "e": 2918, "s": 2908, "text": "Example: " }, { "code": null, "e": 2923, "s": 2918, "text": "Ruby" }, { "code": "# Ruby program to illustrate method return statement #!/usr/bin/ruby # geeks is the method namedef num # variables of methoda = 10b = 39 sum = a + b # return the value of the sumreturn sum end # calling of num methodputs \"The result is: #{num}\"", "e": 3168, "s": 2923, "text": null }, { "code": null, "e": 3176, "s": 3168, "text": "Output:" }, { "code": null, "e": 3194, "s": 3176, "text": "The result is: 49" }, { "code": null, "e": 3212, "s": 3194, "text": "praveenkumarkp666" }, { "code": null, "e": 3225, "s": 3212, "text": "Ruby-Methods" }, { "code": null, "e": 3230, "s": 3225, "text": "Ruby" }, { "code": null, "e": 3328, "s": 3230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3374, "s": 3328, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 3398, "s": 3374, "text": "Global Variable in Ruby" }, { "code": null, "e": 3441, "s": 3398, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 3463, "s": 3441, "text": "Ruby | Case Statement" }, { "code": null, "e": 3494, "s": 3463, "text": "Ruby | Array select() function" }, { "code": null, "e": 3538, "s": 3494, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 3568, "s": 3538, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 3586, "s": 3568, "text": "Ruby | Data Types" }, { "code": null, "e": 3620, "s": 3586, "text": "Ruby | String capitalize() Method" } ]
How to directly update a field by using ng-click in AngularJS ?
10 Oct, 2019 Any field can be updated with ng-click using a custom JavaScript function. For this, we can make a clickable object in an HTML (usually a button) and attach a ng-click directive with it that calls this custom function. The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can popup alert when a button is clicked. Syntax: <element ng-click="expression"> Contents... </element> Example 1: This example calls a function to change the field value after click on the button. <!DOCTYPE html><html ng-app="example"> <head> <title> How to directly update a field by using ng-click in AngularJS? </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body> <div ng-controller="basicCntrl"> <h1 style="color:green"> Hello {{name}}! </h1> <!-- on button click the change() function is called from $scope --> <button type="button" ng-click="change()"> Click! </button> </div> <script type="text/javascript"> var app = angular.module('example', []); app.controller('basicCntrl', function($scope) { $scope.name = "GFG"; $scope.change = function() { this.name = 'GeeksForGeeks'; } }); </script></body> </html> Output: Before Click on the Button: After Click on the Button: The button calls the change function which changes the variable name. The change reflected on the page because of the {{name}} syntax. For simpler logic such as the one shown in example 1, we can avoid calling the function and changing the variable inside the ng-click directive. Example 2: This example changes the variable name inside the ng-click directive. <!DOCTYPE html><html ng-app="example"> <head> <title> How to directly update a field by using ng-click in AngularJS? </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body> <div ng-controller="basicCntrl"> <h1 style="color:green"> Hello {{name}}! </h1> <!-- on button click the name is changed directly --> <button type="button" ng-click="name='GeeksForGeeks'"> Click! </button> </div> <script type="text/javascript"> var app = angular.module('example', []); app.controller('basicCntrl', function($scope) { $scope.name = "GFG"; }); </script></body> </html> Output: Before Click on the Button: After Click on the Button: Also, We can use other HTML tags to make the ng-click work such as a paragraph tag. Example 3: This example uses a paragraph tag to change the heading content. <!DOCTYPE html><html ng-app="example"> <head> <title> How to directly update a field by using ng-click in AngularJS? </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"> </script></head> <body> <div ng-controller="basicCntrl"> <h1 style="color:green"> Hello {{name}}! </h1> <!-- on paragraph click the name is changed directly --> <p ng-click="name='GeeksForGeeks'"> Click! </p> </div> <script type="text/javascript"> var app = angular.module('example', []); app.controller('basicCntrl', function($scope) { $scope.name = "GFG"; }); </script></body> </html> Output: Before Click on the paramgraph element ‘Click’: After Click on the paramgraph element ‘Click’: AngularJS-Misc Picked AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular | keyup event Auth Guards in Angular 9/10/11 Routing in Angular 9/10 What is AOT and JIT Compiler in Angular ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Oct, 2019" }, { "code": null, "e": 433, "s": 28, "text": "Any field can be updated with ng-click using a custom JavaScript function. For this, we can make a clickable object in an HTML (usually a button) and attach a ng-click directive with it that calls this custom function. The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can popup alert when a button is clicked." }, { "code": null, "e": 441, "s": 433, "text": "Syntax:" }, { "code": null, "e": 496, "s": 441, "text": "<element ng-click=\"expression\"> Contents... </element>" }, { "code": null, "e": 590, "s": 496, "text": "Example 1: This example calls a function to change the field value after click on the button." }, { "code": "<!DOCTYPE html><html ng-app=\"example\"> <head> <title> How to directly update a field by using ng-click in AngularJS? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body> <div ng-controller=\"basicCntrl\"> <h1 style=\"color:green\"> Hello {{name}}! </h1> <!-- on button click the change() function is called from $scope --> <button type=\"button\" ng-click=\"change()\"> Click! </button> </div> <script type=\"text/javascript\"> var app = angular.module('example', []); app.controller('basicCntrl', function($scope) { $scope.name = \"GFG\"; $scope.change = function() { this.name = 'GeeksForGeeks'; } }); </script></body> </html>", "e": 1497, "s": 590, "text": null }, { "code": null, "e": 1505, "s": 1497, "text": "Output:" }, { "code": null, "e": 1533, "s": 1505, "text": "Before Click on the Button:" }, { "code": null, "e": 1560, "s": 1533, "text": "After Click on the Button:" }, { "code": null, "e": 1840, "s": 1560, "text": "The button calls the change function which changes the variable name. The change reflected on the page because of the {{name}} syntax. For simpler logic such as the one shown in example 1, we can avoid calling the function and changing the variable inside the ng-click directive." }, { "code": null, "e": 1921, "s": 1840, "text": "Example 2: This example changes the variable name inside the ng-click directive." }, { "code": "<!DOCTYPE html><html ng-app=\"example\"> <head> <title> How to directly update a field by using ng-click in AngularJS? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body> <div ng-controller=\"basicCntrl\"> <h1 style=\"color:green\"> Hello {{name}}! </h1> <!-- on button click the name is changed directly --> <button type=\"button\" ng-click=\"name='GeeksForGeeks'\"> Click! </button> </div> <script type=\"text/javascript\"> var app = angular.module('example', []); app.controller('basicCntrl', function($scope) { $scope.name = \"GFG\"; }); </script></body> </html>", "e": 2739, "s": 1921, "text": null }, { "code": null, "e": 2747, "s": 2739, "text": "Output:" }, { "code": null, "e": 2775, "s": 2747, "text": "Before Click on the Button:" }, { "code": null, "e": 2802, "s": 2775, "text": "After Click on the Button:" }, { "code": null, "e": 2886, "s": 2802, "text": "Also, We can use other HTML tags to make the ng-click work such as a paragraph tag." }, { "code": null, "e": 2962, "s": 2886, "text": "Example 3: This example uses a paragraph tag to change the heading content." }, { "code": "<!DOCTYPE html><html ng-app=\"example\"> <head> <title> How to directly update a field by using ng-click in AngularJS? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js\"> </script></head> <body> <div ng-controller=\"basicCntrl\"> <h1 style=\"color:green\"> Hello {{name}}! </h1> <!-- on paragraph click the name is changed directly --> <p ng-click=\"name='GeeksForGeeks'\"> Click! </p> </div> <script type=\"text/javascript\"> var app = angular.module('example', []); app.controller('basicCntrl', function($scope) { $scope.name = \"GFG\"; }); </script></body> </html>", "e": 3744, "s": 2962, "text": null }, { "code": null, "e": 3752, "s": 3744, "text": "Output:" }, { "code": null, "e": 3800, "s": 3752, "text": "Before Click on the paramgraph element ‘Click’:" }, { "code": null, "e": 3847, "s": 3800, "text": "After Click on the paramgraph element ‘Click’:" }, { "code": null, "e": 3862, "s": 3847, "text": "AngularJS-Misc" }, { "code": null, "e": 3869, "s": 3862, "text": "Picked" }, { "code": null, "e": 3879, "s": 3869, "text": "AngularJS" }, { "code": null, "e": 3896, "s": 3879, "text": "Web Technologies" }, { "code": null, "e": 3923, "s": 3896, "text": "Web technologies Questions" }, { "code": null, "e": 4021, "s": 3923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4041, "s": 4021, "text": "Angular File Upload" }, { "code": null, "e": 4063, "s": 4041, "text": "Angular | keyup event" }, { "code": null, "e": 4094, "s": 4063, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 4118, "s": 4094, "text": "Routing in Angular 9/10" }, { "code": null, "e": 4160, "s": 4118, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 4222, "s": 4160, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4255, "s": 4222, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4316, "s": 4255, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4366, "s": 4316, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Setting file offsets in Python
17 Sep, 2021 Prerequisite: seek(), tell() Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer within the file. offset is used later on to perform operations within the text file depending on the permissions given, like read, write, etc. Before starting let recall some basic methods for file handling: seek(): In Python, seek() function is used to change the position of the File Handle to a given specific position. The file handle is like a cursor, which defines where the data has to be read or written in the file. Syntax: f.seek(offset, from_what), where f is file pointer Parameters:Offset: Number of positions to move forwardfrom_what: It defines point of reference. tell(): Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Sometimes it becomes important for us to know the position of the File Handle. tell() method can be used to get the position of File Handle. tell() method returns the current position of the file object. This method takes no parameters and returns an integer value. Initially file pointer points to the beginning of the file(if not opened in append mode). So, the initial value of tell() is zero. Syntax : f.tell() Return: This method returns the current position of the file read/write pointer within the file. Step 1: Creating a text file. Let’s create a text file “emails.txt” containing multiple emails to demonstrate the working of offset : Python3 # WRITING OPERATIONS# creates a file named emails.txtfhand = open("emails.txt", "w") # this enters the values into the filefhand.write('''stephen.marquard@uct.ac.zastephen.marquard@uct.ac.zalouis@media.berkeley.edulouis@media.berkeley.edulouis@media.berkeley.edulouis@media.berkeley.eduray@media.berkeley.eduray@media.berkeley.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.edu''') # closing the filefhand.close() This creates a file “emails.txt” and fills it with emails. Step 2: Let’s check the content of the emails.txt file that we just created by writing this code : Python3 # opening the file with reading permissionsfhand = open("emails.txt", "r") # print the content of the whole fileprint(fhand.read()) # close the filefhand.close() Output: Step 3: After creating the “emails.txt” file. We read it by opening it once again, this time with reading permissions, This sets an offset named “fhand” to the beginning of the file,i.e., in position 0. We can check that by using this code : Python3 # open the filefhand = open("emails.txt", "r") # check default value of offsetprint(f"The default position of offset is: {fhand.tell()}") Output: The default position of offset is: 0 Step 4: We write a program that asks the user to enter the number of characters they want to see from the beginning of the file. Python3 # reading first nth charactersn = 40characters = fhand.read(n)print(f"First {n} Characters : ", characters) Output: First 40 Characters : stephen.marquard@uct.ac.za stephen.marqu Here I entered to display 40 characters. Step 5: We then check the position of the offset by using the tell() function. We use this code: Python3 # Checking the current offset/positionoffset = fhand.tell()print("Current position of the offset:", offset) Output: Current position of the offset: 41 By covering 40 characters, the offset now acquires the 41st position. Step 6: Now, if we want to change the current position of the offset to any position we want, we can do that using the seek() function. By, passing the position we want the offset to be at, as an argument for the seek function, we can make the offset, jump to that position. We can confirm using this code: Python3 # Repositioning the offset to the beginningoffset = fhand.seek(0)print("Offset after using seek function : ", offset) # closing the filefhand.close() Output: Offset after using seek function : 0 As we can see in the code above, the offset jumps to the beginning of the file as we gave the argument of “0” in the set function. And the offset value as displayed in the output will be : sweetyty sagar0719kumar Picked python-file-handling Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Sep, 2021" }, { "code": null, "e": 57, "s": 28, "text": "Prerequisite: seek(), tell()" }, { "code": null, "e": 473, "s": 57, "text": "Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer within the file. offset is used later on to perform operations within the text file depending on the permissions given, like read, write, etc. " }, { "code": null, "e": 538, "s": 473, "text": "Before starting let recall some basic methods for file handling:" }, { "code": null, "e": 755, "s": 538, "text": "seek(): In Python, seek() function is used to change the position of the File Handle to a given specific position. The file handle is like a cursor, which defines where the data has to be read or written in the file." }, { "code": null, "e": 814, "s": 755, "text": "Syntax: f.seek(offset, from_what), where f is file pointer" }, { "code": null, "e": 910, "s": 814, "text": "Parameters:Offset: Number of positions to move forwardfrom_what: It defines point of reference." }, { "code": null, "e": 1616, "s": 910, "text": "tell(): Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Sometimes it becomes important for us to know the position of the File Handle. tell() method can be used to get the position of File Handle. tell() method returns the current position of the file object. This method takes no parameters and returns an integer value. Initially file pointer points to the beginning of the file(if not opened in append mode). So, the initial value of tell() is zero." }, { "code": null, "e": 1635, "s": 1616, "text": "Syntax : f.tell() " }, { "code": null, "e": 1732, "s": 1635, "text": "Return: This method returns the current position of the file read/write pointer within the file." }, { "code": null, "e": 1762, "s": 1732, "text": "Step 1: Creating a text file." }, { "code": null, "e": 1866, "s": 1762, "text": "Let’s create a text file “emails.txt” containing multiple emails to demonstrate the working of offset :" }, { "code": null, "e": 1874, "s": 1866, "text": "Python3" }, { "code": "# WRITING OPERATIONS# creates a file named emails.txtfhand = open(\"emails.txt\", \"w\") # this enters the values into the filefhand.write('''stephen.marquard@uct.ac.zastephen.marquard@uct.ac.zalouis@media.berkeley.edulouis@media.berkeley.edulouis@media.berkeley.edulouis@media.berkeley.eduray@media.berkeley.eduray@media.berkeley.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.edu''') # closing the filefhand.close()", "e": 2325, "s": 1874, "text": null }, { "code": null, "e": 2384, "s": 2325, "text": "This creates a file “emails.txt” and fills it with emails." }, { "code": null, "e": 2483, "s": 2384, "text": "Step 2: Let’s check the content of the emails.txt file that we just created by writing this code :" }, { "code": null, "e": 2491, "s": 2483, "text": "Python3" }, { "code": "# opening the file with reading permissionsfhand = open(\"emails.txt\", \"r\") # print the content of the whole fileprint(fhand.read()) # close the filefhand.close()", "e": 2653, "s": 2491, "text": null }, { "code": null, "e": 2661, "s": 2653, "text": "Output:" }, { "code": null, "e": 2669, "s": 2661, "text": "Step 3:" }, { "code": null, "e": 2903, "s": 2669, "text": "After creating the “emails.txt” file. We read it by opening it once again, this time with reading permissions, This sets an offset named “fhand” to the beginning of the file,i.e., in position 0. We can check that by using this code :" }, { "code": null, "e": 2911, "s": 2903, "text": "Python3" }, { "code": "# open the filefhand = open(\"emails.txt\", \"r\") # check default value of offsetprint(f\"The default position of offset is: {fhand.tell()}\")", "e": 3049, "s": 2911, "text": null }, { "code": null, "e": 3057, "s": 3049, "text": "Output:" }, { "code": null, "e": 3094, "s": 3057, "text": "The default position of offset is: 0" }, { "code": null, "e": 3223, "s": 3094, "text": "Step 4: We write a program that asks the user to enter the number of characters they want to see from the beginning of the file." }, { "code": null, "e": 3231, "s": 3223, "text": "Python3" }, { "code": "# reading first nth charactersn = 40characters = fhand.read(n)print(f\"First {n} Characters : \", characters)", "e": 3339, "s": 3231, "text": null }, { "code": null, "e": 3347, "s": 3339, "text": "Output:" }, { "code": null, "e": 3411, "s": 3347, "text": "First 40 Characters : stephen.marquard@uct.ac.za\nstephen.marqu" }, { "code": null, "e": 3452, "s": 3411, "text": "Here I entered to display 40 characters." }, { "code": null, "e": 3549, "s": 3452, "text": "Step 5: We then check the position of the offset by using the tell() function. We use this code:" }, { "code": null, "e": 3557, "s": 3549, "text": "Python3" }, { "code": "# Checking the current offset/positionoffset = fhand.tell()print(\"Current position of the offset:\", offset)", "e": 3665, "s": 3557, "text": null }, { "code": null, "e": 3673, "s": 3665, "text": "Output:" }, { "code": null, "e": 3708, "s": 3673, "text": "Current position of the offset: 41" }, { "code": null, "e": 3779, "s": 3708, "text": "By covering 40 characters, the offset now acquires the 41st position. " }, { "code": null, "e": 4086, "s": 3779, "text": "Step 6: Now, if we want to change the current position of the offset to any position we want, we can do that using the seek() function. By, passing the position we want the offset to be at, as an argument for the seek function, we can make the offset, jump to that position. We can confirm using this code:" }, { "code": null, "e": 4094, "s": 4086, "text": "Python3" }, { "code": "# Repositioning the offset to the beginningoffset = fhand.seek(0)print(\"Offset after using seek function : \", offset) # closing the filefhand.close()", "e": 4244, "s": 4094, "text": null }, { "code": null, "e": 4252, "s": 4244, "text": "Output:" }, { "code": null, "e": 4290, "s": 4252, "text": "Offset after using seek function : 0" }, { "code": null, "e": 4479, "s": 4290, "text": "As we can see in the code above, the offset jumps to the beginning of the file as we gave the argument of “0” in the set function. And the offset value as displayed in the output will be :" }, { "code": null, "e": 4488, "s": 4479, "text": "sweetyty" }, { "code": null, "e": 4503, "s": 4488, "text": "sagar0719kumar" }, { "code": null, "e": 4510, "s": 4503, "text": "Picked" }, { "code": null, "e": 4531, "s": 4510, "text": "python-file-handling" }, { "code": null, "e": 4555, "s": 4531, "text": "Technical Scripter 2020" }, { "code": null, "e": 4562, "s": 4555, "text": "Python" }, { "code": null, "e": 4581, "s": 4562, "text": "Technical Scripter" }, { "code": null, "e": 4679, "s": 4581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4711, "s": 4679, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4738, "s": 4711, "text": "Python Classes and Objects" }, { "code": null, "e": 4759, "s": 4738, "text": "Python OOPs Concepts" }, { "code": null, "e": 4782, "s": 4759, "text": "Introduction To PYTHON" }, { "code": null, "e": 4813, "s": 4782, "text": "Python | os.path.join() method" }, { "code": null, "e": 4869, "s": 4813, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4911, "s": 4869, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4953, "s": 4911, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4992, "s": 4953, "text": "Python | Get unique values from a list" } ]
sciPy stats.gmean() function | Python
19 Aug, 2021 scipy.stats.gmean(array, axis=0, dtype=None) calculates the geometric mean of the array elements along the specified axis of the array (list in python). It’s formula – Parameters : array: Input array or object having the elements to calculate the geometric mean. axis: Axis along which the mean is to be computed. By default axis = 0 dtype: It sets the type of returned element.Returns : Geometric mean of the array elements based on the set parameters. Code #1: Python3 # Geometric Mean from scipy.stats.mstats import gmeanarr1 = gmean([1, 3, 27]) print("Geometric Mean is :", arr1) Geometric Mean is : 4.32674871092 Code #2: With multi-dimensional data Python3 # Geometric Mean from scipy.stats.mstats import gmeanarr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print("Geometric Mean is :", gmean(arr1)) # using axis = 0print("\nGeometric Mean is with default axis = 0 : \n", gmean(arr1, axis = 0)) # using axis = 1print("\nGeometric Mean is with default axis = 1 : \n", gmean(arr1, axis = 1)) Geometric Mean is : [ 2.81731325 4.55901411 7.89644408] Geometric Mean is with default axis = 0 : [ 2.81731325 4.55901411 7.89644408] Geometric Mean is with default axis = 1 : [ 4.32674871 4.16016765 5.01329793 5.24148279] anikaseth98 Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2021" }, { "code": null, "e": 198, "s": 28, "text": "scipy.stats.gmean(array, axis=0, dtype=None) calculates the geometric mean of the array elements along the specified axis of the array (list in python). It’s formula – " }, { "code": null, "e": 486, "s": 200, "text": "Parameters : array: Input array or object having the elements to calculate the geometric mean. axis: Axis along which the mean is to be computed. By default axis = 0 dtype: It sets the type of returned element.Returns : Geometric mean of the array elements based on the set parameters." }, { "code": null, "e": 497, "s": 486, "text": "Code #1: " }, { "code": null, "e": 505, "s": 497, "text": "Python3" }, { "code": "# Geometric Mean from scipy.stats.mstats import gmeanarr1 = gmean([1, 3, 27]) print(\"Geometric Mean is :\", arr1)", "e": 619, "s": 505, "text": null }, { "code": null, "e": 653, "s": 619, "text": "Geometric Mean is : 4.32674871092" }, { "code": null, "e": 696, "s": 655, "text": " Code #2: With multi-dimensional data " }, { "code": null, "e": 704, "s": 696, "text": "Python3" }, { "code": "# Geometric Mean from scipy.stats.mstats import gmeanarr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print(\"Geometric Mean is :\", gmean(arr1)) # using axis = 0print(\"\\nGeometric Mean is with default axis = 0 : \\n\", gmean(arr1, axis = 0)) # using axis = 1print(\"\\nGeometric Mean is with default axis = 1 : \\n\", gmean(arr1, axis = 1)) ", "e": 1075, "s": 704, "text": null }, { "code": null, "e": 1311, "s": 1075, "text": "Geometric Mean is : [ 2.81731325 4.55901411 7.89644408]\n\nGeometric Mean is with default axis = 0 : \n [ 2.81731325 4.55901411 7.89644408]\n\nGeometric Mean is with default axis = 1 : \n [ 4.32674871 4.16016765 5.01329793 5.24148279]" }, { "code": null, "e": 1325, "s": 1313, "text": "anikaseth98" }, { "code": null, "e": 1354, "s": 1325, "text": "Python scipy-stats-functions" }, { "code": null, "e": 1367, "s": 1354, "text": "Python-scipy" }, { "code": null, "e": 1374, "s": 1367, "text": "Python" }, { "code": null, "e": 1472, "s": 1374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1490, "s": 1472, "text": "Python Dictionary" }, { "code": null, "e": 1532, "s": 1490, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1554, "s": 1532, "text": "Enumerate() in Python" }, { "code": null, "e": 1589, "s": 1554, "text": "Read a file line by line in Python" }, { "code": null, "e": 1615, "s": 1589, "text": "Python String | replace()" }, { "code": null, "e": 1647, "s": 1615, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1676, "s": 1647, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1703, "s": 1676, "text": "Python Classes and Objects" }, { "code": null, "e": 1733, "s": 1703, "text": "Iterate over a list in Python" } ]
Test Internet Speed using Python
19 Feb, 2020 Prerequisites: Python Programming Language Python is a high-level widely used general-purpose language. Python can be used for many tasks such as web development, machine learning, Gui applications. It can also be used for testing Internet speed. Python provides various libraries for doing the same. One such library is speedtest-cli. This library is a command-line interface for testing internet bandwidth using speedtest.net This module does not come built-in with Python. To install it type the below command in the terminal. pip install speedtest-cli After installing the above package one can check if the package is installed correctly or not by doing the version check. The version of the package can be checked using the following command speedtest-cli --version Speedtest-cli is a module that is used in the command-line interface for testing internet bandwidth using speedtest.net. To get the speed in the megabits type the below command in the terminal. speedtest-cli The above command gives the speed test result is in Megabits. To get the result in Bytes we can use the following command. speedtest-cli --bytes The pictorial version of your speed test result can also be retrieved using this module. To do the same type the below command in the terminal. speedtest-cli --share It returns a link on which we can visit on our browser and see the graphical representation of various kinds of our internet speed. To print a simpler version of the speed test result containing only Ping, Download & Upload results instead of detailed output. speedtest-cli --simple Using Python script to check the internet speed # Python program to test# internet speed import speedtest st = speedtest.Speedtest() option = int(input('''What speed do you want to test: 1) Download Speed 2) Upload Speed 3) Ping Your Choice: ''')) if option == 1: print(st.download()) elif option == 2: print(st.upload()) elif option == 3: servernames =[] st.get_servers(servernames) print(st.results.ping) else: print("Please enter the correct choice !") Output: To get the list of all the available options, type the below command in the terminal. speedtest-cli -h speedtest-cli -h speedtest-cli --help speedtest-cli --help python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2020" }, { "code": null, "e": 95, "s": 52, "text": "Prerequisites: Python Programming Language" }, { "code": null, "e": 480, "s": 95, "text": "Python is a high-level widely used general-purpose language. Python can be used for many tasks such as web development, machine learning, Gui applications. It can also be used for testing Internet speed. Python provides various libraries for doing the same. One such library is speedtest-cli. This library is a command-line interface for testing internet bandwidth using speedtest.net" }, { "code": null, "e": 582, "s": 480, "text": "This module does not come built-in with Python. To install it type the below command in the terminal." }, { "code": null, "e": 609, "s": 582, "text": "pip install speedtest-cli\n" }, { "code": null, "e": 801, "s": 609, "text": "After installing the above package one can check if the package is installed correctly or not by doing the version check. The version of the package can be checked using the following command" }, { "code": null, "e": 826, "s": 801, "text": "speedtest-cli --version\n" }, { "code": null, "e": 1020, "s": 826, "text": "Speedtest-cli is a module that is used in the command-line interface for testing internet bandwidth using speedtest.net. To get the speed in the megabits type the below command in the terminal." }, { "code": null, "e": 1035, "s": 1020, "text": "speedtest-cli\n" }, { "code": null, "e": 1158, "s": 1035, "text": "The above command gives the speed test result is in Megabits. To get the result in Bytes we can use the following command." }, { "code": null, "e": 1181, "s": 1158, "text": "speedtest-cli --bytes\n" }, { "code": null, "e": 1325, "s": 1181, "text": "The pictorial version of your speed test result can also be retrieved using this module. To do the same type the below command in the terminal." }, { "code": null, "e": 1348, "s": 1325, "text": "speedtest-cli --share\n" }, { "code": null, "e": 1480, "s": 1348, "text": "It returns a link on which we can visit on our browser and see the graphical representation of various kinds of our internet speed." }, { "code": null, "e": 1608, "s": 1480, "text": "To print a simpler version of the speed test result containing only Ping, Download & Upload results instead of detailed output." }, { "code": null, "e": 1632, "s": 1608, "text": "speedtest-cli --simple\n" }, { "code": null, "e": 1680, "s": 1632, "text": "Using Python script to check the internet speed" }, { "code": "# Python program to test# internet speed import speedtest st = speedtest.Speedtest() option = int(input('''What speed do you want to test: 1) Download Speed 2) Upload Speed 3) Ping Your Choice: ''')) if option == 1: print(st.download()) elif option == 2: print(st.upload()) elif option == 3: servernames =[] st.get_servers(servernames) print(st.results.ping) else: print(\"Please enter the correct choice !\") ", "e": 2158, "s": 1680, "text": null }, { "code": null, "e": 2166, "s": 2158, "text": "Output:" }, { "code": null, "e": 2252, "s": 2166, "text": "To get the list of all the available options, type the below command in the terminal." }, { "code": null, "e": 2269, "s": 2252, "text": "speedtest-cli -h" }, { "code": null, "e": 2286, "s": 2269, "text": "speedtest-cli -h" }, { "code": null, "e": 2307, "s": 2286, "text": "speedtest-cli --help" }, { "code": null, "e": 2328, "s": 2307, "text": "speedtest-cli --help" }, { "code": null, "e": 2343, "s": 2328, "text": "python-modules" }, { "code": null, "e": 2350, "s": 2343, "text": "Python" }, { "code": null, "e": 2448, "s": 2350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2466, "s": 2448, "text": "Python Dictionary" }, { "code": null, "e": 2508, "s": 2466, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2530, "s": 2508, "text": "Enumerate() in Python" }, { "code": null, "e": 2556, "s": 2530, "text": "Python String | replace()" }, { "code": null, "e": 2588, "s": 2556, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2617, "s": 2588, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2644, "s": 2617, "text": "Python Classes and Objects" }, { "code": null, "e": 2674, "s": 2644, "text": "Iterate over a list in Python" }, { "code": null, "e": 2695, "s": 2674, "text": "Python OOPs Concepts" } ]
Check if a given array contains duplicate elements within k distance from each other
27 Jun, 2022 Given an unsorted array that may contain duplicates. Also given a number k which is smaller than size of array. Write a function that returns true if array contains duplicates within k distance.Examples: Input: k = 3, arr[] = {1, 2, 3, 4, 1, 2, 3, 4} Output: false All duplicates are more than k distance away. Input: k = 3, arr[] = {1, 2, 3, 1, 4, 5} Output: true 1 is repeated at distance 3. Input: k = 3, arr[] = {1, 2, 3, 4, 5} Output: false Input: k = 3, arr[] = {1, 2, 3, 4, 4} Output: true A Simple Solution is to run two loops. The outer loop picks every element ‘arr[i]’ as a starting element, the inner loop compares all elements which are within k distance of ‘arr[i]’. The time complexity of this solution is O(kn). Implementation: C++ Java C# #include <bits/stdc++.h>using namespace std; /* C++ program to Check if a given array contains duplicate elements within k distance from each other */bool checkDuplicatesWithinK(int arr[], int n, int k){ // traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // searching in next k-1 elements if its duplicate // is present or not while (range > 0 and j < n) { if (arr[i] == arr[j]) return true; j++; range--; } } return false;} // Driver method to test above methodint main(){ int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkDuplicatesWithinK(arr, n, 3)) cout << "Yes"; else cout << "No";} // This article is contributed by Arpit Jain public class GFG{ /* Java program to Check if a given array contains duplicate elements within k distance from each other */ public static boolean checkDuplicatesWithinK(int[] arr, int n, int k) { // traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // searching in next k-1 elements if its // duplicate is present or not while (range > 0 && j < n) { if (arr[i] == arr[j]) { return true; } j++; range--; } } return false; } // Driver method to test above method public static void main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.length; if (checkDuplicatesWithinK(arr, n, 3)) { System.out.print("Yes"); } else { System.out.print("No"); } }} // This article is contributed by Aarti_Rathi /* C# program to Check if a givenarray contains duplicate elementswithin k distance from each other */using System;using System.Collections.Generic; class GFG { static bool checkDuplicatesWithinK(int[] arr, int n, int k) { // traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // searching in next k-1 elements if its // duplicate is present or not while (range > 0 && j < n) { if (arr[i] == arr[j]) return true; j++; range--; } } return false; } // Driver code public static void Main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; if (checkDuplicatesWithinK(arr, n, 3)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code has been contributed by Aarti_Rathi Yes We can solve this problem in Θ(n) time using Hashing. The idea is to one by add elements to hash. We also remove elements which are at more than k distance from current element. Following is detailed algorithm. Create an empty hashtable. Traverse all elements from left from right. Let the current element be ‘arr[i]’ If current element ‘arr[i]’ is present in hashtable, then return true. Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k Create an empty hashtable. Traverse all elements from left from right. Let the current element be ‘arr[i]’ If current element ‘arr[i]’ is present in hashtable, then return true. Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k If current element ‘arr[i]’ is present in hashtable, then return true. Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k Implementation: C++ Java Python 3 C# Javascript #include<bits/stdc++.h>using namespace std; /* C++ program to Check if a given array contains duplicate elements within k distance from each other */bool checkDuplicatesWithinK(int arr[], int n, int k){ // Creates an empty hashset unordered_set<int> myset; // Traverse the input array for (int i = 0; i < n; i++) { // If already present n hash, then we found // a duplicate within k distance if (myset.find(arr[i]) != myset.end()) return true; // Add this item to hashset myset.insert(arr[i]); // Remove the k+1 distant item if (i >= k) myset.erase(arr[i-k]); } return false;} // Driver method to test above methodint main (){ int arr[] = {10, 5, 3, 4, 3, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); if (checkDuplicatesWithinK(arr, n, 3)) cout << "Yes"; else cout << "No";} //This article is contributed by Chhavi /* Java program to Check if a given array contains duplicate elements within k distance from each other */import java.util.*; class Main{ static boolean checkDuplicatesWithinK(int arr[], int k) { // Creates an empty hashset HashSet<Integer> set = new HashSet<>(); // Traverse the input array for (int i=0; i<arr.length; i++) { // If already present n hash, then we found // a duplicate within k distance if (set.contains(arr[i])) return true; // Add this item to hashset set.add(arr[i]); // Remove the k+1 distant item if (i >= k) set.remove(arr[i-k]); } return false; } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 5, 3, 4, 3, 5, 6}; if (checkDuplicatesWithinK(arr, 3)) System.out.println("Yes"); else System.out.println("No"); }} # Python 3 program to Check if a given array# contains duplicate elements within k distance# from each otherdef checkDuplicatesWithinK(arr, n, k): # Creates an empty list myset = [] # Traverse the input array for i in range(n): # If already present n hash, then we # found a duplicate within k distance if arr[i] in myset: return True # Add this item to hashset myset.append(arr[i]) # Remove the k+1 distant item if (i >= k): myset.remove(arr[i - k]) return False # Driver Codeif __name__ == "__main__": arr = [10, 5, 3, 4, 3, 5, 6] n = len(arr) if (checkDuplicatesWithinK(arr, n, 3)): print("Yes") else: print("No") # This code is contributed by ita_c /* C# program to Check if a givenarray contains duplicate elementswithin k distance from each other */using System;using System.Collections.Generic; class GFG{ static bool checkDuplicatesWithinK(int []arr, int k) { // Creates an empty hashset HashSet<int> set = new HashSet<int>(); // Traverse the input array for (int i = 0; i < arr.Length; i++) { // If already present n hash, then we found // a duplicate within k distance if (set.Contains(arr[i])) return true; // Add this item to hashset set.Add(arr[i]); // Remove the k+1 distant item if (i >= k) set.Remove(arr[i - k]); } return false; } // Driver code public static void Main (String[] args) { int []arr = {10, 5, 3, 4, 3, 5, 6}; if (checkDuplicatesWithinK(arr, 3)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code has been contributed// by 29AjayKumar <script> /* Javascript program to Check if a given array contains duplicate elements within k distance from each other */ function checkDuplicatesWithinK(arr, n, k) { // Creates an empty hashset let myset = []; // Traverse the input array for(let i=0;i<n;i++) { // If already present n hash, then we found // a duplicate within k distance if(arr.includes(arr[i])) { return true; } // Add this item to hashset myset.add(arr[i]); // Remove the k+1 distant item if (i >= k) { index = array.indexOf(arr[i - k]); array.splice(index, 1); } } return false; } // Driver method to test above method let arr = [10, 5, 3, 4, 3, 5, 6]; let n= arr.length; if (checkDuplicatesWithinK(arr, n, 3)) { document.write("Yes"); } else { document.write("No"); } // This code is contributed by rag2127 </script> Yes Check if a given array contains duplicate elements within k distance from each other | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersCheck if a given array contains duplicate elements within k distance from each other | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hzRo7dLtQHs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Anuj. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp 29AjayKumar rag2127 111arpit1 codewithrathi hardikkoriintern codewithmini Amazon Arrays Hash Amazon Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jun, 2022" }, { "code": null, "e": 257, "s": 52, "text": "Given an unsorted array that may contain duplicates. Also given a number k which is smaller than size of array. Write a function that returns true if array contains duplicates within k distance.Examples: " }, { "code": null, "e": 553, "s": 257, "text": "Input: k = 3, arr[] = {1, 2, 3, 4, 1, 2, 3, 4}\nOutput: false\nAll duplicates are more than k distance away.\n\nInput: k = 3, arr[] = {1, 2, 3, 1, 4, 5}\nOutput: true\n1 is repeated at distance 3.\n\nInput: k = 3, arr[] = {1, 2, 3, 4, 5}\nOutput: false\n\nInput: k = 3, arr[] = {1, 2, 3, 4, 4}\nOutput: true" }, { "code": null, "e": 785, "s": 553, "text": "A Simple Solution is to run two loops. The outer loop picks every element ‘arr[i]’ as a starting element, the inner loop compares all elements which are within k distance of ‘arr[i]’. The time complexity of this solution is O(kn). " }, { "code": null, "e": 801, "s": 785, "text": "Implementation:" }, { "code": null, "e": 805, "s": 801, "text": "C++" }, { "code": null, "e": 810, "s": 805, "text": "Java" }, { "code": null, "e": 813, "s": 810, "text": "C#" }, { "code": "#include <bits/stdc++.h>using namespace std; /* C++ program to Check if a given array contains duplicate elements within k distance from each other */bool checkDuplicatesWithinK(int arr[], int n, int k){ // traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // searching in next k-1 elements if its duplicate // is present or not while (range > 0 and j < n) { if (arr[i] == arr[j]) return true; j++; range--; } } return false;} // Driver method to test above methodint main(){ int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkDuplicatesWithinK(arr, n, 3)) cout << \"Yes\"; else cout << \"No\";} // This article is contributed by Arpit Jain", "e": 1652, "s": 813, "text": null }, { "code": "public class GFG{ /* Java program to Check if a given array contains duplicate elements within k distance from each other */ public static boolean checkDuplicatesWithinK(int[] arr, int n, int k) { // traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // searching in next k-1 elements if its // duplicate is present or not while (range > 0 && j < n) { if (arr[i] == arr[j]) { return true; } j++; range--; } } return false; } // Driver method to test above method public static void main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.length; if (checkDuplicatesWithinK(arr, n, 3)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); } }} // This article is contributed by Aarti_Rathi", "e": 2526, "s": 1652, "text": null }, { "code": "/* C# program to Check if a givenarray contains duplicate elementswithin k distance from each other */using System;using System.Collections.Generic; class GFG { static bool checkDuplicatesWithinK(int[] arr, int n, int k) { // traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // searching in next k-1 elements if its // duplicate is present or not while (range > 0 && j < n) { if (arr[i] == arr[j]) return true; j++; range--; } } return false; } // Driver code public static void Main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; if (checkDuplicatesWithinK(arr, n, 3)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code has been contributed by Aarti_Rathi", "e": 3538, "s": 2526, "text": null }, { "code": null, "e": 3542, "s": 3538, "text": "Yes" }, { "code": null, "e": 3753, "s": 3542, "text": "We can solve this problem in Θ(n) time using Hashing. The idea is to one by add elements to hash. We also remove elements which are at more than k distance from current element. Following is detailed algorithm." }, { "code": null, "e": 4020, "s": 3753, "text": "Create an empty hashtable. Traverse all elements from left from right. Let the current element be ‘arr[i]’ If current element ‘arr[i]’ is present in hashtable, then return true. Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k" }, { "code": null, "e": 4048, "s": 4020, "text": "Create an empty hashtable. " }, { "code": null, "e": 4288, "s": 4048, "text": "Traverse all elements from left from right. Let the current element be ‘arr[i]’ If current element ‘arr[i]’ is present in hashtable, then return true. Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k" }, { "code": null, "e": 4360, "s": 4288, "text": "If current element ‘arr[i]’ is present in hashtable, then return true. " }, { "code": null, "e": 4449, "s": 4360, "text": "Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k" }, { "code": null, "e": 4465, "s": 4449, "text": "Implementation:" }, { "code": null, "e": 4469, "s": 4465, "text": "C++" }, { "code": null, "e": 4474, "s": 4469, "text": "Java" }, { "code": null, "e": 4483, "s": 4474, "text": "Python 3" }, { "code": null, "e": 4486, "s": 4483, "text": "C#" }, { "code": null, "e": 4497, "s": 4486, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; /* C++ program to Check if a given array contains duplicate elements within k distance from each other */bool checkDuplicatesWithinK(int arr[], int n, int k){ // Creates an empty hashset unordered_set<int> myset; // Traverse the input array for (int i = 0; i < n; i++) { // If already present n hash, then we found // a duplicate within k distance if (myset.find(arr[i]) != myset.end()) return true; // Add this item to hashset myset.insert(arr[i]); // Remove the k+1 distant item if (i >= k) myset.erase(arr[i-k]); } return false;} // Driver method to test above methodint main (){ int arr[] = {10, 5, 3, 4, 3, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); if (checkDuplicatesWithinK(arr, n, 3)) cout << \"Yes\"; else cout << \"No\";} //This article is contributed by Chhavi", "e": 5435, "s": 4497, "text": null }, { "code": "/* Java program to Check if a given array contains duplicate elements within k distance from each other */import java.util.*; class Main{ static boolean checkDuplicatesWithinK(int arr[], int k) { // Creates an empty hashset HashSet<Integer> set = new HashSet<>(); // Traverse the input array for (int i=0; i<arr.length; i++) { // If already present n hash, then we found // a duplicate within k distance if (set.contains(arr[i])) return true; // Add this item to hashset set.add(arr[i]); // Remove the k+1 distant item if (i >= k) set.remove(arr[i-k]); } return false; } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 5, 3, 4, 3, 5, 6}; if (checkDuplicatesWithinK(arr, 3)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 6440, "s": 5435, "text": null }, { "code": "# Python 3 program to Check if a given array# contains duplicate elements within k distance# from each otherdef checkDuplicatesWithinK(arr, n, k): # Creates an empty list myset = [] # Traverse the input array for i in range(n): # If already present n hash, then we # found a duplicate within k distance if arr[i] in myset: return True # Add this item to hashset myset.append(arr[i]) # Remove the k+1 distant item if (i >= k): myset.remove(arr[i - k]) return False # Driver Codeif __name__ == \"__main__\": arr = [10, 5, 3, 4, 3, 5, 6] n = len(arr) if (checkDuplicatesWithinK(arr, n, 3)): print(\"Yes\") else: print(\"No\") # This code is contributed by ita_c", "e": 7219, "s": 6440, "text": null }, { "code": "/* C# program to Check if a givenarray contains duplicate elementswithin k distance from each other */using System;using System.Collections.Generic; class GFG{ static bool checkDuplicatesWithinK(int []arr, int k) { // Creates an empty hashset HashSet<int> set = new HashSet<int>(); // Traverse the input array for (int i = 0; i < arr.Length; i++) { // If already present n hash, then we found // a duplicate within k distance if (set.Contains(arr[i])) return true; // Add this item to hashset set.Add(arr[i]); // Remove the k+1 distant item if (i >= k) set.Remove(arr[i - k]); } return false; } // Driver code public static void Main (String[] args) { int []arr = {10, 5, 3, 4, 3, 5, 6}; if (checkDuplicatesWithinK(arr, 3)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code has been contributed// by 29AjayKumar", "e": 8277, "s": 7219, "text": null }, { "code": "<script> /* Javascript program to Check if a given array contains duplicate elements within k distance from each other */ function checkDuplicatesWithinK(arr, n, k) { // Creates an empty hashset let myset = []; // Traverse the input array for(let i=0;i<n;i++) { // If already present n hash, then we found // a duplicate within k distance if(arr.includes(arr[i])) { return true; } // Add this item to hashset myset.add(arr[i]); // Remove the k+1 distant item if (i >= k) { index = array.indexOf(arr[i - k]); array.splice(index, 1); } } return false; } // Driver method to test above method let arr = [10, 5, 3, 4, 3, 5, 6]; let n= arr.length; if (checkDuplicatesWithinK(arr, n, 3)) { document.write(\"Yes\"); } else { document.write(\"No\"); } // This code is contributed by rag2127 </script>", "e": 9381, "s": 8277, "text": null }, { "code": null, "e": 9385, "s": 9381, "text": "Yes" }, { "code": null, "e": 10371, "s": 9385, "text": "Check if a given array contains duplicate elements within k distance from each other | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersCheck if a given array contains duplicate elements within k distance from each other | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hzRo7dLtQHs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 10533, "s": 10371, "text": "This article is contributed by Anuj. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10539, "s": 10533, "text": "ukasp" }, { "code": null, "e": 10551, "s": 10539, "text": "29AjayKumar" }, { "code": null, "e": 10559, "s": 10551, "text": "rag2127" }, { "code": null, "e": 10569, "s": 10559, "text": "111arpit1" }, { "code": null, "e": 10583, "s": 10569, "text": "codewithrathi" }, { "code": null, "e": 10600, "s": 10583, "text": "hardikkoriintern" }, { "code": null, "e": 10613, "s": 10600, "text": "codewithmini" }, { "code": null, "e": 10620, "s": 10613, "text": "Amazon" }, { "code": null, "e": 10627, "s": 10620, "text": "Arrays" }, { "code": null, "e": 10632, "s": 10627, "text": "Hash" }, { "code": null, "e": 10639, "s": 10632, "text": "Amazon" }, { "code": null, "e": 10646, "s": 10639, "text": "Arrays" }, { "code": null, "e": 10651, "s": 10646, "text": "Hash" } ]
Using Plotly for Interactive Data Visualization in Python
07 Dec, 2021 Plotly is an open-source module of Python which is used for data visualization and supports various graphs like line charts, scatter plots, bar charts, histograms, area plot, etc. In this article, we will see how to plot a basic chart with plotly and also how to make a plot interactive. But before starting you might be wondering why there is a need to learn plotly, so let’s have a look at it. Plotly uses javascript behind the scenes and is used to make interactive plots where we can zoom in on the graph or add additional information like data on hover and many more things. Let’s see few more advantages of plotly – Plotly has hover tool capabilities that allow us to detect any outliers or anomalies in a large number of data points. It is visually attractive that can be accepted by a wide range of audiences. It allows us for the endless customization of our graphs that makes our plot more meaningful and understandable for others. Plotly does not come built-in with Python. To install it type the below command in the terminal. pip install plotly plotly installation image widget in Plotly, there are three main modules – plotly.plotly acts as the interface between the local machine and Plotly. It contains functions that require a response from Plotly’s server. plotly.graph_objects module contains the objects (Figure, layout, data, and the definition of the plots like scatter plot, line chart) that are responsible for creating the plots. The Figure can be represented either as dict or instances of plotly.graph_objects.Figure and these are serialized as JSON before it gets passed to plotly.js. Figures are represented as trees where the root node has three top layer attributes – data, layout, and frames and the named nodes called ‘attributes’. Note: plotly.express module can create the entire Figure at once. It uses the graph_objects internally and returns the graph_objects.Figure instance. Example: Python3 import plotly.express as px # Creating the Figure instancefig = px.line(x=[1, 2], y=[3, 4]) # printing the figure instanceprint(fig) Output: plotly.tools module contains various tools in the forms of the functions that can enhance the Plotly experience. After going through the basics of plotly let’s see how to create some basic charts using plotly. A line chart is one of the simple plots where a line is drawn to shoe relation between the X-axis and Y-axis. It can be created using the px.line() method with each data position is represented as a vertex (which location is given by the x and y columns) of a polyline mark in 2D space. Syntax: Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None) Example: Python3 import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y="sepal_width",) # showing the plotfig.show() Output: In the above example, we can see that – The labels to the x-axis and y-axis have given automatically by plotly. The data of the x-axis and y-axis is shown on hover. We can also select a part of the data according to our needs and can also zoom out. Plotly also provides a set of tools (seen on the top right corner) to interact with every chart. Poltly also allows us to save the graph locally in a static format. Now let’s try to customize our graph a little. Example 1: In this example, we will use the line dash parameter which is used to group the lines according to the dataframe column passed. Python3 import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y="sepal_width", line_group='species') # showing the plotfig.show() Output: Example 2: In this example, we will group and color the data according to the species. We will also change the line format. For this we will use two attributes such – line_dash and color. Python3 import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y="sepal_width", line_dash='species', color='species') # showing the plotfig.show() Output: A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. In other words, it is the pictorial representation of dataset. These data sets contain the numerical values of variables that represent the length or height. It can be created using the px.bar() method. Syntax: plotly.express.bar(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, hover_name=None, hover_data=None, custom_data=None, text=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, title=None, template=None, width=None, height=None, **kwargs) Example: Python3 import plotly.express as px # Loading the datadf = px.data.tips() # Creating the bar chartfig = px.bar(df, x='day', y="total_bill") fig.show() Output: Let’s try to customize this plot. Customizations that we will use – color: Used to color the bars. facet_row: Divides the graph into rows according to the data passed facet_col: Divides the graph into columns according to the data passed Example: Python3 import plotly.express as px # Loading the datadf = px.data.tips() # Creating the bar chartfig = px.bar(df, x='day', y="total_bill", color='sex', facet_row='time', facet_col='sex') fig.show() Output: A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them. it can be created using the px.scatter() method. Syntax: plotly.express.scatter(data_frame=None, x=None, y=None, color=None, symbol=None, size=None, hover_name=None, hover_data=None, facet_row=None, facet_col=None, facet_col_wrap=0, opacity=None, title=None, template=None, width=None, height=None, **kwargs) Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the scatter chartfig = px.scatter(df, x='total_bill', y="tip") # showing the plotfig.show() Output: Let’s see various customizations available for this chart that we will use – color: Color the points. symbol: Gives a symbol to each point according to the data passed. size: The size for each point. Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the scatter chartfig = px.scatter(df, x='total_bill', y="tip", color='time', symbol='sex', size='size', facet_row='day', facet_col='time') # showing the plotfig.show() Output: A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. It can be created using the px.histogram() method. Syntax: plotly.express.histogram(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, barnorm=None, histnorm=None, nbins=None, title=None, template=None, width=None, height=None) Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the histogramfig = px.histogram(df, x="total_bill") # showing the plotfig.show() Output: Let’s customize the above graph. Customizations that we will be using are – color: To color the bars nbins: To set the number of bins histnorm: Mode through which the bins are represented. Different values that can be passed using this argument are-percent or probability: The output of histfunc for a given bin is divided by the sum of the output of histfunc for all bins.density: The output of histfunc for a given bin is divided by the size of the bin.probability density: The output of histfunc for a given bin is normalized such that it corresponds to the probability that a random percent or probability: The output of histfunc for a given bin is divided by the sum of the output of histfunc for all bins. density: The output of histfunc for a given bin is divided by the size of the bin. probability density: The output of histfunc for a given bin is normalized such that it corresponds to the probability that a random barmode: Can be either ‘group’, ‘overlay’ or ‘relative’.group: Bars are stacked above zero for positive values and below zero for negative valuesoverlay: Bars are drawn on the top of each othergroup: Bars are placed beside each other. group: Bars are stacked above zero for positive values and below zero for negative values overlay: Bars are drawn on the top of each other group: Bars are placed beside each other. Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the histogramfig = px.histogram(df, x="total_bill", color='sex', nbins=50, histnorm='percent', barmode='overlay') # showing the plotfig.show() Output: A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. A circular chart cuts in a form of radii into segments describing relative frequencies or magnitude also known as a circle graph. It can be created using the px.pie() method. Syntax: plotly.express.pie(data_frame=None, names=None, values=None, color=None, color_discrete_sequence=None, color_discrete_map={}, hover_name=None, hover_data=None, custom_data=None, labels={}, title=None, template=None, width=None, height=None, opacity=None, hole=None) Example: Python3 import plotly.express as px # Loading the iris datasetdf = px.data.tips() fig = px.pie(df, values="total_bill", names="day")fig.show() Output: Let’s customize the above graph. Customizations that we will be using are – color_discrete_sequence: Strings defining valid CSS colors opacity: Opacity for markers. The value should be between 0 and 1 hole: Creates a hole in between to make it a donut chart. The value should be between 0 and 1 Example: Python3 import plotly.express as px # Loading the iris datasetdf = px.data.tips() fig = px.pie(df, values="total_bill", names="day", color_discrete_sequence=px.colors.sequential.RdBu, opacity=0.7, hole=0.5)fig.show() Output: A Box Plot is also known as Whisker plot is created to display the summary of the set of data values having properties like minimum, first quartile, median, third quartile and maximum. In the box plot, a box is created from the first quartile to the third quartile, a vertical line is also there which goes through the box at the median. Here x-axis denotes the data to be plotted while the y-axis shows the frequency distribution. It can be created using the px.box() method Syntax: plotly.express.box(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, title=None, template=None, width=None, height=None, **kwargs) Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the boxplotfig = px.box(df, x="day", y="tip") # showing the plotfig.show() Output: Let’s see various customizations that can be used on boxplots – color: used to assign color to marks facet_row: assign marks to facetted subplots in the vertical direction facet_col: assign marks to facetted subplots in the horizontal direction boxmode: One of ‘group’ or ‘overlay’ In ‘overlay’ mode, boxes are on drawn top of one another. In ‘group’ mode, boxes are placed beside each other. notched: If True, boxes are drawn with notches Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the boxplotfig = px.box(df, x="day", y="tip", color='sex', facet_row='time', boxmode='group', notched=True) # showing the plotfig.show() Output: Violin Plot is a method to visualize the distribution of numerical data of different variables. It is similar to Box Plot but with a rotated plot on each side, giving more information about the density estimate on the y-axis. The density is mirrored and flipped over and the resulting shape is filled in, creating an image resembling a violin. The advantage of a violin plot is that it can show nuances in the distribution that aren’t perceptible in a boxplot. On the other hand, the boxplot more clearly shows the outliers in the data. It can be created using the px.violin() method. Syntax: violin(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None, **kwargs) Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the violin plotfig = px.violin(df, x="day", y="tip") # showing the plotfig.show() Output: For customizing the violin plot we will use the same customizations available for the box plot except the boxmode and notched which are not available for the violin plot. We will also the box parameter. Setting this parameter to True will show a box plot inside the violin plot. Example: Python3 import plotly.express as px # using the datasetdf = px.data.tips() # plotting the violin plotfig = px.violin(df, x="day", y="tip", color='sex', facet_row='time', box=True) # showing the plotfig.show() Output: 3D Scatter Plot can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. All the parameter control visual semantic which are used to identify the different subsets. Using redundant semantics can be helpful for making graphics more accessible. It can be created using the scatter_3d function of plotly.express class. Syntax: plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None, **kwargs) Example: Python3 import plotly.express as px # data to be plotteddf = px.data.tips() # plotting the figurefig = px.scatter_3d(df, x="total_bill", y="sex", z="tip") fig.show() Output: Customizing the 3D scatter plot. We will use the following customization – color: Set the color of the markers size: Set the size of the marker symbol: Set the symbol of the plot Example: Python3 import plotly.express as px # data to be plotteddf = px.data.tips() # plotting the figurefig = px.scatter_3d(df, x="total_bill", y="sex", z="tip", color='day', size='total_bill', symbol='time') fig.show() Output: Every graph created by the plotly provides various interactions, where we can select a part of the plot, we get information on hovering over the plot, and also a toolbar is also created with every plot that can many tasks like saving the plot locally or zooming in and out, etc. Besides all these plotly allows us to add more tools like dropdowns, buttons, sliders, etc. These can be created using the update menu attribute of the plot layout. Let’s see how to do all such things in detail. A drop-down menu is a part of the menu button which is displayed on a screen all the time. Every menu button is associated with a Menu widget that can display the choices for that menu button when clicked on it. In plotly, there are 4 possible methods to modify the charts by using update menu method. restyle: modify data or data attributes relayout: modify layout attributes update: modify data and layout attributes animate: start or pause an animation Example: Python3 import plotly.graph_objects as pximport numpy as npimport pandas as pd df = pd.read_csv('tips.csv') plot = px.Figure(data=[px.Scatter( x=df['day'], y=df['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict(buttons=list([ dict( args=["type", "scatter"], label="Scatter Plot", method="restyle" ), dict( args=["type", "bar"], label="Bar Chart", method="restyle" ) ]), direction="down", ), ]) plot.show() Output: In plotly, actions custom Buttons are used to quickly make actions directly from a record. Custom Buttons can be added to page layouts in CRM, Marketing, and Custom Apps. There are also 4 possible methods that can be applied in custom buttons: restyle: modify data or data attributes relayout: modify layout attributes update: modify data and layout attributes animate: start or pause an animation Example: Python3 import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv("tips.csv") plot = px.Figure(data=[px.Scatter( x=data['day'], y=data['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict( args=["type", "scatter"], label="Scatter Plot", method="restyle" ), dict( args=["type", "bar"], label="Bar Chart", method="restyle" ) ]), ), ]) plot.show() Output: In plotly, the range slider is a custom range-type input control. It allows selecting a value or a range of values between a specified minimum and maximum range. And the range selector is a tool for selecting ranges to display within the chart. It provides buttons to select pre-configured ranges in the chart. It also provides input boxes where the minimum and maximum dates can be manually input. Example: Python3 import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['tip'] plot = px.Figure(data=[px.Scatter( x=x, y=y, mode='markers',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step="day", stepmode="backward"), ]) ), rangeslider=dict( visible=True ), )) plot.show() Output: sumitgumber28 abhishek0719kadiyan as5853535 kk773572498 Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Dec, 2021" }, { "code": null, "e": 450, "s": 54, "text": "Plotly is an open-source module of Python which is used for data visualization and supports various graphs like line charts, scatter plots, bar charts, histograms, area plot, etc. In this article, we will see how to plot a basic chart with plotly and also how to make a plot interactive. But before starting you might be wondering why there is a need to learn plotly, so let’s have a look at it." }, { "code": null, "e": 676, "s": 450, "text": "Plotly uses javascript behind the scenes and is used to make interactive plots where we can zoom in on the graph or add additional information like data on hover and many more things. Let’s see few more advantages of plotly –" }, { "code": null, "e": 795, "s": 676, "text": "Plotly has hover tool capabilities that allow us to detect any outliers or anomalies in a large number of data points." }, { "code": null, "e": 872, "s": 795, "text": "It is visually attractive that can be accepted by a wide range of audiences." }, { "code": null, "e": 996, "s": 872, "text": "It allows us for the endless customization of our graphs that makes our plot more meaningful and understandable for others." }, { "code": null, "e": 1093, "s": 996, "text": "Plotly does not come built-in with Python. To install it type the below command in the terminal." }, { "code": null, "e": 1112, "s": 1093, "text": "pip install plotly" }, { "code": null, "e": 1145, "s": 1112, "text": "plotly installation image widget" }, { "code": null, "e": 1188, "s": 1145, "text": "in Plotly, there are three main modules – " }, { "code": null, "e": 1330, "s": 1188, "text": "plotly.plotly acts as the interface between the local machine and Plotly. It contains functions that require a response from Plotly’s server." }, { "code": null, "e": 1820, "s": 1330, "text": "plotly.graph_objects module contains the objects (Figure, layout, data, and the definition of the plots like scatter plot, line chart) that are responsible for creating the plots. The Figure can be represented either as dict or instances of plotly.graph_objects.Figure and these are serialized as JSON before it gets passed to plotly.js. Figures are represented as trees where the root node has three top layer attributes – data, layout, and frames and the named nodes called ‘attributes’." }, { "code": null, "e": 1970, "s": 1820, "text": "Note: plotly.express module can create the entire Figure at once. It uses the graph_objects internally and returns the graph_objects.Figure instance." }, { "code": null, "e": 1979, "s": 1970, "text": "Example:" }, { "code": null, "e": 1987, "s": 1979, "text": "Python3" }, { "code": "import plotly.express as px # Creating the Figure instancefig = px.line(x=[1, 2], y=[3, 4]) # printing the figure instanceprint(fig)", "e": 2124, "s": 1987, "text": null }, { "code": null, "e": 2132, "s": 2124, "text": "Output:" }, { "code": null, "e": 2245, "s": 2132, "text": "plotly.tools module contains various tools in the forms of the functions that can enhance the Plotly experience." }, { "code": null, "e": 2342, "s": 2245, "text": "After going through the basics of plotly let’s see how to create some basic charts using plotly." }, { "code": null, "e": 2630, "s": 2342, "text": "A line chart is one of the simple plots where a line is drawn to shoe relation between the X-axis and Y-axis. It can be created using the px.line() method with each data position is represented as a vertex (which location is given by the x and y columns) of a polyline mark in 2D space." }, { "code": null, "e": 2638, "s": 2630, "text": "Syntax:" }, { "code": null, "e": 2830, "s": 2638, "text": "Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None)" }, { "code": null, "e": 2839, "s": 2830, "text": "Example:" }, { "code": null, "e": 2847, "s": 2839, "text": "Python3" }, { "code": "import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y=\"sepal_width\",) # showing the plotfig.show()", "e": 3012, "s": 2847, "text": null }, { "code": null, "e": 3020, "s": 3012, "text": "Output:" }, { "code": null, "e": 3061, "s": 3020, "text": "In the above example, we can see that – " }, { "code": null, "e": 3133, "s": 3061, "text": "The labels to the x-axis and y-axis have given automatically by plotly." }, { "code": null, "e": 3186, "s": 3133, "text": "The data of the x-axis and y-axis is shown on hover." }, { "code": null, "e": 3270, "s": 3186, "text": "We can also select a part of the data according to our needs and can also zoom out." }, { "code": null, "e": 3367, "s": 3270, "text": "Plotly also provides a set of tools (seen on the top right corner) to interact with every chart." }, { "code": null, "e": 3435, "s": 3367, "text": "Poltly also allows us to save the graph locally in a static format." }, { "code": null, "e": 3483, "s": 3435, "text": "Now let’s try to customize our graph a little. " }, { "code": null, "e": 3622, "s": 3483, "text": "Example 1: In this example, we will use the line dash parameter which is used to group the lines according to the dataframe column passed." }, { "code": null, "e": 3630, "s": 3622, "text": "Python3" }, { "code": "import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y=\"sepal_width\", line_group='species') # showing the plotfig.show()", "e": 3816, "s": 3630, "text": null }, { "code": null, "e": 3824, "s": 3816, "text": "Output:" }, { "code": null, "e": 4012, "s": 3824, "text": "Example 2: In this example, we will group and color the data according to the species. We will also change the line format. For this we will use two attributes such – line_dash and color." }, { "code": null, "e": 4020, "s": 4012, "text": "Python3" }, { "code": "import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y=\"sepal_width\", line_dash='species', color='species') # showing the plotfig.show()", "e": 4235, "s": 4020, "text": null }, { "code": null, "e": 4243, "s": 4235, "text": "Output:" }, { "code": null, "e": 4621, "s": 4243, "text": "A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. In other words, it is the pictorial representation of dataset. These data sets contain the numerical values of variables that represent the length or height. It can be created using the px.bar() method." }, { "code": null, "e": 4629, "s": 4621, "text": "Syntax:" }, { "code": null, "e": 4936, "s": 4629, "text": "plotly.express.bar(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, hover_name=None, hover_data=None, custom_data=None, text=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, title=None, template=None, width=None, height=None, **kwargs)" }, { "code": null, "e": 4945, "s": 4936, "text": "Example:" }, { "code": null, "e": 4953, "s": 4945, "text": "Python3" }, { "code": "import plotly.express as px # Loading the datadf = px.data.tips() # Creating the bar chartfig = px.bar(df, x='day', y=\"total_bill\") fig.show()", "e": 5099, "s": 4953, "text": null }, { "code": null, "e": 5107, "s": 5099, "text": "Output:" }, { "code": null, "e": 5175, "s": 5107, "text": "Let’s try to customize this plot. Customizations that we will use –" }, { "code": null, "e": 5206, "s": 5175, "text": "color: Used to color the bars." }, { "code": null, "e": 5274, "s": 5206, "text": "facet_row: Divides the graph into rows according to the data passed" }, { "code": null, "e": 5345, "s": 5274, "text": "facet_col: Divides the graph into columns according to the data passed" }, { "code": null, "e": 5354, "s": 5345, "text": "Example:" }, { "code": null, "e": 5362, "s": 5354, "text": "Python3" }, { "code": "import plotly.express as px # Loading the datadf = px.data.tips() # Creating the bar chartfig = px.bar(df, x='day', y=\"total_bill\", color='sex', facet_row='time', facet_col='sex') fig.show()", "e": 5568, "s": 5362, "text": null }, { "code": null, "e": 5576, "s": 5568, "text": "Output:" }, { "code": null, "e": 5896, "s": 5576, "text": "A scatter plot is a set of dotted points to represent individual pieces of data in the horizontal and vertical axis. A graph in which the values of two variables are plotted along X-axis and Y-axis, the pattern of the resulting points reveals a correlation between them. it can be created using the px.scatter() method." }, { "code": null, "e": 5904, "s": 5896, "text": "Syntax:" }, { "code": null, "e": 6156, "s": 5904, "text": "plotly.express.scatter(data_frame=None, x=None, y=None, color=None, symbol=None, size=None, hover_name=None, hover_data=None, facet_row=None, facet_col=None, facet_col_wrap=0, opacity=None, title=None, template=None, width=None, height=None, **kwargs)" }, { "code": null, "e": 6165, "s": 6156, "text": "Example:" }, { "code": null, "e": 6173, "s": 6165, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the scatter chartfig = px.scatter(df, x='total_bill', y=\"tip\") # showing the plotfig.show()", "e": 6346, "s": 6173, "text": null }, { "code": null, "e": 6354, "s": 6346, "text": "Output:" }, { "code": null, "e": 6432, "s": 6354, "text": "Let’s see various customizations available for this chart that we will use – " }, { "code": null, "e": 6457, "s": 6432, "text": "color: Color the points." }, { "code": null, "e": 6524, "s": 6457, "text": "symbol: Gives a symbol to each point according to the data passed." }, { "code": null, "e": 6555, "s": 6524, "text": "size: The size for each point." }, { "code": null, "e": 6564, "s": 6555, "text": "Example:" }, { "code": null, "e": 6572, "s": 6564, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the scatter chartfig = px.scatter(df, x='total_bill', y=\"tip\", color='time', symbol='sex', size='size', facet_row='day', facet_col='time') # showing the plotfig.show()", "e": 6853, "s": 6572, "text": null }, { "code": null, "e": 6861, "s": 6853, "text": "Output:" }, { "code": null, "e": 7108, "s": 6861, "text": "A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. It can be created using the px.histogram() method." }, { "code": null, "e": 7117, "s": 7108, "text": "Syntax: " }, { "code": null, "e": 7312, "s": 7117, "text": "plotly.express.histogram(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, barnorm=None, histnorm=None, nbins=None, title=None, template=None, width=None, height=None)" }, { "code": null, "e": 7321, "s": 7312, "text": "Example:" }, { "code": null, "e": 7329, "s": 7321, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the histogramfig = px.histogram(df, x=\"total_bill\") # showing the plotfig.show()", "e": 7491, "s": 7329, "text": null }, { "code": null, "e": 7499, "s": 7491, "text": "Output:" }, { "code": null, "e": 7576, "s": 7499, "text": "Let’s customize the above graph. Customizations that we will be using are – " }, { "code": null, "e": 7601, "s": 7576, "text": "color: To color the bars" }, { "code": null, "e": 7634, "s": 7601, "text": "nbins: To set the number of bins" }, { "code": null, "e": 8087, "s": 7634, "text": "histnorm: Mode through which the bins are represented. Different values that can be passed using this argument are-percent or probability: The output of histfunc for a given bin is divided by the sum of the output of histfunc for all bins.density: The output of histfunc for a given bin is divided by the size of the bin.probability density: The output of histfunc for a given bin is normalized such that it corresponds to the probability that a random" }, { "code": null, "e": 8212, "s": 8087, "text": "percent or probability: The output of histfunc for a given bin is divided by the sum of the output of histfunc for all bins." }, { "code": null, "e": 8295, "s": 8212, "text": "density: The output of histfunc for a given bin is divided by the size of the bin." }, { "code": null, "e": 8427, "s": 8295, "text": "probability density: The output of histfunc for a given bin is normalized such that it corresponds to the probability that a random" }, { "code": null, "e": 8662, "s": 8427, "text": "barmode: Can be either ‘group’, ‘overlay’ or ‘relative’.group: Bars are stacked above zero for positive values and below zero for negative valuesoverlay: Bars are drawn on the top of each othergroup: Bars are placed beside each other." }, { "code": null, "e": 8752, "s": 8662, "text": "group: Bars are stacked above zero for positive values and below zero for negative values" }, { "code": null, "e": 8801, "s": 8752, "text": "overlay: Bars are drawn on the top of each other" }, { "code": null, "e": 8843, "s": 8801, "text": "group: Bars are placed beside each other." }, { "code": null, "e": 8852, "s": 8843, "text": "Example:" }, { "code": null, "e": 8860, "s": 8852, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the histogramfig = px.histogram(df, x=\"total_bill\", color='sex', nbins=50, histnorm='percent', barmode='overlay') # showing the plotfig.show()", "e": 9120, "s": 8860, "text": null }, { "code": null, "e": 9128, "s": 9120, "text": "Output:" }, { "code": null, "e": 9519, "s": 9128, "text": "A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. A circular chart cuts in a form of radii into segments describing relative frequencies or magnitude also known as a circle graph. It can be created using the px.pie() method." }, { "code": null, "e": 9527, "s": 9519, "text": "Syntax:" }, { "code": null, "e": 9793, "s": 9527, "text": "plotly.express.pie(data_frame=None, names=None, values=None, color=None, color_discrete_sequence=None, color_discrete_map={}, hover_name=None, hover_data=None, custom_data=None, labels={}, title=None, template=None, width=None, height=None, opacity=None, hole=None)" }, { "code": null, "e": 9802, "s": 9793, "text": "Example:" }, { "code": null, "e": 9810, "s": 9802, "text": "Python3" }, { "code": "import plotly.express as px # Loading the iris datasetdf = px.data.tips() fig = px.pie(df, values=\"total_bill\", names=\"day\")fig.show()", "e": 9947, "s": 9810, "text": null }, { "code": null, "e": 9955, "s": 9947, "text": "Output:" }, { "code": null, "e": 10032, "s": 9955, "text": "Let’s customize the above graph. Customizations that we will be using are – " }, { "code": null, "e": 10091, "s": 10032, "text": "color_discrete_sequence: Strings defining valid CSS colors" }, { "code": null, "e": 10157, "s": 10091, "text": "opacity: Opacity for markers. The value should be between 0 and 1" }, { "code": null, "e": 10251, "s": 10157, "text": "hole: Creates a hole in between to make it a donut chart. The value should be between 0 and 1" }, { "code": null, "e": 10260, "s": 10251, "text": "Example:" }, { "code": null, "e": 10268, "s": 10260, "text": "Python3" }, { "code": "import plotly.express as px # Loading the iris datasetdf = px.data.tips() fig = px.pie(df, values=\"total_bill\", names=\"day\", color_discrete_sequence=px.colors.sequential.RdBu, opacity=0.7, hole=0.5)fig.show()", "e": 10503, "s": 10268, "text": null }, { "code": null, "e": 10511, "s": 10503, "text": "Output:" }, { "code": null, "e": 10987, "s": 10511, "text": "A Box Plot is also known as Whisker plot is created to display the summary of the set of data values having properties like minimum, first quartile, median, third quartile and maximum. In the box plot, a box is created from the first quartile to the third quartile, a vertical line is also there which goes through the box at the median. Here x-axis denotes the data to be plotted while the y-axis shows the frequency distribution. It can be created using the px.box() method" }, { "code": null, "e": 10995, "s": 10987, "text": "Syntax:" }, { "code": null, "e": 11153, "s": 10995, "text": "plotly.express.box(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, title=None, template=None, width=None, height=None, **kwargs)" }, { "code": null, "e": 11162, "s": 11153, "text": "Example:" }, { "code": null, "e": 11170, "s": 11162, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the boxplotfig = px.box(df, x=\"day\", y=\"tip\") # showing the plotfig.show()", "e": 11326, "s": 11170, "text": null }, { "code": null, "e": 11334, "s": 11326, "text": "Output:" }, { "code": null, "e": 11399, "s": 11334, "text": "Let’s see various customizations that can be used on boxplots – " }, { "code": null, "e": 11436, "s": 11399, "text": "color: used to assign color to marks" }, { "code": null, "e": 11507, "s": 11436, "text": "facet_row: assign marks to facetted subplots in the vertical direction" }, { "code": null, "e": 11580, "s": 11507, "text": "facet_col: assign marks to facetted subplots in the horizontal direction" }, { "code": null, "e": 11728, "s": 11580, "text": "boxmode: One of ‘group’ or ‘overlay’ In ‘overlay’ mode, boxes are on drawn top of one another. In ‘group’ mode, boxes are placed beside each other." }, { "code": null, "e": 11775, "s": 11728, "text": "notched: If True, boxes are drawn with notches" }, { "code": null, "e": 11784, "s": 11775, "text": "Example:" }, { "code": null, "e": 11792, "s": 11784, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the boxplotfig = px.box(df, x=\"day\", y=\"tip\", color='sex', facet_row='time', boxmode='group', notched=True) # showing the plotfig.show()", "e": 12034, "s": 11792, "text": null }, { "code": null, "e": 12042, "s": 12034, "text": "Output:" }, { "code": null, "e": 12627, "s": 12042, "text": "Violin Plot is a method to visualize the distribution of numerical data of different variables. It is similar to Box Plot but with a rotated plot on each side, giving more information about the density estimate on the y-axis. The density is mirrored and flipped over and the resulting shape is filled in, creating an image resembling a violin. The advantage of a violin plot is that it can show nuances in the distribution that aren’t perceptible in a boxplot. On the other hand, the boxplot more clearly shows the outliers in the data. It can be created using the px.violin() method." }, { "code": null, "e": 12635, "s": 12627, "text": "Syntax:" }, { "code": null, "e": 12881, "s": 12635, "text": "violin(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None, hover_name=None, hover_data=None, title=None, template=None, width=None, height=None, **kwargs)" }, { "code": null, "e": 12890, "s": 12881, "text": "Example:" }, { "code": null, "e": 12898, "s": 12890, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the violin plotfig = px.violin(df, x=\"day\", y=\"tip\") # showing the plotfig.show()", "e": 13061, "s": 12898, "text": null }, { "code": null, "e": 13069, "s": 13061, "text": "Output:" }, { "code": null, "e": 13348, "s": 13069, "text": "For customizing the violin plot we will use the same customizations available for the box plot except the boxmode and notched which are not available for the violin plot. We will also the box parameter. Setting this parameter to True will show a box plot inside the violin plot." }, { "code": null, "e": 13357, "s": 13348, "text": "Example:" }, { "code": null, "e": 13365, "s": 13357, "text": "Python3" }, { "code": "import plotly.express as px # using the datasetdf = px.data.tips() # plotting the violin plotfig = px.violin(df, x=\"day\", y=\"tip\", color='sex', facet_row='time', box=True) # showing the plotfig.show()", "e": 13584, "s": 13365, "text": null }, { "code": null, "e": 13592, "s": 13584, "text": "Output:" }, { "code": null, "e": 14012, "s": 13592, "text": "3D Scatter Plot can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. All the parameter control visual semantic which are used to identify the different subsets. Using redundant semantics can be helpful for making graphics more accessible. It can be created using the scatter_3d function of plotly.express class." }, { "code": null, "e": 14020, "s": 14012, "text": "Syntax:" }, { "code": null, "e": 14227, "s": 14020, "text": "plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None, **kwargs)" }, { "code": null, "e": 14236, "s": 14227, "text": "Example:" }, { "code": null, "e": 14244, "s": 14236, "text": "Python3" }, { "code": "import plotly.express as px # data to be plotteddf = px.data.tips() # plotting the figurefig = px.scatter_3d(df, x=\"total_bill\", y=\"sex\", z=\"tip\") fig.show()", "e": 14405, "s": 14244, "text": null }, { "code": null, "e": 14413, "s": 14405, "text": "Output:" }, { "code": null, "e": 14489, "s": 14413, "text": "Customizing the 3D scatter plot. We will use the following customization – " }, { "code": null, "e": 14525, "s": 14489, "text": "color: Set the color of the markers" }, { "code": null, "e": 14558, "s": 14525, "text": "size: Set the size of the marker" }, { "code": null, "e": 14593, "s": 14558, "text": "symbol: Set the symbol of the plot" }, { "code": null, "e": 14602, "s": 14593, "text": "Example:" }, { "code": null, "e": 14610, "s": 14602, "text": "Python3" }, { "code": "import plotly.express as px # data to be plotteddf = px.data.tips() # plotting the figurefig = px.scatter_3d(df, x=\"total_bill\", y=\"sex\", z=\"tip\", color='day', size='total_bill', symbol='time') fig.show()", "e": 14838, "s": 14610, "text": null }, { "code": null, "e": 14846, "s": 14838, "text": "Output:" }, { "code": null, "e": 15337, "s": 14846, "text": "Every graph created by the plotly provides various interactions, where we can select a part of the plot, we get information on hovering over the plot, and also a toolbar is also created with every plot that can many tasks like saving the plot locally or zooming in and out, etc. Besides all these plotly allows us to add more tools like dropdowns, buttons, sliders, etc. These can be created using the update menu attribute of the plot layout. Let’s see how to do all such things in detail." }, { "code": null, "e": 15639, "s": 15337, "text": "A drop-down menu is a part of the menu button which is displayed on a screen all the time. Every menu button is associated with a Menu widget that can display the choices for that menu button when clicked on it. In plotly, there are 4 possible methods to modify the charts by using update menu method." }, { "code": null, "e": 15679, "s": 15639, "text": "restyle: modify data or data attributes" }, { "code": null, "e": 15714, "s": 15679, "text": "relayout: modify layout attributes" }, { "code": null, "e": 15756, "s": 15714, "text": "update: modify data and layout attributes" }, { "code": null, "e": 15793, "s": 15756, "text": "animate: start or pause an animation" }, { "code": null, "e": 15802, "s": 15793, "text": "Example:" }, { "code": null, "e": 15810, "s": 15802, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy as npimport pandas as pd df = pd.read_csv('tips.csv') plot = px.Figure(data=[px.Scatter( x=df['day'], y=df['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict(buttons=list([ dict( args=[\"type\", \"scatter\"], label=\"Scatter Plot\", method=\"restyle\" ), dict( args=[\"type\", \"bar\"], label=\"Bar Chart\", method=\"restyle\" ) ]), direction=\"down\", ), ]) plot.show()", "e": 16423, "s": 15810, "text": null }, { "code": null, "e": 16431, "s": 16423, "text": "Output:" }, { "code": null, "e": 16675, "s": 16431, "text": "In plotly, actions custom Buttons are used to quickly make actions directly from a record. Custom Buttons can be added to page layouts in CRM, Marketing, and Custom Apps. There are also 4 possible methods that can be applied in custom buttons:" }, { "code": null, "e": 16715, "s": 16675, "text": "restyle: modify data or data attributes" }, { "code": null, "e": 16750, "s": 16715, "text": "relayout: modify layout attributes" }, { "code": null, "e": 16792, "s": 16750, "text": "update: modify data and layout attributes" }, { "code": null, "e": 16829, "s": 16792, "text": "animate: start or pause an animation" }, { "code": null, "e": 16838, "s": 16829, "text": "Example:" }, { "code": null, "e": 16846, "s": 16838, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport pandas as pd # reading the databasedata = pd.read_csv(\"tips.csv\") plot = px.Figure(data=[px.Scatter( x=data['day'], y=data['tip'], mode='markers',)]) # Add dropdownplot.update_layout( updatemenus=[ dict( type=\"buttons\", direction=\"left\", buttons=list([ dict( args=[\"type\", \"scatter\"], label=\"Scatter Plot\", method=\"restyle\" ), dict( args=[\"type\", \"bar\"], label=\"Bar Chart\", method=\"restyle\" ) ]), ), ]) plot.show()", "e": 17554, "s": 16846, "text": null }, { "code": null, "e": 17562, "s": 17554, "text": "Output:" }, { "code": null, "e": 17961, "s": 17562, "text": "In plotly, the range slider is a custom range-type input control. It allows selecting a value or a range of values between a specified minimum and maximum range. And the range selector is a tool for selecting ranges to display within the chart. It provides buttons to select pre-configured ranges in the chart. It also provides input boxes where the minimum and maximum dates can be manually input." }, { "code": null, "e": 17970, "s": 17961, "text": "Example:" }, { "code": null, "e": 17978, "s": 17970, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['tip'] plot = px.Figure(data=[px.Scatter( x=x, y=y, mode='markers',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step=\"day\", stepmode=\"backward\"), ]) ), rangeslider=dict( visible=True ), )) plot.show()", "e": 18479, "s": 17978, "text": null }, { "code": null, "e": 18487, "s": 18479, "text": "Output:" }, { "code": null, "e": 18501, "s": 18487, "text": "sumitgumber28" }, { "code": null, "e": 18521, "s": 18501, "text": "abhishek0719kadiyan" }, { "code": null, "e": 18531, "s": 18521, "text": "as5853535" }, { "code": null, "e": 18543, "s": 18531, "text": "kk773572498" }, { "code": null, "e": 18557, "s": 18543, "text": "Python-Plotly" }, { "code": null, "e": 18564, "s": 18557, "text": "Python" } ]
URL Rewriting using Java Servlet
13 Aug, 2018 Url rewriting is a process of appending or modifying any url structure while loading a page. The request made by client is always a new request and the server can not identify whether the current request is send by a new client or the previous same client. Due to This property of HTTP protocol and Web Servers are called stateless. But many times we should know who is client in the processing request.For example:In any social networking site during login to till logout the server should know who is client so that server can manage all the request according to the user need.This problem is solved by Session in Servlet. Session : Session is a state between client and server and it contain multiple request and response between client and server. As we know that HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. Following are some ways by which we can provide unique id in request and response : Session Interface in Servlet Cookies Management URL Rewriting URL Rewriting If your browser does not support cookies, URL rewriting provides you with another session tracking alternative. URL rewriting is a method in which the requested URL is modified to include a session ID. There are several ways to perform URL rewriting.Here we are discussing session management technique in which we pass control from one servlet to another. The Syntax for passing control from one servlet to another is as follows // SecondServlet is the name of the servlet where you want to pass controlout.print("<a href='SecondServlet?uname=" + n + "'>visit</a>"); Note : Generally we write web.xml file for request dispatcher but in this example we use annotation so their is no need of creating web.xml file. Syntax of annotation is : @WebServlet("/ServletName") // at the place of ServletName we have to write the name of our servlet file and this annotation should be written at the starting of class in servlet. Example of Session tracking using URL rewriting using annotation <!-- Save this file as Index.html --><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><form action="FirstServlet" method="get"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="submit"/> </form> </body></html> // Name this file as FirstServlet.javapackage GeeksforGeeks;import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*;@WebServlet("/FirstServlet") // annotation // this annotation is used for replacing xml filepublic class FirstServlet extends HttpServlet { // class name is FirstServlet which extends HttpServlet public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); /* The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding.*/ PrintWriter out = response.getWriter(); /*T he Java PrintWriter class ( java.io.PrintWriter ) enables you to write formatted data to an underlying Writer . For instance, writing int, long and other primitive data formatted as text, rather than as their byte values*/ String n = request.getParameter("userName"); //request.getParameter takes the value from index.html file // where name is username out.print("Welcome " + n); // out.println is used to print on the client web browser //url rewriting is used for creating session // it will redirect you to SecondServlet page out.print("<a href='SecondServlet?uname=" + n + "'>visit</a>"); out.close(); } catch (Exception e) { System.out.println(e); } }} // Name this file as SecondServlet.javapackage GeeksforGeeks; import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*; @WebServlet("/SecondServlet") // annotationpublic class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); /* * The response's character encoding is only set from the given * content type if this method is called before getWriter is called. * This method may be called repeatedly to change content type and * character encoding. */ PrintWriter out = response.getWriter(); /* * The Java PrintWriter class ( java.io.PrintWriter ) enables you to * write formatted data to an underlying Writer . For instance, * writing int, long and other primitive data formatted as text, * rather than as their byte values */ // getting value from the query string String n = request.getParameter("uname"); out.print("Hello " + n); /* out.println is used to print on the client web browser */ out.close(); } catch (Exception e) { System.out.println(e); } }} Program flow Explanation(Follow the diagram)When you deploy your project in eclipse the first page which is loaded in the HTML form whose form action is first servlet so the control will go to servlet1. In this case, we name servlet1 as FirstServlet where the username is printed. In FirstServlet we provide url where we transfer the control to servlet2 using url rewriting. In our case we name servlet2 as SecondServlet.Advantage of URL Rewriting : It doesn’t depend upon cookies and will work whether cookies are enabled or disabled Extra form submission is not required on all pages Disadvantage of URL RewritingIt will work only with links ad can send only text java-servlet Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Aug, 2018" }, { "code": null, "e": 146, "s": 53, "text": "Url rewriting is a process of appending or modifying any url structure while loading a page." }, { "code": null, "e": 678, "s": 146, "text": "The request made by client is always a new request and the server can not identify whether the current request is send by a new client or the previous same client. Due to This property of HTTP protocol and Web Servers are called stateless. But many times we should know who is client in the processing request.For example:In any social networking site during login to till logout the server should know who is client so that server can manage all the request according to the user need.This problem is solved by Session in Servlet." }, { "code": null, "e": 1026, "s": 678, "text": "Session : Session is a state between client and server and it contain multiple request and response between client and server. As we know that HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response." }, { "code": null, "e": 1110, "s": 1026, "text": "Following are some ways by which we can provide unique id in request and response :" }, { "code": null, "e": 1139, "s": 1110, "text": "Session Interface in Servlet" }, { "code": null, "e": 1158, "s": 1139, "text": "Cookies Management" }, { "code": null, "e": 1172, "s": 1158, "text": "URL Rewriting" }, { "code": null, "e": 1186, "s": 1172, "text": "URL Rewriting" }, { "code": null, "e": 1615, "s": 1186, "text": "If your browser does not support cookies, URL rewriting provides you with another session tracking alternative. URL rewriting is a method in which the requested URL is modified to include a session ID. There are several ways to perform URL rewriting.Here we are discussing session management technique in which we pass control from one servlet to another. The Syntax for passing control from one servlet to another is as follows" }, { "code": "// SecondServlet is the name of the servlet where you want to pass controlout.print(\"<a href='SecondServlet?uname=\" + n + \"'>visit</a>\");", "e": 1753, "s": 1615, "text": null }, { "code": null, "e": 1899, "s": 1753, "text": "Note : Generally we write web.xml file for request dispatcher but in this example we use annotation so their is no need of creating web.xml file." }, { "code": null, "e": 1925, "s": 1899, "text": "Syntax of annotation is :" }, { "code": "@WebServlet(\"/ServletName\") // at the place of ServletName we have to write the name of our servlet file and this annotation should be written at the starting of class in servlet.", "e": 2105, "s": 1925, "text": null }, { "code": null, "e": 2170, "s": 2105, "text": "Example of Session tracking using URL rewriting using annotation" }, { "code": "<!-- Save this file as Index.html --><!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Insert title here</title></head><body><form action=\"FirstServlet\" method=\"get\"> Name:<input type=\"text\" name=\"userName\"/><br/> <input type=\"submit\" value=\"submit\"/> </form> </body></html>", "e": 2455, "s": 2170, "text": null }, { "code": "// Name this file as FirstServlet.javapackage GeeksforGeeks;import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*;@WebServlet(\"/FirstServlet\") // annotation // this annotation is used for replacing xml filepublic class FirstServlet extends HttpServlet { // class name is FirstServlet which extends HttpServlet public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType(\"text/html\"); /* The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding.*/ PrintWriter out = response.getWriter(); /*T he Java PrintWriter class ( java.io.PrintWriter ) enables you to write formatted data to an underlying Writer . For instance, writing int, long and other primitive data formatted as text, rather than as their byte values*/ String n = request.getParameter(\"userName\"); //request.getParameter takes the value from index.html file // where name is username out.print(\"Welcome \" + n); // out.println is used to print on the client web browser //url rewriting is used for creating session // it will redirect you to SecondServlet page out.print(\"<a href='SecondServlet?uname=\" + n + \"'>visit</a>\"); out.close(); } catch (Exception e) { System.out.println(e); } }}", "e": 4061, "s": 2455, "text": null }, { "code": "// Name this file as SecondServlet.javapackage GeeksforGeeks; import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*; @WebServlet(\"/SecondServlet\") // annotationpublic class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType(\"text/html\"); /* * The response's character encoding is only set from the given * content type if this method is called before getWriter is called. * This method may be called repeatedly to change content type and * character encoding. */ PrintWriter out = response.getWriter(); /* * The Java PrintWriter class ( java.io.PrintWriter ) enables you to * write formatted data to an underlying Writer . For instance, * writing int, long and other primitive data formatted as text, * rather than as their byte values */ // getting value from the query string String n = request.getParameter(\"uname\"); out.print(\"Hello \" + n); /* out.println is used to print on the client web browser */ out.close(); } catch (Exception e) { System.out.println(e); } }}", "e": 5455, "s": 4061, "text": null }, { "code": null, "e": 5468, "s": 5455, "text": "Program flow" }, { "code": null, "e": 5905, "s": 5468, "text": "Explanation(Follow the diagram)When you deploy your project in eclipse the first page which is loaded in the HTML form whose form action is first servlet so the control will go to servlet1. In this case, we name servlet1 as FirstServlet where the username is printed. In FirstServlet we provide url where we transfer the control to servlet2 using url rewriting. In our case we name servlet2 as SecondServlet.Advantage of URL Rewriting :" }, { "code": null, "e": 5990, "s": 5905, "text": "It doesn’t depend upon cookies and will work whether cookies are enabled or disabled" }, { "code": null, "e": 6041, "s": 5990, "text": "Extra form submission is not required on all pages" }, { "code": null, "e": 6121, "s": 6041, "text": "Disadvantage of URL RewritingIt will work only with links ad can send only text" }, { "code": null, "e": 6134, "s": 6121, "text": "java-servlet" }, { "code": null, "e": 6139, "s": 6134, "text": "Java" }, { "code": null, "e": 6144, "s": 6139, "text": "Java" } ]
Maximum GCD among all pairs (i, j) of first N natural numbers
20 Apr, 2021 Given a positive integer N > 1, the task is to find the maximum GCD among all the pairs (i, j) such that i < j < N.Examples: Input: N = 3Output: 3Explanation:All the possible pairs are: (1, 2) (1, 3) (2, 3) with GCD 1.Input: N = 4Output: 2Explanation:Out of all the possible pairs the pair with max GCD is (2, 4) with a value 2. Naive Approach: Generate all possible pair of integers from the range [1, N] and calculate GCD of all pairs. Finally, print the maximum GCD obtained. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find maximum gcd// of all pairs possible from// first n natural numbersint maxGCD(int n){ // Stores maximum gcd int maxHcf = INT_MIN; // Iterate over all possible pairs for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = max(maxHcf, __gcd(i, j)); } } return maxHcf;} // Driver Codeint main(){ int n = 4; cout << maxGCD(n); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Function to find maximum gcd// of all pairs possible from// first n natural numbersstatic int maxGCD(int n){ // Stores maximum gcd int maxHcf = Integer.MIN_VALUE; // Iterate over all possible pairs for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = Math.max(maxHcf, __gcd(i, j)); } } return maxHcf;} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void main(String[] args){ int n = 4; System.out.print(maxGCD(n));}} // This code is contributed by Rajput-Ji # Python3 program for# the above approachdef __gcd(a, b): if(b == 0): return a; else: return __gcd(b, a % b); # Function to find maximum gcd# of all pairs possible from# first n natural numbersdef maxGCD(n): # Stores maximum gcd maxHcf = -2391734235435; # Iterate over all possible pairs for i in range(1, n + 1): for j in range(i + 1, n + 1): # Update maximum GCD maxHcf = max(maxHcf, __gcd(i, j)); return maxHcf; # Driver Codeif __name__ == '__main__': n = 4; print(maxGCD(n)); # This code is contributed by gauravrajput1 // C# program for// the above approachusing System;class GFG{ // Function to find maximum gcd// of all pairs possible from// first n natural numbersstatic int maxGCD(int n){ // Stores maximum gcd int maxHcf = int.MinValue; // Iterate over all possible pairs for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = Math.Max(maxHcf, __gcd(i, j)); } } return maxHcf;} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void Main(String[] args){ int n = 4; Console.Write(maxGCD(n));}} // This code is contributed by 29AjayKumar <script>// javascript program for// the above approach // Function to find maximum gcd // of all pairs possible from // first n natural numbers function maxGCD(n) { // Stores maximum gcd var maxHcf = Number.MIN_VALUE; // Iterate over all possible pairs for (i = 1; i <= n; i++) { for (j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = Math.max(maxHcf, __gcd(i, j)); } } return maxHcf; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Code var n = 4; document.write(maxGCD(n)); // This code contributed by umadevi9616</script> 2 Time Complexity: O(N 2 log N) Auxiliary Space: O(1)Efficient Approach: The GCD of N and N / 2 is N / 2 which is the maximum of all GCDs possible for any pair from 1 to N. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum GCD// among all the pairs from// first n natural numbersint maxGCD(int n){ // Return max GCD return (n / 2);} // Driver Codeint main(){ int n = 4; cout << maxGCD(n); return 0;} // Java implementation of the above approachclass GFG{ // Function to find the maximum GCD// among all the pairs from// first n natural numbersstatic int maxGCD(int n){ // Return max GCD return (n / 2);} // Driver codepublic static void main(String[] args){ int n = 4; System.out.print(maxGCD(n));}} // This code is contributed by Dewanti # Python3 implementation of the# above approach # Function to find the maximum GCD# among all the pairs from first n# natural numbersdef maxGCD(n): # Return max GCD return (n // 2); # Driver codeif __name__ == '__main__': n = 4; print(maxGCD(n)); # This code is contributed by Amit Katiyar // C# implementation of// the above approachusing System;class GFG{ // Function to find the maximum GCD// among all the pairs from// first n natural numbersstatic int maxGCD(int n){ // Return max GCD return (n / 2);} // Driver codepublic static void Main(String[] args){ int n = 4; Console.Write(maxGCD(n));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the above approach // Function to find the maximum GCD// among all the pairs from// first n natural numbersfunction maxGCD(n){ // Return max GCD return parseInt(n / 2);} // Driver Codevar n = 4;document.write( maxGCD(n)); // This code is contributed by rrrtnx.</script> 2 Time Complexity: O(1)Auxiliary Space: O(1) dewantipandeydp Rajput-Ji 29AjayKumar amit143katiyar GauravRajput1 umadevi9616 rrrtnx HCF Greedy Mathematical Searching Searching Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Apr, 2021" }, { "code": null, "e": 153, "s": 28, "text": "Given a positive integer N > 1, the task is to find the maximum GCD among all the pairs (i, j) such that i < j < N.Examples:" }, { "code": null, "e": 357, "s": 153, "text": "Input: N = 3Output: 3Explanation:All the possible pairs are: (1, 2) (1, 3) (2, 3) with GCD 1.Input: N = 4Output: 2Explanation:Out of all the possible pairs the pair with max GCD is (2, 4) with a value 2." }, { "code": null, "e": 507, "s": 357, "text": "Naive Approach: Generate all possible pair of integers from the range [1, N] and calculate GCD of all pairs. Finally, print the maximum GCD obtained." }, { "code": null, "e": 558, "s": 507, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 562, "s": 558, "text": "C++" }, { "code": null, "e": 567, "s": 562, "text": "Java" }, { "code": null, "e": 575, "s": 567, "text": "Python3" }, { "code": null, "e": 578, "s": 575, "text": "C#" }, { "code": null, "e": 589, "s": 578, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find maximum gcd// of all pairs possible from// first n natural numbersint maxGCD(int n){ // Stores maximum gcd int maxHcf = INT_MIN; // Iterate over all possible pairs for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = max(maxHcf, __gcd(i, j)); } } return maxHcf;} // Driver Codeint main(){ int n = 4; cout << maxGCD(n); return 0;}", "e": 1148, "s": 589, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to find maximum gcd// of all pairs possible from// first n natural numbersstatic int maxGCD(int n){ // Stores maximum gcd int maxHcf = Integer.MIN_VALUE; // Iterate over all possible pairs for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = Math.max(maxHcf, __gcd(i, j)); } } return maxHcf;} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void main(String[] args){ int n = 4; System.out.print(maxGCD(n));}} // This code is contributed by Rajput-Ji", "e": 1846, "s": 1148, "text": null }, { "code": "# Python3 program for# the above approachdef __gcd(a, b): if(b == 0): return a; else: return __gcd(b, a % b); # Function to find maximum gcd# of all pairs possible from# first n natural numbersdef maxGCD(n): # Stores maximum gcd maxHcf = -2391734235435; # Iterate over all possible pairs for i in range(1, n + 1): for j in range(i + 1, n + 1): # Update maximum GCD maxHcf = max(maxHcf, __gcd(i, j)); return maxHcf; # Driver Codeif __name__ == '__main__': n = 4; print(maxGCD(n)); # This code is contributed by gauravrajput1", "e": 2455, "s": 1846, "text": null }, { "code": "// C# program for// the above approachusing System;class GFG{ // Function to find maximum gcd// of all pairs possible from// first n natural numbersstatic int maxGCD(int n){ // Stores maximum gcd int maxHcf = int.MinValue; // Iterate over all possible pairs for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = Math.Max(maxHcf, __gcd(i, j)); } } return maxHcf;} static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Codepublic static void Main(String[] args){ int n = 4; Console.Write(maxGCD(n));}} // This code is contributed by 29AjayKumar", "e": 3139, "s": 2455, "text": null }, { "code": "<script>// javascript program for// the above approach // Function to find maximum gcd // of all pairs possible from // first n natural numbers function maxGCD(n) { // Stores maximum gcd var maxHcf = Number.MIN_VALUE; // Iterate over all possible pairs for (i = 1; i <= n; i++) { for (j = i + 1; j <= n; j++) { // Update maximum GCD maxHcf = Math.max(maxHcf, __gcd(i, j)); } } return maxHcf; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver Code var n = 4; document.write(maxGCD(n)); // This code contributed by umadevi9616</script>", "e": 3847, "s": 3139, "text": null }, { "code": null, "e": 3849, "s": 3847, "text": "2" }, { "code": null, "e": 4020, "s": 3849, "text": "Time Complexity: O(N 2 log N) Auxiliary Space: O(1)Efficient Approach: The GCD of N and N / 2 is N / 2 which is the maximum of all GCDs possible for any pair from 1 to N." }, { "code": null, "e": 4071, "s": 4020, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 4075, "s": 4071, "text": "C++" }, { "code": null, "e": 4080, "s": 4075, "text": "Java" }, { "code": null, "e": 4088, "s": 4080, "text": "Python3" }, { "code": null, "e": 4091, "s": 4088, "text": "C#" }, { "code": null, "e": 4102, "s": 4091, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum GCD// among all the pairs from// first n natural numbersint maxGCD(int n){ // Return max GCD return (n / 2);} // Driver Codeint main(){ int n = 4; cout << maxGCD(n); return 0;}", "e": 4417, "s": 4102, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to find the maximum GCD// among all the pairs from// first n natural numbersstatic int maxGCD(int n){ // Return max GCD return (n / 2);} // Driver codepublic static void main(String[] args){ int n = 4; System.out.print(maxGCD(n));}} // This code is contributed by Dewanti", "e": 4774, "s": 4417, "text": null }, { "code": "# Python3 implementation of the# above approach # Function to find the maximum GCD# among all the pairs from first n# natural numbersdef maxGCD(n): # Return max GCD return (n // 2); # Driver codeif __name__ == '__main__': n = 4; print(maxGCD(n)); # This code is contributed by Amit Katiyar", "e": 5083, "s": 4774, "text": null }, { "code": "// C# implementation of// the above approachusing System;class GFG{ // Function to find the maximum GCD// among all the pairs from// first n natural numbersstatic int maxGCD(int n){ // Return max GCD return (n / 2);} // Driver codepublic static void Main(String[] args){ int n = 4; Console.Write(maxGCD(n));}} // This code is contributed by Rajput-Ji", "e": 5438, "s": 5083, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to find the maximum GCD// among all the pairs from// first n natural numbersfunction maxGCD(n){ // Return max GCD return parseInt(n / 2);} // Driver Codevar n = 4;document.write( maxGCD(n)); // This code is contributed by rrrtnx.</script>", "e": 5756, "s": 5438, "text": null }, { "code": null, "e": 5758, "s": 5756, "text": "2" }, { "code": null, "e": 5801, "s": 5758, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 5817, "s": 5801, "text": "dewantipandeydp" }, { "code": null, "e": 5827, "s": 5817, "text": "Rajput-Ji" }, { "code": null, "e": 5839, "s": 5827, "text": "29AjayKumar" }, { "code": null, "e": 5854, "s": 5839, "text": "amit143katiyar" }, { "code": null, "e": 5868, "s": 5854, "text": "GauravRajput1" }, { "code": null, "e": 5880, "s": 5868, "text": "umadevi9616" }, { "code": null, "e": 5887, "s": 5880, "text": "rrrtnx" }, { "code": null, "e": 5891, "s": 5887, "text": "HCF" }, { "code": null, "e": 5898, "s": 5891, "text": "Greedy" }, { "code": null, "e": 5911, "s": 5898, "text": "Mathematical" }, { "code": null, "e": 5921, "s": 5911, "text": "Searching" }, { "code": null, "e": 5931, "s": 5921, "text": "Searching" }, { "code": null, "e": 5938, "s": 5931, "text": "Greedy" }, { "code": null, "e": 5951, "s": 5938, "text": "Mathematical" } ]
How to set vertical space between the list of items using CSS ?
11 May, 2022 List of items in HTML can be of multiple type like ordered list, unordered list or could be description list. By default, there is a fixed vertical space between the list of items. We can increase or decrease the vertical spacing of the list of items by using different CSS properties. In this article, we will cover all the possible ways to set the vertical space between the list of items. CSS line-height Property: In this method, we will set the line-height of list items which will ultimately increases or decrease the vertical spacing of list items. Syntax:line-height: normal|number|length|percentage|initial|inherit; line-height: normal|number|length|percentage|initial|inherit; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Using line-height to set line-height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left ul { /* Increase line-height compare to default */ line-height: 2.5em; float: left; } .right { float: right; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h4> Using line-height property to set line height </h4> <br><br> <div class="left"> <b>line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class="right"> <b>No line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Using line-height to set line-height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left ul { /* Increase line-height compare to default */ line-height: 2.5em; float: left; } .right { float: right; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h4> Using line-height property to set line height </h4> <br><br> <div class="left"> <b>line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class="right"> <b>No line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html> Output: CSS margin-top Property: We will apply margin-top property that will set line-height of list items which will ultimately increases or decrease the vertical spacing of list items. The CSS margin-bottom property can also applicable.Note: You can also use only CSS margin property. Syntax:For margin-top margin-top: length|auto|initial|inherit|percentage;For margin-bottom margin-bottom: length|auto|initial|inherit|percentage; For margin-top margin-top: length|auto|initial|inherit|percentage; For margin-bottom margin-bottom: length|auto|initial|inherit|percentage; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Using margin-top and margin-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { margin-top: 1.5em; } li:not(:last-of-type) { margin-bottom: 1.5em; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h4> Using margin-top and margin-bottom to set line height </h4> <br><br> <div class="left"> <b>margin-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class="right"> <b>margin-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Using margin-top and margin-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { margin-top: 1.5em; } li:not(:last-of-type) { margin-bottom: 1.5em; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h4> Using margin-top and margin-bottom to set line height </h4> <br><br> <div class="left"> <b>margin-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class="right"> <b>margin-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html> Output: CSS padding-top Property: We will apply padding-top property that will set line-height of list items which will ultimately increase or decrease the vertical spacing of list items. The CSS padding-bottom property is also applicable.Note: You can also use only CSS padding property. Syntax:For padding-top padding-top: length|initial|inherit;For padding-bottom padding-bottom: length|initial|inherit; For padding-top padding-top: length|initial|inherit; For padding-bottom padding-bottom: length|initial|inherit; Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Using padding-top and padding-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { padding-top: 1.0em; } li:not(:last-of-type) { padding-bottom: 1.0em; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h4> Using padding-top and padding-bottom to set line height </h4> <br><br> <div class="left"> <b>padding-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class="right"> <b>padding-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Using padding-top and padding-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { padding-top: 1.0em; } li:not(:last-of-type) { padding-bottom: 1.0em; } </style> </head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <h4> Using padding-top and padding-bottom to set line height </h4> <br><br> <div class="left"> <b>padding-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class="right"> <b>padding-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html> Output: Note: Vertical spaces will be different in all the methods. sumitgumber28 CSS-Properties HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2022" }, { "code": null, "e": 420, "s": 28, "text": "List of items in HTML can be of multiple type like ordered list, unordered list or could be description list. By default, there is a fixed vertical space between the list of items. We can increase or decrease the vertical spacing of the list of items by using different CSS properties. In this article, we will cover all the possible ways to set the vertical space between the list of items." }, { "code": null, "e": 584, "s": 420, "text": "CSS line-height Property: In this method, we will set the line-height of list items which will ultimately increases or decrease the vertical spacing of list items." }, { "code": null, "e": 653, "s": 584, "text": "Syntax:line-height: normal|number|length|percentage|initial|inherit;" }, { "code": null, "e": 715, "s": 653, "text": "line-height: normal|number|length|percentage|initial|inherit;" }, { "code": null, "e": 2073, "s": 715, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> Using line-height to set line-height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left ul { /* Increase line-height compare to default */ line-height: 2.5em; float: left; } .right { float: right; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h4> Using line-height property to set line height </h4> <br><br> <div class=\"left\"> <b>line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class=\"right\"> <b>No line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> Using line-height to set line-height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left ul { /* Increase line-height compare to default */ line-height: 2.5em; float: left; } .right { float: right; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h4> Using line-height property to set line height </h4> <br><br> <div class=\"left\"> <b>line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class=\"right\"> <b>No line-height property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html>", "e": 3423, "s": 2073, "text": null }, { "code": null, "e": 3431, "s": 3423, "text": "Output:" }, { "code": null, "e": 3710, "s": 3431, "text": "CSS margin-top Property: We will apply margin-top property that will set line-height of list items which will ultimately increases or decrease the vertical spacing of list items. The CSS margin-bottom property can also applicable.Note: You can also use only CSS margin property." }, { "code": null, "e": 3857, "s": 3710, "text": "Syntax:For margin-top\nmargin-top: length|auto|initial|inherit|percentage;For margin-bottom\nmargin-bottom: length|auto|initial|inherit|percentage;\n" }, { "code": null, "e": 3924, "s": 3857, "text": "For margin-top\nmargin-top: length|auto|initial|inherit|percentage;" }, { "code": null, "e": 3998, "s": 3924, "text": "For margin-bottom\nmargin-bottom: length|auto|initial|inherit|percentage;\n" }, { "code": null, "e": 5424, "s": 3998, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> Using margin-top and margin-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { margin-top: 1.5em; } li:not(:last-of-type) { margin-bottom: 1.5em; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h4> Using margin-top and margin-bottom to set line height </h4> <br><br> <div class=\"left\"> <b>margin-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class=\"right\"> <b>margin-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> Using margin-top and margin-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { margin-top: 1.5em; } li:not(:last-of-type) { margin-bottom: 1.5em; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h4> Using margin-top and margin-bottom to set line height </h4> <br><br> <div class=\"left\"> <b>margin-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class=\"right\"> <b>margin-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html>", "e": 6842, "s": 5424, "text": null }, { "code": null, "e": 6850, "s": 6842, "text": "Output:" }, { "code": null, "e": 7131, "s": 6850, "text": "CSS padding-top Property: We will apply padding-top property that will set line-height of list items which will ultimately increase or decrease the vertical spacing of list items. The CSS padding-bottom property is also applicable.Note: You can also use only CSS padding property." }, { "code": null, "e": 7249, "s": 7131, "text": "Syntax:For padding-top\npadding-top: length|initial|inherit;For padding-bottom\npadding-bottom: length|initial|inherit;" }, { "code": null, "e": 7302, "s": 7249, "text": "For padding-top\npadding-top: length|initial|inherit;" }, { "code": null, "e": 7361, "s": 7302, "text": "For padding-bottom\npadding-bottom: length|initial|inherit;" }, { "code": null, "e": 8795, "s": 7361, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> Using padding-top and padding-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { padding-top: 1.0em; } li:not(:last-of-type) { padding-bottom: 1.0em; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h4> Using padding-top and padding-bottom to set line height </h4> <br><br> <div class=\"left\"> <b>padding-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class=\"right\"> <b>padding-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title> Using padding-top and padding-bottom to set line height </title> <style> .container { width: 500px } h1 { color: green; } b { position: absolute; top: 20%; } .left { float: left; } .right { float: right; } li:not(:first-of-type) { padding-top: 1.0em; } li:not(:last-of-type) { padding-bottom: 1.0em; } </style> </head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h4> Using padding-top and padding-bottom to set line height </h4> <br><br> <div class=\"left\"> <b>padding-top property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> <div class=\"right\"> <b>padding-bottom property effect</b><br> <ul> <li>For Geeks</li> <li>GeeksforGeeks</li> <li>A Computer Science Poratal</li> </ul> </div> </div></body> </html>", "e": 10221, "s": 8795, "text": null }, { "code": null, "e": 10229, "s": 10221, "text": "Output:" }, { "code": null, "e": 10289, "s": 10229, "text": "Note: Vertical spaces will be different in all the methods." }, { "code": null, "e": 10303, "s": 10289, "text": "sumitgumber28" }, { "code": null, "e": 10318, "s": 10303, "text": "CSS-Properties" }, { "code": null, "e": 10328, "s": 10318, "text": "HTML-Misc" }, { "code": null, "e": 10335, "s": 10328, "text": "Picked" }, { "code": null, "e": 10339, "s": 10335, "text": "CSS" }, { "code": null, "e": 10344, "s": 10339, "text": "HTML" }, { "code": null, "e": 10361, "s": 10344, "text": "Web Technologies" }, { "code": null, "e": 10388, "s": 10361, "text": "Web technologies Questions" }, { "code": null, "e": 10393, "s": 10388, "text": "HTML" }, { "code": null, "e": 10491, "s": 10393, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10528, "s": 10491, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 10567, "s": 10528, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 10606, "s": 10567, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 10670, "s": 10606, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 10731, "s": 10670, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 10755, "s": 10731, "text": "REST API (Introduction)" }, { "code": null, "e": 10808, "s": 10755, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 10868, "s": 10808, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 10929, "s": 10868, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python PySpark – DataFrame filter on multiple columns
14 Sep, 2021 In this article, we are going to filter the dataframe on multiple columns by using filter() and where() function in Pyspark in Python. Creating Dataframe for demonestration: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, "sravan", "company 1"], [2, "ojaswi", "company 1"], [3, "rohith", "company 2"], [4, "sridevi", "company 1"], [1, "sravan", "company 1"], [4, "sridevi", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show() Output: filter() is used to return the dataframe based on the given condition by removing the rows in the dataframe or by extracting the particular rows or columns from the dataframe. We are going to filter the dataframe on multiple columns. It can take a condition and returns the dataframe. Syntax: filter(dataframe.column condition) Example 1: Conditional operator includes boolean or logical or relational operators. Python3 # select dataframe where ID less than 3dataframe.filter(dataframe.ID < 3).show() Output: Example 2: Python program to filter data based on two columns. In this example, we created a pyspark dataframe and select dataframe where ID less than 3 or name is Sridevi Python3 # select dataframe where ID less than# 3 or name is sridevidataframe.filter((dataframe.ID < 3) | (dataframe.NAME == 'sridevi')).show() Output: Example 3: Multiple columns filtering Python3 # select dataframe where ID less than# 3 or name is sridevi and comapny 1dataframe.filter((dataframe.ID < 3) | ( (dataframe.NAME == 'sridevi') & (dataframe.Company == 'company 1'))).show() Output: Where: where is similar to filter() function that is used to return the dataframe based on the given condition by removing the rows in the dataframe or by extracting the particular rows or columns from the dataframe. It can take a condition and returns the dataframe. where(dataframe.column condition) Example 1: Python program to filter on multiple columns Python3 # select dataframe where ID less than# 3 or name is sridevi and comapny 1dataframe.where((dataframe.ID < 3) | ( (dataframe.NAME == 'sridevi') & (dataframe.Company == 'company 1'))).show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 163, "s": 28, "text": "In this article, we are going to filter the dataframe on multiple columns by using filter() and where() function in Pyspark in Python." }, { "code": null, "e": 202, "s": 163, "text": "Creating Dataframe for demonestration:" }, { "code": null, "e": 210, "s": 202, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, \"sravan\", \"company 1\"], [2, \"ojaswi\", \"company 1\"], [3, \"rohith\", \"company 2\"], [4, \"sridevi\", \"company 1\"], [1, \"sravan\", \"company 1\"], [4, \"sridevi\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show()", "e": 868, "s": 210, "text": null }, { "code": null, "e": 876, "s": 868, "text": "Output:" }, { "code": null, "e": 1161, "s": 876, "text": "filter() is used to return the dataframe based on the given condition by removing the rows in the dataframe or by extracting the particular rows or columns from the dataframe. We are going to filter the dataframe on multiple columns. It can take a condition and returns the dataframe." }, { "code": null, "e": 1169, "s": 1161, "text": "Syntax:" }, { "code": null, "e": 1204, "s": 1169, "text": "filter(dataframe.column condition)" }, { "code": null, "e": 1289, "s": 1204, "text": "Example 1: Conditional operator includes boolean or logical or relational operators." }, { "code": null, "e": 1297, "s": 1289, "text": "Python3" }, { "code": "# select dataframe where ID less than 3dataframe.filter(dataframe.ID < 3).show()", "e": 1378, "s": 1297, "text": null }, { "code": null, "e": 1386, "s": 1378, "text": "Output:" }, { "code": null, "e": 1558, "s": 1386, "text": "Example 2: Python program to filter data based on two columns. In this example, we created a pyspark dataframe and select dataframe where ID less than 3 or name is Sridevi" }, { "code": null, "e": 1566, "s": 1558, "text": "Python3" }, { "code": "# select dataframe where ID less than# 3 or name is sridevidataframe.filter((dataframe.ID < 3) | (dataframe.NAME == 'sridevi')).show()", "e": 1718, "s": 1566, "text": null }, { "code": null, "e": 1726, "s": 1718, "text": "Output:" }, { "code": null, "e": 1764, "s": 1726, "text": "Example 3: Multiple columns filtering" }, { "code": null, "e": 1772, "s": 1764, "text": "Python3" }, { "code": "# select dataframe where ID less than# 3 or name is sridevi and comapny 1dataframe.filter((dataframe.ID < 3) | ( (dataframe.NAME == 'sridevi') & (dataframe.Company == 'company 1'))).show()", "e": 1966, "s": 1772, "text": null }, { "code": null, "e": 1974, "s": 1966, "text": "Output:" }, { "code": null, "e": 2242, "s": 1974, "text": "Where: where is similar to filter() function that is used to return the dataframe based on the given condition by removing the rows in the dataframe or by extracting the particular rows or columns from the dataframe. It can take a condition and returns the dataframe." }, { "code": null, "e": 2276, "s": 2242, "text": "where(dataframe.column condition)" }, { "code": null, "e": 2332, "s": 2276, "text": "Example 1: Python program to filter on multiple columns" }, { "code": null, "e": 2340, "s": 2332, "text": "Python3" }, { "code": "# select dataframe where ID less than# 3 or name is sridevi and comapny 1dataframe.where((dataframe.ID < 3) | ( (dataframe.NAME == 'sridevi') & (dataframe.Company == 'company 1'))).show()", "e": 2532, "s": 2340, "text": null }, { "code": null, "e": 2540, "s": 2532, "text": "Output:" }, { "code": null, "e": 2547, "s": 2540, "text": "Picked" }, { "code": null, "e": 2562, "s": 2547, "text": "Python-Pyspark" }, { "code": null, "e": 2569, "s": 2562, "text": "Python" }, { "code": null, "e": 2667, "s": 2569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2685, "s": 2667, "text": "Python Dictionary" }, { "code": null, "e": 2727, "s": 2685, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2749, "s": 2727, "text": "Enumerate() in Python" }, { "code": null, "e": 2784, "s": 2749, "text": "Read a file line by line in Python" }, { "code": null, "e": 2816, "s": 2784, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2845, "s": 2816, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2875, "s": 2845, "text": "Iterate over a list in Python" }, { "code": null, "e": 2902, "s": 2875, "text": "Python Classes and Objects" }, { "code": null, "e": 2938, "s": 2902, "text": "Convert integer to string in Python" } ]
Global Variables in MS SQL Server
19 Aug, 2020 Global variables are pre-defined system variables. It starts with @@. It provides information about the present user environment for SQL Server. SQL Server provides multiple global variables, which are very effective to use in Transact-SQL. The following are some frequently used global variables – @@SERVERNAME @@CONNECTIONS @@MAX_CONNECTIONS @@CPU_BUSY @@ERROR @@IDLE @@LANGUAGE @@TRANCOUNT @@VERSION These are explained as following below. @@SERVERNAME :This is used to find the name of the machine/computer on which SQL Server is running.Example –Select @@servernameOutput –SERVERXX\CTRXREST@@CONNECTIONS :This is used to find number of logins or attempted logins since SQL Server was last started.Example –Select @@connectionsOutput –59846824@@MAX_CONNECTIONS :This is used to find the maximum number of simultaneous connections that can be made with SQL Server or instance in this computer environment.Example –select @@max_connectionsOutput –32767@@CPU_BUSY :This is used to find the amount of time, in microseconds, that the CPU has spent doing SQL Server work since the last time SQL Server was running.Example –Select @@cpu_busyOutput –887468@@ERROR :This is used to check the error status (succeeded or failed) of the most recently executed statement. It contains Zero (0) if the previous transaction succeeded, else, it contains the last error number generated by the system.Example –Select @@errorOutput –0@@IDLE :The amount of time, in microseconds, that SQL Server has been idle since it was last started.Example –Select @@idleOutput –123691249@@LANGUAGE :This is used to find the name of the language that is currently used by the SQL Server.Example –Select @@languageOutput –us_english@@TRANCOUNT :This is used to count the number of open transactions in the current session.Example –Select @@trancountOutput –0@@VERSION :This is used to find the current version of the SQL Server Software.Example –Select @@versionOutput –Microsoft SQL Server 2014 (SP3-CU-GDR) (KB4535288) - 12.0.6372.1 (X64) Dec 12 2019 15:14:11 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor) @@SERVERNAME :This is used to find the name of the machine/computer on which SQL Server is running.Example –Select @@servernameOutput –SERVERXX\CTRXREST Select @@servername Output – SERVERXX\CTRXREST @@CONNECTIONS :This is used to find number of logins or attempted logins since SQL Server was last started.Example –Select @@connectionsOutput –59846824 Select @@connections Output – 59846824 @@MAX_CONNECTIONS :This is used to find the maximum number of simultaneous connections that can be made with SQL Server or instance in this computer environment.Example –select @@max_connectionsOutput –32767 select @@max_connections Output – 32767 @@CPU_BUSY :This is used to find the amount of time, in microseconds, that the CPU has spent doing SQL Server work since the last time SQL Server was running.Example –Select @@cpu_busyOutput –887468 Select @@cpu_busy Output – 887468 @@ERROR :This is used to check the error status (succeeded or failed) of the most recently executed statement. It contains Zero (0) if the previous transaction succeeded, else, it contains the last error number generated by the system.Example –Select @@errorOutput –0 Select @@error Output – 0 @@IDLE :The amount of time, in microseconds, that SQL Server has been idle since it was last started.Example –Select @@idleOutput –123691249 Select @@idle Output – 123691249 @@LANGUAGE :This is used to find the name of the language that is currently used by the SQL Server.Example –Select @@languageOutput –us_english Select @@language Output – us_english @@TRANCOUNT :This is used to count the number of open transactions in the current session.Example –Select @@trancountOutput –0 Select @@trancount Output – 0 @@VERSION :This is used to find the current version of the SQL Server Software.Example –Select @@versionOutput –Microsoft SQL Server 2014 (SP3-CU-GDR) (KB4535288) - 12.0.6372.1 (X64) Dec 12 2019 15:14:11 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor) Select @@version Output – Microsoft SQL Server 2014 (SP3-CU-GDR) (KB4535288) - 12.0.6372.1 (X64) Dec 12 2019 15:14:11 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor) DBMS-SQL SQL-Server 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? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2020" }, { "code": null, "e": 327, "s": 28, "text": "Global variables are pre-defined system variables. It starts with @@. It provides information about the present user environment for SQL Server. SQL Server provides multiple global variables, which are very effective to use in Transact-SQL. The following are some frequently used global variables –" }, { "code": null, "e": 340, "s": 327, "text": "@@SERVERNAME" }, { "code": null, "e": 354, "s": 340, "text": "@@CONNECTIONS" }, { "code": null, "e": 372, "s": 354, "text": "@@MAX_CONNECTIONS" }, { "code": null, "e": 383, "s": 372, "text": "@@CPU_BUSY" }, { "code": null, "e": 391, "s": 383, "text": "@@ERROR" }, { "code": null, "e": 398, "s": 391, "text": "@@IDLE" }, { "code": null, "e": 409, "s": 398, "text": "@@LANGUAGE" }, { "code": null, "e": 421, "s": 409, "text": "@@TRANCOUNT" }, { "code": null, "e": 431, "s": 421, "text": "@@VERSION" }, { "code": null, "e": 471, "s": 431, "text": "These are explained as following below." }, { "code": null, "e": 2174, "s": 471, "text": "@@SERVERNAME :This is used to find the name of the machine/computer on which SQL Server is running.Example –Select @@servernameOutput –SERVERXX\\CTRXREST@@CONNECTIONS :This is used to find number of logins or attempted logins since SQL Server was last started.Example –Select @@connectionsOutput –59846824@@MAX_CONNECTIONS :This is used to find the maximum number of simultaneous connections that can be made with SQL Server or instance in this computer environment.Example –select @@max_connectionsOutput –32767@@CPU_BUSY :This is used to find the amount of time, in microseconds, that the CPU has spent doing SQL Server work since the last time SQL Server was running.Example –Select @@cpu_busyOutput –887468@@ERROR :This is used to check the error status (succeeded or failed) of the most recently executed statement. It contains Zero (0) if the previous transaction succeeded, else, it contains the last error number generated by the system.Example –Select @@errorOutput –0@@IDLE :The amount of time, in microseconds, that SQL Server has been idle since it was last started.Example –Select @@idleOutput –123691249@@LANGUAGE :This is used to find the name of the language that is currently used by the SQL Server.Example –Select @@languageOutput –us_english@@TRANCOUNT :This is used to count the number of open transactions in the current session.Example –Select @@trancountOutput –0@@VERSION :This is used to find the current version of the SQL Server Software.Example –Select @@versionOutput –Microsoft SQL Server 2014 (SP3-CU-GDR) (KB4535288) - 12.0.6372.1 (X64)\nDec 12 2019 15:14:11\nCopyright (c) Microsoft Corporation\nStandard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)" }, { "code": null, "e": 2327, "s": 2174, "text": "@@SERVERNAME :This is used to find the name of the machine/computer on which SQL Server is running.Example –Select @@servernameOutput –SERVERXX\\CTRXREST" }, { "code": null, "e": 2347, "s": 2327, "text": "Select @@servername" }, { "code": null, "e": 2356, "s": 2347, "text": "Output –" }, { "code": null, "e": 2374, "s": 2356, "text": "SERVERXX\\CTRXREST" }, { "code": null, "e": 2527, "s": 2374, "text": "@@CONNECTIONS :This is used to find number of logins or attempted logins since SQL Server was last started.Example –Select @@connectionsOutput –59846824" }, { "code": null, "e": 2548, "s": 2527, "text": "Select @@connections" }, { "code": null, "e": 2557, "s": 2548, "text": "Output –" }, { "code": null, "e": 2566, "s": 2557, "text": "59846824" }, { "code": null, "e": 2774, "s": 2566, "text": "@@MAX_CONNECTIONS :This is used to find the maximum number of simultaneous connections that can be made with SQL Server or instance in this computer environment.Example –select @@max_connectionsOutput –32767" }, { "code": null, "e": 2799, "s": 2774, "text": "select @@max_connections" }, { "code": null, "e": 2808, "s": 2799, "text": "Output –" }, { "code": null, "e": 2814, "s": 2808, "text": "32767" }, { "code": null, "e": 3013, "s": 2814, "text": "@@CPU_BUSY :This is used to find the amount of time, in microseconds, that the CPU has spent doing SQL Server work since the last time SQL Server was running.Example –Select @@cpu_busyOutput –887468" }, { "code": null, "e": 3031, "s": 3013, "text": "Select @@cpu_busy" }, { "code": null, "e": 3040, "s": 3031, "text": "Output –" }, { "code": null, "e": 3047, "s": 3040, "text": "887468" }, { "code": null, "e": 3315, "s": 3047, "text": "@@ERROR :This is used to check the error status (succeeded or failed) of the most recently executed statement. It contains Zero (0) if the previous transaction succeeded, else, it contains the last error number generated by the system.Example –Select @@errorOutput –0" }, { "code": null, "e": 3330, "s": 3315, "text": "Select @@error" }, { "code": null, "e": 3339, "s": 3330, "text": "Output –" }, { "code": null, "e": 3341, "s": 3339, "text": "0" }, { "code": null, "e": 3482, "s": 3341, "text": "@@IDLE :The amount of time, in microseconds, that SQL Server has been idle since it was last started.Example –Select @@idleOutput –123691249" }, { "code": null, "e": 3496, "s": 3482, "text": "Select @@idle" }, { "code": null, "e": 3505, "s": 3496, "text": "Output –" }, { "code": null, "e": 3515, "s": 3505, "text": "123691249" }, { "code": null, "e": 3659, "s": 3515, "text": "@@LANGUAGE :This is used to find the name of the language that is currently used by the SQL Server.Example –Select @@languageOutput –us_english" }, { "code": null, "e": 3677, "s": 3659, "text": "Select @@language" }, { "code": null, "e": 3686, "s": 3677, "text": "Output –" }, { "code": null, "e": 3697, "s": 3686, "text": "us_english" }, { "code": null, "e": 3824, "s": 3697, "text": "@@TRANCOUNT :This is used to count the number of open transactions in the current session.Example –Select @@trancountOutput –0" }, { "code": null, "e": 3843, "s": 3824, "text": "Select @@trancount" }, { "code": null, "e": 3852, "s": 3843, "text": "Output –" }, { "code": null, "e": 3854, "s": 3852, "text": "0" }, { "code": null, "e": 4172, "s": 3854, "text": "@@VERSION :This is used to find the current version of the SQL Server Software.Example –Select @@versionOutput –Microsoft SQL Server 2014 (SP3-CU-GDR) (KB4535288) - 12.0.6372.1 (X64)\nDec 12 2019 15:14:11\nCopyright (c) Microsoft Corporation\nStandard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)" }, { "code": null, "e": 4189, "s": 4172, "text": "Select @@version" }, { "code": null, "e": 4198, "s": 4189, "text": "Output –" }, { "code": null, "e": 4404, "s": 4198, "text": "Microsoft SQL Server 2014 (SP3-CU-GDR) (KB4535288) - 12.0.6372.1 (X64)\nDec 12 2019 15:14:11\nCopyright (c) Microsoft Corporation\nStandard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)" }, { "code": null, "e": 4413, "s": 4404, "text": "DBMS-SQL" }, { "code": null, "e": 4424, "s": 4413, "text": "SQL-Server" }, { "code": null, "e": 4428, "s": 4424, "text": "SQL" }, { "code": null, "e": 4432, "s": 4428, "text": "SQL" }, { "code": null, "e": 4530, "s": 4432, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4596, "s": 4530, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 4620, "s": 4596, "text": "Window functions in SQL" }, { "code": null, "e": 4652, "s": 4620, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 4685, "s": 4652, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 4702, "s": 4685, "text": "SQL using Python" }, { "code": null, "e": 4732, "s": 4702, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 4810, "s": 4732, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 4846, "s": 4810, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 4877, "s": 4846, "text": "SQL Query to Compare Two Dates" } ]
Python | Pandas dataframe.aggregate()
19 Feb, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Dataframe.aggregate() function is used to apply some aggregation across one or more column. Aggregate using callable, string, dict, or list of string/callables. Most frequently used aggregations are: sum: Return the sum of the values for the requested axismin: Return the minimum of the values for the requested axismax: Return the maximum of the values for the requested axis Syntax: DataFrame.aggregate(func, axis=0, *args, **kwargs) Parameters:func : callable, string, dictionary, or list of string/callables. Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. For a DataFrame, can pass a dict, if the keys are DataFrame column names.axis : (default 0) {0 or ‘index’, 1 or ‘columns’} 0 or ‘index’: apply function to each column. 1 or ‘columns’: apply function to each row. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Returns: Aggregated DataFrame For link to CSV file Used in Code, click here Example #1: Aggregate ‘sum’ and ‘min’ function across all the columns in data frame. # importing pandas packageimport pandas as pd # making data frame from csv filedf = pd.read_csv("nba.csv") # printing the first 10 rows of the dataframedf[:10] Aggregation works with only numeric type columns. # Applying aggregation across all the columns # sum and min will be found for each # numeric type column in df dataframe df.aggregate(['sum', 'min']) Output:For each column which are having numeric values, minimum and sum of all values has been found. For dataframe df , we have four such columns Number, Age, Weight, Salary. Example #2: In Pandas, we can also apply different aggregation functions across different columns. For that, we need to pass a dictionary with key containing the column names and values containing the list of aggregation functions for any specific column. # importing pandas packageimport pandas as pd # making data frame from csv filedf = pd.read_csv("nba.csv") # We are going to find aggregation for these columnsdf.aggregate({"Number":['sum', 'min'], "Age":['max', 'min'], "Weight":['min', 'sum'], "Salary":['sum']}) Output:Separate aggregation has been applied to each column, if any specific aggregation is not applied on a column then it has NaN value corresponding to it.Python | Pandas dataframe.aggregate() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.aggregate() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=RCLtgM2LLhs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2021" }, { "code": null, "e": 266, "s": 52, "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": 466, "s": 266, "text": "Dataframe.aggregate() function is used to apply some aggregation across one or more column. Aggregate using callable, string, dict, or list of string/callables. Most frequently used aggregations are:" }, { "code": null, "e": 643, "s": 466, "text": "sum: Return the sum of the values for the requested axismin: Return the minimum of the values for the requested axismax: Return the maximum of the values for the requested axis" }, { "code": null, "e": 702, "s": 643, "text": "Syntax: DataFrame.aggregate(func, axis=0, *args, **kwargs)" }, { "code": null, "e": 1124, "s": 702, "text": "Parameters:func : callable, string, dictionary, or list of string/callables. Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. For a DataFrame, can pass a dict, if the keys are DataFrame column names.axis : (default 0) {0 or ‘index’, 1 or ‘columns’} 0 or ‘index’: apply function to each column. 1 or ‘columns’: apply function to each row." }, { "code": null, "e": 1133, "s": 1124, "text": "Chapters" }, { "code": null, "e": 1160, "s": 1133, "text": "descriptions off, selected" }, { "code": null, "e": 1210, "s": 1160, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1233, "s": 1210, "text": "captions off, selected" }, { "code": null, "e": 1241, "s": 1233, "text": "English" }, { "code": null, "e": 1265, "s": 1241, "text": "This is a modal window." }, { "code": null, "e": 1334, "s": 1265, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1356, "s": 1334, "text": "End of dialog window." }, { "code": null, "e": 1386, "s": 1356, "text": "Returns: Aggregated DataFrame" }, { "code": null, "e": 1432, "s": 1386, "text": "For link to CSV file Used in Code, click here" }, { "code": null, "e": 1517, "s": 1432, "text": "Example #1: Aggregate ‘sum’ and ‘min’ function across all the columns in data frame." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedf = pd.read_csv(\"nba.csv\") # printing the first 10 rows of the dataframedf[:10]", "e": 1679, "s": 1517, "text": null }, { "code": null, "e": 1729, "s": 1679, "text": "Aggregation works with only numeric type columns." }, { "code": "# Applying aggregation across all the columns # sum and min will be found for each # numeric type column in df dataframe df.aggregate(['sum', 'min'])", "e": 1880, "s": 1729, "text": null }, { "code": null, "e": 2068, "s": 1880, "text": "Output:For each column which are having numeric values, minimum and sum of all values has been found. For dataframe df , we have four such columns Number, Age, Weight, Salary. Example #2:" }, { "code": null, "e": 2312, "s": 2068, "text": "In Pandas, we can also apply different aggregation functions across different columns. For that, we need to pass a dictionary with key containing the column names and values containing the list of aggregation functions for any specific column." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedf = pd.read_csv(\"nba.csv\") # We are going to find aggregation for these columnsdf.aggregate({\"Number\":['sum', 'min'], \"Age\":['max', 'min'], \"Weight\":['min', 'sum'], \"Salary\":['sum']})", "e": 2618, "s": 2312, "text": null }, { "code": null, "e": 3668, "s": 2618, "text": "Output:Separate aggregation has been applied to each column, if any specific aggregation is not applied on a column then it has NaN value corresponding to it.Python | Pandas dataframe.aggregate() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.aggregate() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:11•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=RCLtgM2LLhs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 3692, "s": 3668, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3724, "s": 3692, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 3738, "s": 3724, "text": "Python-pandas" }, { "code": null, "e": 3745, "s": 3738, "text": "Python" }, { "code": null, "e": 3843, "s": 3745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3861, "s": 3843, "text": "Python Dictionary" }, { "code": null, "e": 3903, "s": 3861, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3925, "s": 3903, "text": "Enumerate() in Python" }, { "code": null, "e": 3960, "s": 3925, "text": "Read a file line by line in Python" }, { "code": null, "e": 3986, "s": 3960, "text": "Python String | replace()" }, { "code": null, "e": 4018, "s": 3986, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4047, "s": 4018, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4074, "s": 4047, "text": "Python Classes and Objects" }, { "code": null, "e": 4104, "s": 4074, "text": "Iterate over a list in Python" } ]
HTML | value Attribute
30 Nov, 2021 The value attribute in HTML is used to specify the value of the element with which it is used. It has different meaning for different HTML elements.Usage: It can be used with the following elements: <input>, <button>, <meter>, <li>, <option>, <progress>, and <param>, <output>. <input>: When the value attribute is present, it specifies the initial value of the input element.It has a different meaning for different input type: When present in “button”, “reset” and “submit” it specifies the text on the button. When present in “text”, “password” and “hidden” it specifies the initial value of the input field. When present in “checkbox”, “radio” and “image” it specifies the value associated with the input. Syntax:<input value = "value"> <input value = "value"> Example-1:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Input: <input type = "text" value = "GeeksforGeeks"> </body></html> <!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Input: <input type = "text" value = "GeeksforGeeks"> </body></html> Output: Example-2:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <input type = "button" value = "Click me!"> </body></html> <!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <input type = "button" value = "Click me!"> </body></html> Output: <button>: When the value attribute is present, it specifies the initial value of the button element. Syntax:<button value = "value"> <button value = "value"> Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <button id="btn" value="GeeksforGeeks" onclick="geek()"> Click me!</button> <p id="g"></p> <script> function geek() { var x = document.getElementById("btn").value; document.getElementById("g").innerHTML = "Welcome to " + x; } </script> </body></html> <!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <button id="btn" value="GeeksforGeeks" onclick="geek()"> Click me!</button> <p id="g"></p> <script> function geek() { var x = document.getElementById("btn").value; document.getElementById("g").innerHTML = "Welcome to " + x; } </script> </body></html> Output:Before clicking the button:After clicking the button: <meter>: It specifies the current value of the gauge. The value must be between min and max attribute. Syntax:<meter value = "value"> <meter value = "value"> Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Health: <meter min="0" low="40" high="90" max="100" value="60"></meter></p> </body></html> <!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Health: <meter min="0" low="40" high="90" max="100" value="60"></meter></p> </body></html> Output: <li>: When the value attribute is present, it specifies the initial value of the list item. It is only applicable on the ordered list. Syntax:<li value = "number">list item </li> <li value = "number">list item </li> number: specifies the value of the list item. Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body > <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Sorting Algorithms</p> <ol> <li value="50">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html> <!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body > <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Sorting Algorithms</p> <ol> <li value="50">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html> Output: <option>: When the value attribute is present, it specifies the value of the option element. Syntax:<option value = "value"></option> <option value = "value"></option> Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Sorting Algorithms: <select id="opt"> <option value="quick">Quick sort</option> <option value="merge">Merge sort</option> <option value="insertion">Insertion sort</option> </select> <button type="button" onclick="geek()">Click me!</button> <p id = "p"></p> <script> function geek() { var x = document.getElementById("opt").selectedIndex; var y = document.getElementsByTagName("option")[x].value; document.getElementById("p").innerHTML = "The selected option has value equals " + y + "."; } </script> </body></html> <!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Sorting Algorithms: <select id="opt"> <option value="quick">Quick sort</option> <option value="merge">Merge sort</option> <option value="insertion">Insertion sort</option> </select> <button type="button" onclick="geek()">Click me!</button> <p id = "p"></p> <script> function geek() { var x = document.getElementById("opt").selectedIndex; var y = document.getElementsByTagName("option")[x].value; document.getElementById("p").innerHTML = "The selected option has value equals " + y + "."; } </script> </body></html> Output:Before clicking the button:After clicking the button: <progress>: When the value attribute is present, it specifies the value of the progress element. Syntax:<progress value = "number"></progress> <progress value = "number"></progress> number specifies the initial value of the progress element. Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Progress: <progress value="65" max="100"> </progress> </body></html> <!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Progress: <progress value="65" max="100"> </progress> </body></html> Output: Supported Browsers: The browser supported by value attribute in progress element are listed below: Google Chrome Internet Explorer Firefox Opera Safari ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Nov, 2021" }, { "code": null, "e": 331, "s": 53, "text": "The value attribute in HTML is used to specify the value of the element with which it is used. It has different meaning for different HTML elements.Usage: It can be used with the following elements: <input>, <button>, <meter>, <li>, <option>, <progress>, and <param>, <output>." }, { "code": null, "e": 482, "s": 331, "text": "<input>: When the value attribute is present, it specifies the initial value of the input element.It has a different meaning for different input type:" }, { "code": null, "e": 566, "s": 482, "text": "When present in “button”, “reset” and “submit” it specifies the text on the button." }, { "code": null, "e": 665, "s": 566, "text": "When present in “text”, “password” and “hidden” it specifies the initial value of the input field." }, { "code": null, "e": 763, "s": 665, "text": "When present in “checkbox”, “radio” and “image” it specifies the value associated with the input." }, { "code": null, "e": 794, "s": 763, "text": "Syntax:<input value = \"value\">" }, { "code": null, "e": 818, "s": 794, "text": "<input value = \"value\">" }, { "code": null, "e": 1182, "s": 818, "text": "Example-1:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Input: <input type = \"text\" value = \"GeeksforGeeks\"> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Input: <input type = \"text\" value = \"GeeksforGeeks\"> </body></html>", "e": 1536, "s": 1182, "text": null }, { "code": null, "e": 1544, "s": 1536, "text": "Output:" }, { "code": null, "e": 1899, "s": 1544, "text": "Example-2:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <input type = \"button\" value = \"Click me!\"> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <input type = \"button\" value = \"Click me!\"> </body></html>", "e": 2244, "s": 1899, "text": null }, { "code": null, "e": 2252, "s": 2244, "text": "Output:" }, { "code": null, "e": 2353, "s": 2252, "text": "<button>: When the value attribute is present, it specifies the initial value of the button element." }, { "code": null, "e": 2385, "s": 2353, "text": "Syntax:<button value = \"value\">" }, { "code": null, "e": 2410, "s": 2385, "text": "<button value = \"value\">" }, { "code": null, "e": 3050, "s": 2410, "text": "Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <button id=\"btn\" value=\"GeeksforGeeks\" onclick=\"geek()\"> Click me!</button> <p id=\"g\"></p> <script> function geek() { var x = document.getElementById(\"btn\").value; document.getElementById(\"g\").innerHTML = \"Welcome to \" + x; } </script> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <button id=\"btn\" value=\"GeeksforGeeks\" onclick=\"geek()\"> Click me!</button> <p id=\"g\"></p> <script> function geek() { var x = document.getElementById(\"btn\").value; document.getElementById(\"g\").innerHTML = \"Welcome to \" + x; } </script> </body></html>", "e": 3682, "s": 3050, "text": null }, { "code": null, "e": 3743, "s": 3682, "text": "Output:Before clicking the button:After clicking the button:" }, { "code": null, "e": 3846, "s": 3743, "text": "<meter>: It specifies the current value of the gauge. The value must be between min and max attribute." }, { "code": null, "e": 3877, "s": 3846, "text": "Syntax:<meter value = \"value\">" }, { "code": null, "e": 3901, "s": 3877, "text": "<meter value = \"value\">" }, { "code": null, "e": 4312, "s": 3901, "text": "Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Health: <meter min=\"0\" low=\"40\" high=\"90\" max=\"100\" value=\"60\"></meter></p> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Health: <meter min=\"0\" low=\"40\" high=\"90\" max=\"100\" value=\"60\"></meter></p> </body></html>", "e": 4715, "s": 4312, "text": null }, { "code": null, "e": 4723, "s": 4715, "text": "Output:" }, { "code": null, "e": 4858, "s": 4723, "text": "<li>: When the value attribute is present, it specifies the initial value of the list item. It is only applicable on the ordered list." }, { "code": null, "e": 4902, "s": 4858, "text": "Syntax:<li value = \"number\">list item </li>" }, { "code": null, "e": 4939, "s": 4902, "text": "<li value = \"number\">list item </li>" }, { "code": null, "e": 4985, "s": 4939, "text": "number: specifies the value of the list item." }, { "code": null, "e": 5429, "s": 4985, "text": "Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body > <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Sorting Algorithms</p> <ol> <li value=\"50\">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body > <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> <p>Sorting Algorithms</p> <ol> <li value=\"50\">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html>", "e": 5865, "s": 5429, "text": null }, { "code": null, "e": 5873, "s": 5865, "text": "Output:" }, { "code": null, "e": 5966, "s": 5873, "text": "<option>: When the value attribute is present, it specifies the value of the option element." }, { "code": null, "e": 6007, "s": 5966, "text": "Syntax:<option value = \"value\"></option>" }, { "code": null, "e": 6041, "s": 6007, "text": "<option value = \"value\"></option>" }, { "code": null, "e": 7003, "s": 6041, "text": "Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Sorting Algorithms: <select id=\"opt\"> <option value=\"quick\">Quick sort</option> <option value=\"merge\">Merge sort</option> <option value=\"insertion\">Insertion sort</option> </select> <button type=\"button\" onclick=\"geek()\">Click me!</button> <p id = \"p\"></p> <script> function geek() { var x = document.getElementById(\"opt\").selectedIndex; var y = document.getElementsByTagName(\"option\")[x].value; document.getElementById(\"p\").innerHTML = \"The selected option has value equals \" + y + \".\"; } </script> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Sorting Algorithms: <select id=\"opt\"> <option value=\"quick\">Quick sort</option> <option value=\"merge\">Merge sort</option> <option value=\"insertion\">Insertion sort</option> </select> <button type=\"button\" onclick=\"geek()\">Click me!</button> <p id = \"p\"></p> <script> function geek() { var x = document.getElementById(\"opt\").selectedIndex; var y = document.getElementsByTagName(\"option\")[x].value; document.getElementById(\"p\").innerHTML = \"The selected option has value equals \" + y + \".\"; } </script> </body></html>", "e": 7957, "s": 7003, "text": null }, { "code": null, "e": 8018, "s": 7957, "text": "Output:Before clicking the button:After clicking the button:" }, { "code": null, "e": 8115, "s": 8018, "text": "<progress>: When the value attribute is present, it specifies the value of the progress element." }, { "code": null, "e": 8161, "s": 8115, "text": "Syntax:<progress value = \"number\"></progress>" }, { "code": null, "e": 8200, "s": 8161, "text": "<progress value = \"number\"></progress>" }, { "code": null, "e": 8260, "s": 8200, "text": "number specifies the initial value of the progress element." }, { "code": null, "e": 8636, "s": 8260, "text": "Example:<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Progress: <progress value=\"65\" max=\"100\"> </progress> </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML value Attribute </h2> Progress: <progress value=\"65\" max=\"100\"> </progress> </body></html>", "e": 9004, "s": 8636, "text": null }, { "code": null, "e": 9012, "s": 9004, "text": "Output:" }, { "code": null, "e": 9111, "s": 9012, "text": "Supported Browsers: The browser supported by value attribute in progress element are listed below:" }, { "code": null, "e": 9125, "s": 9111, "text": "Google Chrome" }, { "code": null, "e": 9143, "s": 9125, "text": "Internet Explorer" }, { "code": null, "e": 9151, "s": 9143, "text": "Firefox" }, { "code": null, "e": 9157, "s": 9151, "text": "Opera" }, { "code": null, "e": 9164, "s": 9157, "text": "Safari" }, { "code": null, "e": 9178, "s": 9164, "text": "ManasChhabra2" }, { "code": null, "e": 9194, "s": 9178, "text": "HTML-Attributes" }, { "code": null, "e": 9199, "s": 9194, "text": "HTML" }, { "code": null, "e": 9216, "s": 9199, "text": "Web Technologies" }, { "code": null, "e": 9221, "s": 9216, "text": "HTML" } ]
Given GCD G and LCM L, find number of possible pairs (a, b)
Difficulty Level : Medium We need to find number of possible pairs (a, b) such that GCD(a, b) is equal to given G and LCM (a, b) such that LCM(a, b) is equal to given L.Examples: Input : G = 2, L = 12 Output : 4 Explanation : There are 4 possible pairs : (2, 12), (4, 6), (6, 4), (12, 2) Input : G = 3, L = 6 Output : 2 Explanation : There are 2 possible pairs : (3, 6), (6, 3) Solution 1 (Simple): Since a and b both will be less than or equal to lcm(a, b) L, so we try all possible pairs that have product equal to L * G. Note that product of a and b is same as product of gcd(a, b) and lcm(a, b), a*b = G*L.Here is our algorithm p = G*L count = 0 for a = 1 to L if p%a == 0 and gcd(a, p/a) = G count++ end if end for return count C++ Java Python3 C# PHP Javascript // C++ program to find all pairs// with given GCD and LCM.#include <iostream>using namespace std; // C++ function to calculate GCD// of two numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} // C++ function to count number// of pairs with given GCD and LCMint countPairs(int G, int L){ // To store count int count = 0; // To store product a*b = G*L int p = G*L; // p/a will be b if a divides p for (int a=1; a<=L; a++) if (!(p%a) && gcd(a, p/a)==G) count++; return count;} // Driver code to test above functionsint main(){ int G = 2, L = 12; cout << "Total possible pair with GCD " << G; cout << " & LCM " << L; cout <<" = " << countPairs(G, L); return 0;} // Java program to find all pairs// with given GCD and LCM.public class GCD{ // Java function to calculate GCD // of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a , a); } // Java function to count number // of pairs with given GCD and LCM static int countPairs(int G, int L) { // To store count int count = 0; // To store product a*b = G*L int p = G*L; // p/a will be b if a divides p for (int a = 1; a<=L; a++) if ((p%a == 0) && gcd(a, p/a) == G) count++; return count; } public static void main (String[] args) { int G = 2, L = 12; System.out.print("Total possible pair with GCD " + G); System.out.print(" & LCM " + L); System.out.print(" = " + countPairs(G, L)); } } // This code is contributed by Saket Kumar # Python3 program to find all pairs# with given GCD and LCM.import math # Function to calculate GCD# of two numbersdef gcd(a, b): if (a == 0): return b return math.gcd(b % a, a) # Function to count number of# pairs with given GCD and LCMdef countPairs(G, L): # To store count count = 0 # To store product a*b = G*L p = G * L # p/a will be b if a divides p for a in range(1, L + 1): if (not (p % a) and math.gcd(a, p // a) == G): count += 1 return count # Driver Codeif __name__ == "__main__": G = 2 L = 12 print ("Total possible pair with GCD ", G, end = "") print (" & LCM ", L, end = "") print (" = ", countPairs(G, L)) # This code is contributed by ita_c // C# program to find all pairs// with given GCD and LCM.using System; class GCD{ // function to calculate // GCD of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a , a); } // Function to count number of // pairs with given GCD and LCM static int countPairs(int G, int L) { // To store count int count = 0; // To store product a * // b = G * L int p = G * L; // p / a will be b if // a divides p for (int a = 1; a <= L; a++) if ((p % a == 0) && gcd(a, p / a) == G) count++; return count; } // Driver Code public static void Main () { int G = 2, L = 12; Console.Write("Total possible pair with GCD " + G); Console.Write(" & LCM " + L); Console.Write(" = " + countPairs(G, L)); } } // This code is contributed by Nitin Mittal. <?php// PHP program to find all pairs// with given GCD and LCM. // function to calculate GCD// of two numbersfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // function to count number// of pairs with given GCD and LCMfunction countPairs( $G, $L){ // To store count $count = 0; // To store product a*b = G*L $p = $G * $L; // p/a will be b if a divides p for ($a = 1; $a <= $L; $a++) if (!($p % $a) and gcd($a, $p / $a) == $G) $count++; return $count;} // Driver Code $G = 2; $L = 12; echo "Total possible pair with GCD " , $G; echo " & LCM " , $L; echo " = " , countPairs($G, $L); // This code is contributed by anuj_67.?> <script>// javascript program to find all pairs// with given GCD and LCM. // javascript function to calculate GCD // of two numbers function gcd(a , b) { if (a == 0) return b; return gcd(b % a, a); } // javascript function to count number // of pairs with given GCD and LCM function countPairs(G , L) { // To store count var count = 0; // To store product a*b = G*L var p = G * L; // p/a will be b if a divides p for (let a = 1; a <= L; a++) if ((p % a == 0) && gcd(a, p / a) == G) count++; return count; } var G = 2, L = 12; document.write("Total possible pair with GCD " + G); document.write(" & LCM " + L); document.write(" = " + countPairs(G, L)); // This code is contributed by todaysgaurav</script> Total possible pair with GCD 2 & LCM 12 = 4 Auxiliary Space : O(1) Time Complexity: O( L * log(L) ). We have one for loop which iterates L times and in each iteration in the worst case, gcd will be called so O(log L) in the worst case for that call. Solution 2 (Efficient): We know that G * L = a * b Since G is gcd(a, b), both a and b will have G as its factor Let A = a/G Let B = b/G From above definitions of A and B, GCD of A and B must be 1. We can write, a = G * A, b = G * B G * L = G * A * G * B A * B = L / G Now, we need to find all possible pairs of (A, B) such that gcd(A, B) = 1 and A*B = L/G Let say p1, p2, ..., pk are prime factors of L/G. Then if p1 is present in prime factorization of A then p1 can't be present in prime factorization of B because gcd(A, B) = 1. Therefore each prime factor pi will be present in either A or B. Hence total possible ways to divide all prime factors among A and B is 2^k, where L/G has k distinct prime factors. Below is implementation of above steps. C++ Java Python3 C# PHP Javascript // Efficient C++ program to count all // pairs with GCD and LCM. #include <iostream> using namespace std; // A function to find number of distinct // prime factors of a given number n int totalPrimeFactors(int n) { // To keep track of count int count = 0; // 2s that divide n if (!(n%2)) { count++; while (!(n%2)) n /= 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i*i <= n; i = i+2) { // i divides n if (!(n%i)) { count++; while (!(n%i)) n /= i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n>2) count++; return count; } // C++ function to count number // of pair with given GCD and LCM int countPairs(int G, int L) { if (L % G != 0) return 0; int div = L/G; // answer is 2^totalPrimeFactors(L/G) return (1<<totalPrimeFactors(div)); } // Driver code to test above functions int main() { int G = 2, L = 12; cout << "Total possible pair with GCD" << G; cout << " &LCM " << L; cout << " = " << countPairs(G, L); return 0; } // Efficient Java program to count all// pairs with GCD and LCM.public class GCD{ // A function to find number of distinct // prime factors of a given number n static int totalPrimeFactors(int n) { // To keep track of count int count = 0; // 2s that divide n if ((n%2 == 0)) { count++; while ((n%2 == 0)) n /= 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i*i <= n; i = i+2) { // i divides n if ((n%i == 0)) count++; while ((n%i == 0)) n /= 2; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) count++; return count; } // Java function to count number // of pair with given GCD and LCM static int countPairs(int G, int L) { if (L % G != 0) return 0; int div = L/G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); } // Driver function public static void main (String[] args) { int G = 2, L = 12; System.out.print("Total possible pair with GCD " + G); System.out.print(" & LCM " + L); System.out.print(" = " + countPairs(G, L)); }} // This code is contributed by Saket Kumar # Efficient python3 program to count# all pairs with GCD and LCM. # A function to find number of distinct# prime factors of a given number ndef totalPrimeFactors(n): # To keep track of count count = 0; # 2s that divide n if ((n % 2) == 0): count += 1; while ((n % 2) == 0): n //= 2; # n must be odd at this point. # So we can skip one element # (Note i = i +2) i = 3; while (i * i <= n): # i divides n if ((n % i) == 0): count += 1; while ((n % i) == 0): n //= i; i += 2; # This condition is to handle the # case when n is a prime number # greater than 2 if (n > 2): count += 1; return count; # function to count number# of pair with given GCD and LCMdef countPairs(G, L): if (L % G != 0): return 0; div = int(L / G); # answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); # Driver CodeG = 2;L = 12;print("Total possible pair with GCD", G, "& LCM", L, end = "");print(" =", countPairs(G, L)); # This code is contributed by mits // Efficient C# program to count all// pairs with GCD and LCM.using System; class GFG { // A function to find number // of distinct prime factors // of a given number n static int totalPrimeFactors(int n) { // To keep track of count int count = 0; // 2s that divide n if ((n % 2 == 0)) { count++; while ((n % 2 == 0)) n /= 2; } // n must be odd at this // point. So we can skip // one element (Note i = i+2) for (int i = 3; i * i <= n; i = i + 2) { // i divides n if ((n % i == 0)) count++; while ((n % i == 0)) n /= 2; } // This condition is to // handle the case when n // is a prime number // greater than 2 if (n > 2) count++; return count; } // function to count number // of pair with given GCD and LCM static int countPairs(int G, int L) { if (L % G != 0) return 0; int div = L/G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); } // Driver Code public static void Main (String[] args) { int G = 2, L = 12; Console.Write("Total possible pair with GCD " + G); Console.Write(" & LCM " + L); Console.Write(" = " + countPairs(G, L)); }} // This code is contributed by Anshul Aggarwal. <?php// Efficient php program to count all// pairs with GCD and LCM. // A function to find number of distinct// prime factors of a given number nfunction totalPrimeFactors($n){ // To keep track of count $count = 0; // 2s that divide n if (!($n % 2)) { $count++; while (!($n % 2)) $n /= 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for ($i = 3; $i * $i <= $n; $i = $i + 2) { // i divides n if (!($n % $i)) { $count++; while (!($n % $i)) $n /= $i; } } // This condition is to // handle the case when n // is a prime number greater // than 2 if ($n > 2) $count++; return $count;} // function to count number// of pair with given GCD and LCMfunction countPairs($G, $L){ if ($L % $G != 0) return 0; $div = $L/$G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors($div));} // Driver Code $G = 2; $L = 12; echo "Total possible pair with GCD " , $G; echo " & LCM " , $L; echo " = " ,countPairs($G, $L); return 0; // This code is contributed by nitin mittal.?> <script> // Efficient javascript program to count all// pairs with GCD and LCM. // A function to find number of distinct // prime factors of a given number n function totalPrimeFactors(n) { // To keep track of count var count = 0; // 2s that divide n if ((n % 2 == 0)) { count++; while ((n % 2 == 0)) n = parseInt(n/2); } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (i = 3; i * i <= n; i = i + 2) { // i divides n if ((n % i == 0)) count++; while ((n % i == 0)) n = parseInt(n/2); } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) count++; return count; } // javascript function to count number // of pair with given GCD and LCM function countPairs(G , L) { if (L % G != 0) return 0; var div = L / G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); } // Driver function var G = 2, L = 12; document.write("Total possible pair with GCD " + G); document.write(" & LCM " + L); document.write(" = " + countPairs(G, L)); // This code is contributed by aashish1995 </script> Output: Total possible pair with GCD 2 & LCM 12 = 4 Analysis of above algorithm Auxiliary Space: O(1) Time Complexity : O(sqrt(L/G) * log(L/G)). For time complexity to find number of distinct prime factors we need O(sqrt(L/G) * log (L/G)) time, Here sqrt(L) iterations are there in the worst case and in each iteration O(log L/G) iterations again.This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Anshul_Aggarwal vt_m ukasp Mithun Kumar todaysgaurav aashish1995 gulshankumarar231 kk9826225 GCD-LCM Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 26, "s": 0, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 181, "s": 26, "text": "We need to find number of possible pairs (a, b) such that GCD(a, b) is equal to given G and LCM (a, b) such that LCM(a, b) is equal to given L.Examples: " }, { "code": null, "e": 291, "s": 181, "text": "Input : G = 2, L = 12\nOutput : 4\nExplanation : There are 4 possible pairs :\n (2, 12), (4, 6), (6, 4), (12, 2)" }, { "code": null, "e": 383, "s": 293, "text": "Input : G = 3, L = 6\nOutput : 2\nExplanation : There are 2 possible pairs :\n(3, 6), (6, 3)" }, { "code": null, "e": 408, "s": 387, "text": "Solution 1 (Simple):" }, { "code": null, "e": 643, "s": 408, "text": "Since a and b both will be less than or equal to lcm(a, b) L, so we try all possible pairs that have product equal to L * G. Note that product of a and b is same as product of gcd(a, b) and lcm(a, b), a*b = G*L.Here is our algorithm " }, { "code": null, "e": 760, "s": 643, "text": "p = G*L\ncount = 0\nfor a = 1 to L\n if p%a == 0 and gcd(a, p/a) = G\n count++\n end if\nend for\nreturn count" }, { "code": null, "e": 766, "s": 762, "text": "C++" }, { "code": null, "e": 771, "s": 766, "text": "Java" }, { "code": null, "e": 779, "s": 771, "text": "Python3" }, { "code": null, "e": 782, "s": 779, "text": "C#" }, { "code": null, "e": 786, "s": 782, "text": "PHP" }, { "code": null, "e": 797, "s": 786, "text": "Javascript" }, { "code": "// C++ program to find all pairs// with given GCD and LCM.#include <iostream>using namespace std; // C++ function to calculate GCD// of two numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} // C++ function to count number// of pairs with given GCD and LCMint countPairs(int G, int L){ // To store count int count = 0; // To store product a*b = G*L int p = G*L; // p/a will be b if a divides p for (int a=1; a<=L; a++) if (!(p%a) && gcd(a, p/a)==G) count++; return count;} // Driver code to test above functionsint main(){ int G = 2, L = 12; cout << \"Total possible pair with GCD \" << G; cout << \" & LCM \" << L; cout <<\" = \" << countPairs(G, L); return 0;}", "e": 1546, "s": 797, "text": null }, { "code": "// Java program to find all pairs// with given GCD and LCM.public class GCD{ // Java function to calculate GCD // of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a , a); } // Java function to count number // of pairs with given GCD and LCM static int countPairs(int G, int L) { // To store count int count = 0; // To store product a*b = G*L int p = G*L; // p/a will be b if a divides p for (int a = 1; a<=L; a++) if ((p%a == 0) && gcd(a, p/a) == G) count++; return count; } public static void main (String[] args) { int G = 2, L = 12; System.out.print(\"Total possible pair with GCD \" + G); System.out.print(\" & LCM \" + L); System.out.print(\" = \" + countPairs(G, L)); } } // This code is contributed by Saket Kumar", "e": 2517, "s": 1546, "text": null }, { "code": "# Python3 program to find all pairs# with given GCD and LCM.import math # Function to calculate GCD# of two numbersdef gcd(a, b): if (a == 0): return b return math.gcd(b % a, a) # Function to count number of# pairs with given GCD and LCMdef countPairs(G, L): # To store count count = 0 # To store product a*b = G*L p = G * L # p/a will be b if a divides p for a in range(1, L + 1): if (not (p % a) and math.gcd(a, p // a) == G): count += 1 return count # Driver Codeif __name__ == \"__main__\": G = 2 L = 12 print (\"Total possible pair with GCD \", G, end = \"\") print (\" & LCM \", L, end = \"\") print (\" = \", countPairs(G, L)) # This code is contributed by ita_c", "e": 3289, "s": 2517, "text": null }, { "code": "// C# program to find all pairs// with given GCD and LCM.using System; class GCD{ // function to calculate // GCD of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a , a); } // Function to count number of // pairs with given GCD and LCM static int countPairs(int G, int L) { // To store count int count = 0; // To store product a * // b = G * L int p = G * L; // p / a will be b if // a divides p for (int a = 1; a <= L; a++) if ((p % a == 0) && gcd(a, p / a) == G) count++; return count; } // Driver Code public static void Main () { int G = 2, L = 12; Console.Write(\"Total possible pair with GCD \" + G); Console.Write(\" & LCM \" + L); Console.Write(\" = \" + countPairs(G, L)); } } // This code is contributed by Nitin Mittal.", "e": 4317, "s": 3289, "text": null }, { "code": "<?php// PHP program to find all pairs// with given GCD and LCM. // function to calculate GCD// of two numbersfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // function to count number// of pairs with given GCD and LCMfunction countPairs( $G, $L){ // To store count $count = 0; // To store product a*b = G*L $p = $G * $L; // p/a will be b if a divides p for ($a = 1; $a <= $L; $a++) if (!($p % $a) and gcd($a, $p / $a) == $G) $count++; return $count;} // Driver Code $G = 2; $L = 12; echo \"Total possible pair with GCD \" , $G; echo \" & LCM \" , $L; echo \" = \" , countPairs($G, $L); // This code is contributed by anuj_67.?>", "e": 5053, "s": 4317, "text": null }, { "code": "<script>// javascript program to find all pairs// with given GCD and LCM. // javascript function to calculate GCD // of two numbers function gcd(a , b) { if (a == 0) return b; return gcd(b % a, a); } // javascript function to count number // of pairs with given GCD and LCM function countPairs(G , L) { // To store count var count = 0; // To store product a*b = G*L var p = G * L; // p/a will be b if a divides p for (let a = 1; a <= L; a++) if ((p % a == 0) && gcd(a, p / a) == G) count++; return count; } var G = 2, L = 12; document.write(\"Total possible pair with GCD \" + G); document.write(\" & LCM \" + L); document.write(\" = \" + countPairs(G, L)); // This code is contributed by todaysgaurav</script>", "e": 5908, "s": 5053, "text": null }, { "code": null, "e": 5952, "s": 5908, "text": "Total possible pair with GCD 2 & LCM 12 = 4" }, { "code": null, "e": 6159, "s": 5952, "text": "Auxiliary Space : O(1) Time Complexity: O( L * log(L) ). We have one for loop which iterates L times and in each iteration in the worst case, gcd will be called so O(log L) in the worst case for that call. " }, { "code": null, "e": 6183, "s": 6159, "text": "Solution 2 (Efficient):" }, { "code": null, "e": 6877, "s": 6183, "text": "We know that G * L = a * b\nSince G is gcd(a, b), both a and b will have G as its factor\nLet A = a/G\nLet B = b/G\n\nFrom above definitions of A and B, GCD of A and B must be 1.\nWe can write, a = G * A, b = G * B\n\nG * L = G * A * G * B\nA * B = L / G\nNow, we need to find all possible pairs of (A, B)\nsuch that gcd(A, B) = 1 and A*B = L/G\nLet say p1, p2, ..., pk are prime factors of L/G.\nThen if p1 is present in prime factorization of A then p1\ncan't be present in prime factorization of B because \ngcd(A, B) = 1.\nTherefore each prime factor pi will be present in either\nA or B. Hence total possible ways to divide all prime \nfactors among A and B is 2^k, where L/G has k distinct \nprime factors." }, { "code": null, "e": 6918, "s": 6877, "text": "Below is implementation of above steps. " }, { "code": null, "e": 6922, "s": 6918, "text": "C++" }, { "code": null, "e": 6927, "s": 6922, "text": "Java" }, { "code": null, "e": 6935, "s": 6927, "text": "Python3" }, { "code": null, "e": 6938, "s": 6935, "text": "C#" }, { "code": null, "e": 6942, "s": 6938, "text": "PHP" }, { "code": null, "e": 6953, "s": 6942, "text": "Javascript" }, { "code": "// Efficient C++ program to count all // pairs with GCD and LCM. #include <iostream> using namespace std; // A function to find number of distinct // prime factors of a given number n int totalPrimeFactors(int n) { // To keep track of count int count = 0; // 2s that divide n if (!(n%2)) { count++; while (!(n%2)) n /= 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i*i <= n; i = i+2) { // i divides n if (!(n%i)) { count++; while (!(n%i)) n /= i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n>2) count++; return count; } // C++ function to count number // of pair with given GCD and LCM int countPairs(int G, int L) { if (L % G != 0) return 0; int div = L/G; // answer is 2^totalPrimeFactors(L/G) return (1<<totalPrimeFactors(div)); } // Driver code to test above functions int main() { int G = 2, L = 12; cout << \"Total possible pair with GCD\" << G; cout << \" &LCM \" << L; cout << \" = \" << countPairs(G, L); return 0; }", "e": 8434, "s": 6953, "text": null }, { "code": "// Efficient Java program to count all// pairs with GCD and LCM.public class GCD{ // A function to find number of distinct // prime factors of a given number n static int totalPrimeFactors(int n) { // To keep track of count int count = 0; // 2s that divide n if ((n%2 == 0)) { count++; while ((n%2 == 0)) n /= 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i*i <= n; i = i+2) { // i divides n if ((n%i == 0)) count++; while ((n%i == 0)) n /= 2; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) count++; return count; } // Java function to count number // of pair with given GCD and LCM static int countPairs(int G, int L) { if (L % G != 0) return 0; int div = L/G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); } // Driver function public static void main (String[] args) { int G = 2, L = 12; System.out.print(\"Total possible pair with GCD \" + G); System.out.print(\" & LCM \" + L); System.out.print(\" = \" + countPairs(G, L)); }} // This code is contributed by Saket Kumar", "e": 9905, "s": 8434, "text": null }, { "code": "# Efficient python3 program to count# all pairs with GCD and LCM. # A function to find number of distinct# prime factors of a given number ndef totalPrimeFactors(n): # To keep track of count count = 0; # 2s that divide n if ((n % 2) == 0): count += 1; while ((n % 2) == 0): n //= 2; # n must be odd at this point. # So we can skip one element # (Note i = i +2) i = 3; while (i * i <= n): # i divides n if ((n % i) == 0): count += 1; while ((n % i) == 0): n //= i; i += 2; # This condition is to handle the # case when n is a prime number # greater than 2 if (n > 2): count += 1; return count; # function to count number# of pair with given GCD and LCMdef countPairs(G, L): if (L % G != 0): return 0; div = int(L / G); # answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); # Driver CodeG = 2;L = 12;print(\"Total possible pair with GCD\", G, \"& LCM\", L, end = \"\");print(\" =\", countPairs(G, L)); # This code is contributed by mits", "e": 11035, "s": 9905, "text": null }, { "code": "// Efficient C# program to count all// pairs with GCD and LCM.using System; class GFG { // A function to find number // of distinct prime factors // of a given number n static int totalPrimeFactors(int n) { // To keep track of count int count = 0; // 2s that divide n if ((n % 2 == 0)) { count++; while ((n % 2 == 0)) n /= 2; } // n must be odd at this // point. So we can skip // one element (Note i = i+2) for (int i = 3; i * i <= n; i = i + 2) { // i divides n if ((n % i == 0)) count++; while ((n % i == 0)) n /= 2; } // This condition is to // handle the case when n // is a prime number // greater than 2 if (n > 2) count++; return count; } // function to count number // of pair with given GCD and LCM static int countPairs(int G, int L) { if (L % G != 0) return 0; int div = L/G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); } // Driver Code public static void Main (String[] args) { int G = 2, L = 12; Console.Write(\"Total possible pair with GCD \" + G); Console.Write(\" & LCM \" + L); Console.Write(\" = \" + countPairs(G, L)); }} // This code is contributed by Anshul Aggarwal.", "e": 12614, "s": 11035, "text": null }, { "code": "<?php// Efficient php program to count all// pairs with GCD and LCM. // A function to find number of distinct// prime factors of a given number nfunction totalPrimeFactors($n){ // To keep track of count $count = 0; // 2s that divide n if (!($n % 2)) { $count++; while (!($n % 2)) $n /= 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for ($i = 3; $i * $i <= $n; $i = $i + 2) { // i divides n if (!($n % $i)) { $count++; while (!($n % $i)) $n /= $i; } } // This condition is to // handle the case when n // is a prime number greater // than 2 if ($n > 2) $count++; return $count;} // function to count number// of pair with given GCD and LCMfunction countPairs($G, $L){ if ($L % $G != 0) return 0; $div = $L/$G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors($div));} // Driver Code $G = 2; $L = 12; echo \"Total possible pair with GCD \" , $G; echo \" & LCM \" , $L; echo \" = \" ,countPairs($G, $L); return 0; // This code is contributed by nitin mittal.?>", "e": 13834, "s": 12614, "text": null }, { "code": "<script> // Efficient javascript program to count all// pairs with GCD and LCM. // A function to find number of distinct // prime factors of a given number n function totalPrimeFactors(n) { // To keep track of count var count = 0; // 2s that divide n if ((n % 2 == 0)) { count++; while ((n % 2 == 0)) n = parseInt(n/2); } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (i = 3; i * i <= n; i = i + 2) { // i divides n if ((n % i == 0)) count++; while ((n % i == 0)) n = parseInt(n/2); } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) count++; return count; } // javascript function to count number // of pair with given GCD and LCM function countPairs(G , L) { if (L % G != 0) return 0; var div = L / G; // answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); } // Driver function var G = 2, L = 12; document.write(\"Total possible pair with GCD \" + G); document.write(\" & LCM \" + L); document.write(\" = \" + countPairs(G, L)); // This code is contributed by aashish1995 </script>", "e": 15218, "s": 13834, "text": null }, { "code": null, "e": 15227, "s": 15218, "text": "Output: " }, { "code": null, "e": 15271, "s": 15227, "text": "Total possible pair with GCD 2 & LCM 12 = 4" }, { "code": null, "e": 15989, "s": 15271, "text": "Analysis of above algorithm Auxiliary Space: O(1) Time Complexity : O(sqrt(L/G) * log(L/G)). For time complexity to find number of distinct prime factors we need O(sqrt(L/G) * log (L/G)) time, Here sqrt(L) iterations are there in the worst case and in each iteration O(log L/G) iterations again.This article is contributed by Pratik Chhajer. 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": 16002, "s": 15989, "text": "nitin mittal" }, { "code": null, "e": 16018, "s": 16002, "text": "Anshul_Aggarwal" }, { "code": null, "e": 16023, "s": 16018, "text": "vt_m" }, { "code": null, "e": 16029, "s": 16023, "text": "ukasp" }, { "code": null, "e": 16042, "s": 16029, "text": "Mithun Kumar" }, { "code": null, "e": 16055, "s": 16042, "text": "todaysgaurav" }, { "code": null, "e": 16067, "s": 16055, "text": "aashish1995" }, { "code": null, "e": 16085, "s": 16067, "text": "gulshankumarar231" }, { "code": null, "e": 16095, "s": 16085, "text": "kk9826225" }, { "code": null, "e": 16103, "s": 16095, "text": "GCD-LCM" }, { "code": null, "e": 16116, "s": 16103, "text": "Mathematical" }, { "code": null, "e": 16129, "s": 16116, "text": "Mathematical" } ]
Print nodes at k distance from root
16 Jun, 2022 Given a root of a tree, and an integer k. Print all the nodes which are at k distance from root. For example, in the below tree, 4, 5 & 8 are at distance 2 from root. 1 / \ 2 3 / \ / 4 5 8 The problem can be solved using recursion. Thanks to eldho for suggesting the solution. Implementation: C++ C Java Python3 C# Javascript #include<bits/stdc++.h> using namespace std; /* A binary tree node has data,pointer to left child anda pointer to right child */class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; void printKDistant(node *root , int k){ if(root == NULL|| k < 0 ) return; if( k == 0 ) { cout << root->data << " "; return; } printKDistant( root->left, k - 1 ) ; printKDistant( root->right, k - 1 ) ; } /* Driver code*/int main(){ /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 */ node *root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); root->right->left = new node(8); printKDistant(root, 2); return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; void printKDistant(struct node *root , int k) { if(root == NULL|| k < 0 ) return; if( k == 0 ) { printf( "%d ", root->data ); return ; } printKDistant( root->left, k-1 ) ; printKDistant( root->right, k-1 ) ; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(8); printKDistant(root, 2); getchar(); return 0;} // Java program to print nodes at k distance from root /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; void printKDistant(Node node, int k) { if (node == null|| k < 0 ) //Base case return; if (k == 0) { System.out.print(node.data + " "); return; } //recursively traversing printKDistant(node.left, k - 1); printKDistant(node.right, k - 1); } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(8); tree.printKDistant(tree.root, 2); }} // This code has been contributed by Mayank Jaiswal # Python program to find the nodes at k distance from root # A Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None def printKDistant(root, k): if root is None: return if k == 0: print (root.data,end=' ') else: printKDistant(root.left, k-1) printKDistant(root.right, k-1) # Driver program to test above function""" Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8"""root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(8) printKDistant(root, 2) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) using System; // c# program to print nodes at k distance from root /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; public virtual void printKDistant(Node node, int k) { if (node == null|| k < 0 ) { return; } if (k == 0) { Console.Write(node.data + " "); return; } printKDistant(node.left, k - 1); printKDistant(node.right, k - 1); } /* Driver program to test above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(8); tree.printKDistant(tree.root, 2); }} // This code is contributed by Shrikant13 <script> // Javascript program to print nodes at k distance from root /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root =null; function printKDistant(node, k){ if (node == null|| k < 0 ) { return; } if (k == 0) { document.write(node.data + " "); return; } printKDistant(node.left, k - 1); printKDistant(node.right, k - 1); } /* Driver program to test above functions */ /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 */root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(8);printKDistant(root, 2); // This code is contributed by importantly.</script> 4 5 8 Time Complexity: O(n) where n is number of nodes in the given binary tree. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Space Complexity : O(height of the binary tree). Note- If it’s true print the node – Always check the K distance == 0 at every node the left or right subtree – Decrement the distance by 1 when you are passing to its subtree Another Approach– We can do a level order traversal and keep track of the level.when current level is equal to k, then print all the nodes of that level. Python3 # Python program to find the nodes at k distance from root # A Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None def printKDistant(root, k): # check if root is None if root is None: return q = [] # ans = [] q.append(root) lvl = 0 # tracking of level while(q): n = len(q) # when lvl becomes k we add all values of q in ans. if lvl == k: for i in range(n): print((q[i].data), end=" ") return for i in range(1, n+1): temp = q.pop(0) if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) lvl += 1 # if after traversing ,if lvl is less than k , # that means nodes at k distance does not exist. if lvl < k: return # Driver program to test above function""" Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8"""root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(8) printKDistant(root, 2)#this code is contributed by Vivek Maddeshiya 4 5 8 Time Complexity: O(n) where n is number of nodes in the given binary tree. Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem. shrikanth13 rathbhupendra code_rama importantly krishna_97 amartyaghoshgfg vivekmaddheshiya205 hardikkoriintern Amazon Microsoft Ola Cabs Tree Amazon Microsoft Ola Cabs Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Introduction to Tree Data Structure Inorder Tree Traversal without Recursion What is Data Structure: Types, Classifications and Applications Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Diameter of a Binary Tree Lowest Common Ancestor in a Binary Tree | Set 1 Decision Tree Construct Tree from given Inorder and Preorder traversals
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 220, "s": 52, "text": "Given a root of a tree, and an integer k. Print all the nodes which are at k distance from root. For example, in the below tree, 4, 5 & 8 are at distance 2 from root. " }, { "code": null, "e": 299, "s": 220, "text": " 1\n / \\\n 2 3\n / \\ /\n 4 5 8 " }, { "code": null, "e": 388, "s": 299, "text": "The problem can be solved using recursion. Thanks to eldho for suggesting the solution. " }, { "code": null, "e": 404, "s": 388, "text": "Implementation:" }, { "code": null, "e": 408, "s": 404, "text": "C++" }, { "code": null, "e": 410, "s": 408, "text": "C" }, { "code": null, "e": 415, "s": 410, "text": "Java" }, { "code": null, "e": 423, "s": 415, "text": "Python3" }, { "code": null, "e": 426, "s": 423, "text": "C#" }, { "code": null, "e": 437, "s": 426, "text": "Javascript" }, { "code": "#include<bits/stdc++.h> using namespace std; /* A binary tree node has data,pointer to left child anda pointer to right child */class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; void printKDistant(node *root , int k){ if(root == NULL|| k < 0 ) return; if( k == 0 ) { cout << root->data << \" \"; return; } printKDistant( root->left, k - 1 ) ; printKDistant( root->right, k - 1 ) ; } /* Driver code*/int main(){ /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8 */ node *root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); root->right->left = new node(8); printKDistant(root, 2); return 0;} // This code is contributed by rathbhupendra", "e": 1538, "s": 437, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; void printKDistant(struct node *root , int k) { if(root == NULL|| k < 0 ) return; if( k == 0 ) { printf( \"%d \", root->data ); return ; } printKDistant( root->left, k-1 ) ; printKDistant( root->right, k-1 ) ; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(8); printKDistant(root, 2); getchar(); return 0;}", "e": 2701, "s": 1538, "text": null }, { "code": "// Java program to print nodes at k distance from root /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; void printKDistant(Node node, int k) { if (node == null|| k < 0 ) //Base case return; if (k == 0) { System.out.print(node.data + \" \"); return; } //recursively traversing printKDistant(node.left, k - 1); printKDistant(node.right, k - 1); } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(8); tree.printKDistant(tree.root, 2); }} // This code has been contributed by Mayank Jaiswal", "e": 3991, "s": 2701, "text": null }, { "code": "# Python program to find the nodes at k distance from root # A Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None def printKDistant(root, k): if root is None: return if k == 0: print (root.data,end=' ') else: printKDistant(root.left, k-1) printKDistant(root.right, k-1) # Driver program to test above function\"\"\" Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8\"\"\"root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(8) printKDistant(root, 2) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 4786, "s": 3991, "text": null }, { "code": "using System; // c# program to print nodes at k distance from root /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; public virtual void printKDistant(Node node, int k) { if (node == null|| k < 0 ) { return; } if (k == 0) { Console.Write(node.data + \" \"); return; } printKDistant(node.left, k - 1); printKDistant(node.right, k - 1); } /* Driver program to test above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(8); tree.printKDistant(tree.root, 2); }} // This code is contributed by Shrikant13", "e": 6089, "s": 4786, "text": null }, { "code": "<script> // Javascript program to print nodes at k distance from root /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root =null; function printKDistant(node, k){ if (node == null|| k < 0 ) { return; } if (k == 0) { document.write(node.data + \" \"); return; } printKDistant(node.left, k - 1); printKDistant(node.right, k - 1); } /* Driver program to test above functions */ /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8 */root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(8);printKDistant(root, 2); // This code is contributed by importantly.</script>", "e": 7009, "s": 6089, "text": null }, { "code": null, "e": 7016, "s": 7009, "text": "4 5 8 " }, { "code": null, "e": 7091, "s": 7016, "text": "Time Complexity: O(n) where n is number of nodes in the given binary tree." }, { "code": null, "e": 7100, "s": 7091, "text": "Chapters" }, { "code": null, "e": 7127, "s": 7100, "text": "descriptions off, selected" }, { "code": null, "e": 7177, "s": 7127, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 7200, "s": 7177, "text": "captions off, selected" }, { "code": null, "e": 7208, "s": 7200, "text": "English" }, { "code": null, "e": 7226, "s": 7208, "text": "default, selected" }, { "code": null, "e": 7250, "s": 7226, "text": "This is a modal window." }, { "code": null, "e": 7319, "s": 7250, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 7341, "s": 7319, "text": "End of dialog window." }, { "code": null, "e": 7390, "s": 7341, "text": "Space Complexity : O(height of the binary tree)." }, { "code": null, "e": 7396, "s": 7390, "text": "Note-" }, { "code": null, "e": 7473, "s": 7396, "text": "If it’s true print the node – Always check the K distance == 0 at every node" }, { "code": null, "e": 7566, "s": 7473, "text": "the left or right subtree – Decrement the distance by 1 when you are passing to its subtree " }, { "code": null, "e": 7720, "s": 7566, "text": "Another Approach– We can do a level order traversal and keep track of the level.when current level is equal to k, then print all the nodes of that level." }, { "code": null, "e": 7728, "s": 7720, "text": "Python3" }, { "code": "# Python program to find the nodes at k distance from root # A Binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None def printKDistant(root, k): # check if root is None if root is None: return q = [] # ans = [] q.append(root) lvl = 0 # tracking of level while(q): n = len(q) # when lvl becomes k we add all values of q in ans. if lvl == k: for i in range(n): print((q[i].data), end=\" \") return for i in range(1, n+1): temp = q.pop(0) if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) lvl += 1 # if after traversing ,if lvl is less than k , # that means nodes at k distance does not exist. if lvl < k: return # Driver program to test above function\"\"\" Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 8\"\"\"root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(8) printKDistant(root, 2)#this code is contributed by Vivek Maddeshiya", "e": 8995, "s": 7728, "text": null }, { "code": null, "e": 9002, "s": 8995, "text": "4 5 8 " }, { "code": null, "e": 9077, "s": 9002, "text": "Time Complexity: O(n) where n is number of nodes in the given binary tree." }, { "code": null, "e": 9194, "s": 9077, "text": "Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem." }, { "code": null, "e": 9206, "s": 9194, "text": "shrikanth13" }, { "code": null, "e": 9220, "s": 9206, "text": "rathbhupendra" }, { "code": null, "e": 9230, "s": 9220, "text": "code_rama" }, { "code": null, "e": 9242, "s": 9230, "text": "importantly" }, { "code": null, "e": 9253, "s": 9242, "text": "krishna_97" }, { "code": null, "e": 9269, "s": 9253, "text": "amartyaghoshgfg" }, { "code": null, "e": 9289, "s": 9269, "text": "vivekmaddheshiya205" }, { "code": null, "e": 9306, "s": 9289, "text": "hardikkoriintern" }, { "code": null, "e": 9313, "s": 9306, "text": "Amazon" }, { "code": null, "e": 9323, "s": 9313, "text": "Microsoft" }, { "code": null, "e": 9332, "s": 9323, "text": "Ola Cabs" }, { "code": null, "e": 9337, "s": 9332, "text": "Tree" }, { "code": null, "e": 9344, "s": 9337, "text": "Amazon" }, { "code": null, "e": 9354, "s": 9344, "text": "Microsoft" }, { "code": null, "e": 9363, "s": 9354, "text": "Ola Cabs" }, { "code": null, "e": 9368, "s": 9363, "text": "Tree" }, { "code": null, "e": 9466, "s": 9368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9498, "s": 9466, "text": "Introduction to Data Structures" }, { "code": null, "e": 9534, "s": 9498, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 9575, "s": 9534, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 9639, "s": 9575, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9682, "s": 9639, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 9715, "s": 9682, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 9741, "s": 9715, "text": "Diameter of a Binary Tree" }, { "code": null, "e": 9789, "s": 9741, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 9803, "s": 9789, "text": "Decision Tree" } ]
Difference between hover() and mouseover() methods in jQuery - GeeksforGeeks
01 Sep, 2021 Before learning the difference between the hover() and mouseover() method of jQuery, let’s briefly see both methods. hover() Method: When we hover our mouse cursor to any element, two events happen i.e. mouseenter and mouseleave. mouseenter: When we bring the cursor over the element. mouseleave: When we remove the cursor from the element. The hover()method binds handlers for both mouseenter and mouseleave events. Basically, with the hover() method, we will specify what to do when the cursor enters the element and we will specify what to do when the cursor leaves that element. Syntax: $( selector ).hover( handlerIn, handlerOut ) Parameters: It accepts two functions i.e. handlerIn and handlerOut. handlerIn: This function will be executed when the cursor enters the element. handlerOut: (Optional) This function is executed when the cursor leaves the element. When we provide only one function as an argument to the hover() method, then that function will be executed for both mouseenter as well as mouseleave events. Example: In this example, we will see how to use the hover() method. We have a word, and we will try to change the color of it whenever the cursor enters the element. The color will change back when the cursor leaves that element. HTML <!DOCTYPE html><html> <head> <!-- jQuery library --> <script src="https://code.jquery.com/jquery-git.js"> </script></head> <body> <h2>GeeksforGeeks</h2> <script> // Calling hover() method // on h1 tag $("h2").hover( // mouse-enter event function () { // changing the color $("h2").css('color', 'green') }, // mouse-leave event function () { // Putting the color back $("h2").css('color', 'black') }) </script></body> </html> Output: hover method Mouseover() Method: The mouseover() method will be executed when the mouseover event occurs. The mouseover event occurs when the cursor enters the element and then the mouseover() method for that element will be executed. We can also attach a function that will be executed when the mouseover() method is called. Syntax: $(selector).mouseover(handler) Parameter: (Optional) It accepts a function that will be executed when the mouseover() method is called. Example:In this example, we will see how to use the mouseover() method. HTML <!DOCTYPE html><html> <head> <!-- jQuery library --> <script src= "https://code.jquery.com/jquery-git.js"> </script></head> <body> <h2>GeeksforGeeks</h2> <script> $("h2").mouseover( function () { // changing the color $("h2").css('color', 'red') }) </script></body> </html> Output: Difference between hover() and mouseover() methods: hover() mouseover() Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions jQuery-Methods jQuery-Questions Picked HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? How to Insert Form Data into Database using PHP ? REST API (Introduction) Form validation using HTML and JavaScript Types of CSS (Cascading Style Sheet) JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 25369, "s": 25341, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25486, "s": 25369, "text": "Before learning the difference between the hover() and mouseover() method of jQuery, let’s briefly see both methods." }, { "code": null, "e": 25599, "s": 25486, "text": "hover() Method: When we hover our mouse cursor to any element, two events happen i.e. mouseenter and mouseleave." }, { "code": null, "e": 25654, "s": 25599, "text": "mouseenter: When we bring the cursor over the element." }, { "code": null, "e": 25710, "s": 25654, "text": "mouseleave: When we remove the cursor from the element." }, { "code": null, "e": 25953, "s": 25710, "text": "The hover()method binds handlers for both mouseenter and mouseleave events. Basically, with the hover() method, we will specify what to do when the cursor enters the element and we will specify what to do when the cursor leaves that element. " }, { "code": null, "e": 25961, "s": 25953, "text": "Syntax:" }, { "code": null, "e": 26006, "s": 25961, "text": "$( selector ).hover( handlerIn, handlerOut )" }, { "code": null, "e": 26076, "s": 26008, "text": "Parameters: It accepts two functions i.e. handlerIn and handlerOut." }, { "code": null, "e": 26154, "s": 26076, "text": "handlerIn: This function will be executed when the cursor enters the element." }, { "code": null, "e": 26239, "s": 26154, "text": "handlerOut: (Optional) This function is executed when the cursor leaves the element." }, { "code": null, "e": 26397, "s": 26239, "text": "When we provide only one function as an argument to the hover() method, then that function will be executed for both mouseenter as well as mouseleave events." }, { "code": null, "e": 26628, "s": 26397, "text": "Example: In this example, we will see how to use the hover() method. We have a word, and we will try to change the color of it whenever the cursor enters the element. The color will change back when the cursor leaves that element." }, { "code": null, "e": 26633, "s": 26628, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- jQuery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script></head> <body> <h2>GeeksforGeeks</h2> <script> // Calling hover() method // on h1 tag $(\"h2\").hover( // mouse-enter event function () { // changing the color $(\"h2\").css('color', 'green') }, // mouse-leave event function () { // Putting the color back $(\"h2\").css('color', 'black') }) </script></body> </html>", "e": 27239, "s": 26633, "text": null }, { "code": null, "e": 27247, "s": 27239, "text": "Output:" }, { "code": null, "e": 27260, "s": 27247, "text": "hover method" }, { "code": null, "e": 27573, "s": 27260, "text": "Mouseover() Method: The mouseover() method will be executed when the mouseover event occurs. The mouseover event occurs when the cursor enters the element and then the mouseover() method for that element will be executed. We can also attach a function that will be executed when the mouseover() method is called." }, { "code": null, "e": 27581, "s": 27573, "text": "Syntax:" }, { "code": null, "e": 27612, "s": 27581, "text": "$(selector).mouseover(handler)" }, { "code": null, "e": 27717, "s": 27612, "text": "Parameter: (Optional) It accepts a function that will be executed when the mouseover() method is called." }, { "code": null, "e": 27789, "s": 27717, "text": "Example:In this example, we will see how to use the mouseover() method." }, { "code": null, "e": 27794, "s": 27789, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- jQuery library --> <script src= \"https://code.jquery.com/jquery-git.js\"> </script></head> <body> <h2>GeeksforGeeks</h2> <script> $(\"h2\").mouseover( function () { // changing the color $(\"h2\").css('color', 'red') }) </script></body> </html>", "e": 28153, "s": 27794, "text": null }, { "code": null, "e": 28161, "s": 28153, "text": "Output:" }, { "code": null, "e": 28213, "s": 28161, "text": "Difference between hover() and mouseover() methods:" }, { "code": null, "e": 28221, "s": 28213, "text": "hover()" }, { "code": null, "e": 28233, "s": 28221, "text": "mouseover()" }, { "code": null, "e": 28370, "s": 28233, "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": 28385, "s": 28370, "text": "HTML-Questions" }, { "code": null, "e": 28400, "s": 28385, "text": "jQuery-Methods" }, { "code": null, "e": 28417, "s": 28400, "text": "jQuery-Questions" }, { "code": null, "e": 28424, "s": 28417, "text": "Picked" }, { "code": null, "e": 28429, "s": 28424, "text": "HTML" }, { "code": null, "e": 28436, "s": 28429, "text": "JQuery" }, { "code": null, "e": 28453, "s": 28436, "text": "Web Technologies" }, { "code": null, "e": 28458, "s": 28453, "text": "HTML" }, { "code": null, "e": 28556, "s": 28458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28565, "s": 28556, "text": "Comments" }, { "code": null, "e": 28578, "s": 28565, "text": "Old Comments" }, { "code": null, "e": 28626, "s": 28578, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28676, "s": 28626, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28700, "s": 28676, "text": "REST API (Introduction)" }, { "code": null, "e": 28742, "s": 28700, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 28779, "s": 28742, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28825, "s": 28779, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 28888, "s": 28825, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 28917, "s": 28888, "text": "Form validation using jQuery" }, { "code": null, "e": 28994, "s": 28917, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
C# | CopyTo() Method - GeeksforGeeks
31 Jan, 2019 In C#, CopyTo() method is a string method. It is used to copy a specified number of characters from a specified position in the string and it copies the characters of this string into a array of Unicode characters. Syntax: public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) Explanation: CopyTo() method will copied the count characters from the sourceIndex position to the destinationIndex position of destination character array. This method accepts four parameters as follows : sourceIndex : Index of String to be copied. And its type is System.Int32 .destination : It is the array of Unicode characters to which characters will be copied. Its type is System.Char[].destinationIndex : It is starting index of array from where the copy operation begins. Its type is System.Int32.count : It is the number of characters which will copy to destination. Its type is System.Int32. sourceIndex : Index of String to be copied. And its type is System.Int32 . destination : It is the array of Unicode characters to which characters will be copied. Its type is System.Char[]. destinationIndex : It is starting index of array from where the copy operation begins. Its type is System.Int32. count : It is the number of characters which will copy to destination. Its type is System.Int32. Examples : Input : str = "GeeksForGeeks" char [] Copystring = new char[15]; str.CopyTo(5, Copystring, 0, 3); Output: For Input : str2 = "GeeksForGeeks"; char [] Copystring = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; str2.CopyTo(8, Copystring, 6, 5); Output: Hello Geeks Below example programs illustrate the ToCopy() Method : Example 1:// C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str = "GeeksForGeeks"; char[] dest = new char[15]; // str index 5 to 5+3 has to // copy into Copystring // 3 is no. of character // 0 is start index of Copystring str.CopyTo(5, dest, 0, 3); // Displaying String Console.Write("The Copied String in dest Variable is: "); Console.WriteLine(dest); }}Output:The Copied String in dest Variable is: For // C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str = "GeeksForGeeks"; char[] dest = new char[15]; // str index 5 to 5+3 has to // copy into Copystring // 3 is no. of character // 0 is start index of Copystring str.CopyTo(5, dest, 0, 3); // Displaying String Console.Write("The Copied String in dest Variable is: "); Console.WriteLine(dest); }} The Copied String in dest Variable is: For Example 2:// C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str2 = "GeeksForGeeks"; char[] dest = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; // str index 8 to 8 + 5 has // to copy into Copystring // 5 is no of character // 6 is start index of Copystring str2.CopyTo(8, dest, 6, 5); // Displaying the result Console.Write("String Copied in dest is: "); Console.WriteLine(dest); }}Output:String Copied in dest is: Hello Geeks // C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str2 = "GeeksForGeeks"; char[] dest = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; // str index 8 to 8 + 5 has // to copy into Copystring // 5 is no of character // 6 is start index of Copystring str2.CopyTo(8, dest, 6, 5); // Displaying the result Console.Write("String Copied in dest is: "); Console.WriteLine(dest); }} String Copied in dest is: Hello Geeks Note: If “destination” is null then it will cause an Exception as ArgumentNullException. There are different cases when exception occurs: ArgumentOutOfRangeException cases 1: if sourceIndex, destinationIndex, or count is negative.cases 2: if sourceIndex does not identify a position in the current instance.cases 3: if destinationIndex does not identify a valid index in the destination array.cases 4: if the count is greater than the length of the substring from startIndex to the end of this instancecases 5: if the count is greater than the length of the subarray from destinationIndex to the end of the destination array. Reference: https://msdn.microsoft.com/en-us/library/system.string.copyto CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates Destructors in C# Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Abstract Classes C# | Data Types HashSet in C# with Examples Common Language Runtime (CLR) in C# Top 50 C# Interview Questions & Answers
[ { "code": null, "e": 24257, "s": 24229, "text": "\n31 Jan, 2019" }, { "code": null, "e": 24472, "s": 24257, "text": "In C#, CopyTo() method is a string method. It is used to copy a specified number of characters from a specified position in the string and it copies the characters of this string into a array of Unicode characters." }, { "code": null, "e": 24480, "s": 24472, "text": "Syntax:" }, { "code": null, "e": 24593, "s": 24480, "text": "public void CopyTo(int sourceIndex, char[] destination, \n int destinationIndex, int count)\n" }, { "code": null, "e": 24799, "s": 24593, "text": "Explanation: CopyTo() method will copied the count characters from the sourceIndex position to the destinationIndex position of destination character array. This method accepts four parameters as follows :" }, { "code": null, "e": 25196, "s": 24799, "text": "sourceIndex : Index of String to be copied. And its type is System.Int32 .destination : It is the array of Unicode characters to which characters will be copied. Its type is System.Char[].destinationIndex : It is starting index of array from where the copy operation begins. Its type is System.Int32.count : It is the number of characters which will copy to destination. Its type is System.Int32." }, { "code": null, "e": 25271, "s": 25196, "text": "sourceIndex : Index of String to be copied. And its type is System.Int32 ." }, { "code": null, "e": 25386, "s": 25271, "text": "destination : It is the array of Unicode characters to which characters will be copied. Its type is System.Char[]." }, { "code": null, "e": 25499, "s": 25386, "text": "destinationIndex : It is starting index of array from where the copy operation begins. Its type is System.Int32." }, { "code": null, "e": 25596, "s": 25499, "text": "count : It is the number of characters which will copy to destination. Its type is System.Int32." }, { "code": null, "e": 25607, "s": 25596, "text": "Examples :" }, { "code": null, "e": 25921, "s": 25607, "text": "Input : str = \"GeeksForGeeks\"\n char [] Copystring = new char[15]; \n str.CopyTo(5, Copystring, 0, 3);\nOutput: For\n\nInput : str2 = \"GeeksForGeeks\";\n char [] Copystring = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};\n str2.CopyTo(8, Copystring, 6, 5);\nOutput: Hello Geeks\n" }, { "code": null, "e": 25977, "s": 25921, "text": "Below example programs illustrate the ToCopy() Method :" }, { "code": null, "e": 26570, "s": 25977, "text": "Example 1:// C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str = \"GeeksForGeeks\"; char[] dest = new char[15]; // str index 5 to 5+3 has to // copy into Copystring // 3 is no. of character // 0 is start index of Copystring str.CopyTo(5, dest, 0, 3); // Displaying String Console.Write(\"The Copied String in dest Variable is: \"); Console.WriteLine(dest); }}Output:The Copied String in dest Variable is: For\n" }, { "code": "// C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str = \"GeeksForGeeks\"; char[] dest = new char[15]; // str index 5 to 5+3 has to // copy into Copystring // 3 is no. of character // 0 is start index of Copystring str.CopyTo(5, dest, 0, 3); // Displaying String Console.Write(\"The Copied String in dest Variable is: \"); Console.WriteLine(dest); }}", "e": 27103, "s": 26570, "text": null }, { "code": null, "e": 27147, "s": 27103, "text": "The Copied String in dest Variable is: For\n" }, { "code": null, "e": 27801, "s": 27147, "text": "Example 2:// C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str2 = \"GeeksForGeeks\"; char[] dest = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; // str index 8 to 8 + 5 has // to copy into Copystring // 5 is no of character // 6 is start index of Copystring str2.CopyTo(8, dest, 6, 5); // Displaying the result Console.Write(\"String Copied in dest is: \"); Console.WriteLine(dest); }}Output:String Copied in dest is: Hello Geeks\n" }, { "code": "// C# program to illustrate the// ToCopy() string methodusing System; class Geeks { // Main Method public static void Main() { string str2 = \"GeeksForGeeks\"; char[] dest = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; // str index 8 to 8 + 5 has // to copy into Copystring // 5 is no of character // 6 is start index of Copystring str2.CopyTo(8, dest, 6, 5); // Displaying the result Console.Write(\"String Copied in dest is: \"); Console.WriteLine(dest); }}", "e": 28400, "s": 27801, "text": null }, { "code": null, "e": 28439, "s": 28400, "text": "String Copied in dest is: Hello Geeks\n" }, { "code": null, "e": 28605, "s": 28439, "text": "Note: If “destination” is null then it will cause an Exception as ArgumentNullException. There are different cases when exception occurs: ArgumentOutOfRangeException" }, { "code": null, "e": 29065, "s": 28605, "text": "cases 1: if sourceIndex, destinationIndex, or count is negative.cases 2: if sourceIndex does not identify a position in the current instance.cases 3: if destinationIndex does not identify a valid index in the destination array.cases 4: if the count is greater than the length of the substring from startIndex to the end of this instancecases 5: if the count is greater than the length of the subarray from destinationIndex to the end of the destination array." }, { "code": null, "e": 29138, "s": 29065, "text": "Reference: https://msdn.microsoft.com/en-us/library/system.string.copyto" }, { "code": null, "e": 29152, "s": 29138, "text": "CSharp-method" }, { "code": null, "e": 29166, "s": 29152, "text": "CSharp-string" }, { "code": null, "e": 29169, "s": 29166, "text": "C#" }, { "code": null, "e": 29267, "s": 29169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29282, "s": 29267, "text": "C# | Delegates" }, { "code": null, "e": 29300, "s": 29282, "text": "Destructors in C#" }, { "code": null, "e": 29323, "s": 29300, "text": "Extension Method in C#" }, { "code": null, "e": 29363, "s": 29323, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29394, "s": 29363, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29416, "s": 29394, "text": "C# | Abstract Classes" }, { "code": null, "e": 29432, "s": 29416, "text": "C# | Data Types" }, { "code": null, "e": 29460, "s": 29432, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29496, "s": 29460, "text": "Common Language Runtime (CLR) in C#" } ]
Essential Programming | Control Structures | by Diego Lopez Yse | Towards Data Science
If you want to start programming, I must admit that the outlook is not good: different operating systems, so many programming languages, and endless ways of reaching the same results. These are the type of situations that will make you either run away (as fast and as far as you can, hoping you’ll never bump into programming again), or face the beast. If you decide to face it, then you won’t know where to start from, or how to handle it. You’ll only have questions and probably not even one answer, but you know what? This is a great way to start. Actually this is how I started programming. I believed that if I ever wanted to understand programs I had to answer the question of: How do programs work, and how can you build them? Certainly not a simple issue, but come on, harder questions have been answered, right? Take a look at Marvin Minsky. Minsky, who is considered one of the fathers of AI, wrote “The Society of Mind” to answer one of the most difficult questions of our time: what is the human mind, and how does it work? With a revolutionary perspective, Minsky suggested that our minds consist of the aggregation of small-minds (or more basic components) that have evolved to perform highly specific tasks. According to him, most of these tiny-minds lack the attributes we think of as intelligence and are severely limited, and can only reach feelings, thoughts or purposeful action through the interaction with other components. This idea contains a powerful concept: complex matters can be thought as groups of simpler subjects, that can also be partitioned into more basic things, until you reach a proper understanding. If you think about it this way, any efficient system can be explained as a set of simpler functions that when put together perform in a way that reach superior results in comparison to their individual performances. For this reason, if I wanted to understand computer programs (and learn how to make them) I needed to understand their building blocks. You see, when a program runs, the code is read by the computer line by line (from top to bottom, and from left to right), just like you would read a book. At some point, the program may reach a situation where it needs to make a decision such as jump to a different part of the program or re-run a certain piece again. These decisions that affect the flow of the program’s code are known as a Control Structures. Control Structures can be considered as the building blocks of computer programs. They are commands that enable a program to “take decisions”, following one path or another. A program is usually not limited to a linear sequence of instructions since during its process it may bifurcate, repeat code or bypass sections. Control Structures are the blocks that analyze variables and choose directions in which to go based on given parameters. The basic Control Structures in programming languages are: Conditionals (or Selection): which are used to execute one or more statements if a condition is met. Loops (or Iteration): which purpose is to repeat a statement a certain number of times or while a condition is fulfilled. Now let’s take a look at each one of these concepts. Down below we will deep dive using R programming language (one of the mostly used languages for data science), but the same ideas and explanations apply to any other programming language. “Conditionals” are at the very core of programming. The idea behind them is that they allow you to control the flow of the code that is executed based on different conditions in the program (e.g. an input taken from the user, or the internal state of the machine the program is running on). In this article we will explore the Conditionals Control Structures of “If statements” and “If-Else statements”. “If statements” execute one or more statements when a condition is met. If the testing of that condition is TRUE, the statement gets executed. But if it’s FALSE (the condition is not met), then nothing happens. Let ́s visualize it: The syntax of “If statements” is: Example To show a simple case, let’s say you want to verify if the value of a variable (x) is positive: In this example, first we assign the value of 4 to the variable (x) and use the “If statement” to verify if that value is equal or greater than 0. If the test results TRUE (as in this case), the function will print the sentence: “variable x is a positive number”. Output [1] "variable x is a positive number" But since the “If statement” only executes a statement if the tested condition is TRUE, what would had happened if the variable value was negative? To execute a statement on a tested condition with a FALSE result, we need to use “If-Else statement”. This Control Structure allows a program to follow alternative paths of execution, whether a condition is met or not. The syntax of “If-Else statements” is: The “else part” of the instruction is optional and only evaluated if the condition tests FALSE. Example 1 Following our example, we extend the previous conditional “If statement” by adding the “else part” to test if a the value of a variable is positive or negative and perform an action whether the test result is TRUE or FALSE. In this example, we assign the value of -4 to the variable (x) and use the “If statement” to verify if that value is equal or greater than 0. If the test results TRUE, the function will print the sentence: “variable x is a positive number”. But in case the test results FALSE (as in this case), the function continues to the alternative expression and prints the sentence: “variable x is a negative number”. Output [1] "variable x is a negative number" Example 2 Let’s say you need to define more than 2 conditions, as in the event of grading an exam. In that case you can grade A, B, C, D or F (5 options), so, how would you do it? “If-Else statements” can have multiple alternative statements. In the below example we define an initial score, and an “If-Else statement” of 5 rating categories. This piece of code will go through each condition until reaching a TRUE test result. Output [1] “C” “Loop statements” are nothing more than the automation of multi-step processes by organizing sequences of actions, and grouping the parts that need to be repeated. Also a central part of programming, iteration (or Looping) gives computers much of their power. They can repeat a sequence of steps as often as necessary, and appropriate repetitions of simple steps can solve complex problems. In general terms, there are two types of “Looping techniques”: “For Loops”: are the ones that execute for a prescribed number of times, as controlled by a counter or an index.“While Loops” and “Repeat Loops”: are based on the onset and verification of a logical condition. The condition is tested at the start or the end of the loop construct. “For Loops”: are the ones that execute for a prescribed number of times, as controlled by a counter or an index. “While Loops” and “Repeat Loops”: are based on the onset and verification of a logical condition. The condition is tested at the start or the end of the loop construct. Let’s take a look at them: In this Control Structure, statements are executed one after another in a consecutive order over a sequence of values that gets evaluated only when the “For Loop” is initiated (never re-evaluated). In this case, the number of iterations is fixed and known in advance. If the evaluation of the condition on a variable (which can assume values within a specified sequence) results TRUE, one or more statements will be executed sequentially over that string of values. Once the first condition test is done (and results TRUE), the statement is executed and the condition is evaluated again, going through an iterative process. The “variable in sequence” section performs this test on each value of the sequence until it covers the last element. If the condition is not met and the resulting outcome is FALSE (e.g. the “variable in sequence” part has finished going through all the elements of the sequence), the loop ends. If the condition test results FALSE in the first iteration, the “For Loop” is never executed. The syntax of “For Loops” is: Example 1 To show how “For Loops” work, first we will create a sequence by concatenating different names of fruits to create a list (called “fruit_list”): We will use this fruit list as the “sequence” in a“For Loop”, and make the “For Loop” run a statement once (print the name of each value) for each provided value in the sequence (the different fruits in the fruit list): This way, the outcome of the “For Loop” is as follows: ## [1] "Apple"## [1] "Kiwi"## [1] "Orange"## [1] "Banana" OK, so we printed the name of each value in the list. Not a big deal, right? The good thing is that “For Loops” can be used to produce more interesting results. Take a look at the following example. Example 2 What if we want to modify values, or perform calculations sequentially? You can use “For Loops” to perform mathematical operations sequentially over each value of a vector (elements of the same type, which in this case will be numerical). In this example, we will create a sequence of numbers (from 1 to 10), and set a “For Loop” to calculate and print the square root of each value in that sequence: In this case, the outcome of the “For Loop” is: [1] 1[1] 1.414214[1] 1.732051[1] 2[1] 2.236068[1] 2.449490[1] 2.645751[1] 2.828427[1] 3[1] 3.162278 You can use any type of mathematical operator over a numerical sequence, and as we will see later in this article, make all sorts of combinations between different Control Structures to reach more complex results. In “While Loops” a condition is first evaluated, and if the result of testing that condition is TRUE, one or more statements are repeatedly executed until that condition becomes FALSE. Unlike “If statements”, in which a condition tested as TRUE executes an expression only once and ends, “While Loops” are iterative statements that execute some expression over and over again until the condition becomes FALSE. If the condition never turns out to be FALSE, the “While Loop” will go on forever and the program will crash. The other way around, if the condition test results FALSE in the beginning of the loop, the expression will never get executed. The syntax of “While Loops” is: Example 1 Let’s see an example. First we will create a variable (x) and assign it the value of 1. Then we set a “While Loop” to iteratively test a condition over that variable until the condition test results FALSE: This is how it works: the initial value of the variable (x) is 1, so when we test the condition “is the variable (x) less than 10?”, the result evaluates to TRUE and the expression is executed, printing the result of the variable (x), which in the first case is 1. But then something happens: the variable (x) is incremented by 1 before the function ends, and in the next iteration the value of x will be 2. This variable reassignment is important because it will eventually reach the FALSE condition and the loop exit (value of x = 10). Failing to change the initial conditions in a “While Loop” will result into an infinite loop and a program crash. Output [1] 1[1] 2[1] 3[1] 4[1] 5[1] 6[1] 7[1] 8[1] 9 Example 2 Have you heard of the Fibonacci sequence? This is a series of numbers with the characteristic that the next number in the sequence is found by adding up the two numbers before it: 0, 1, 1, 2, 3, 5, 8, 13, 21,... This sequence can be found in several nature phenomena, and has different applications in finance, music, architecture, and other disciplines. Let’s calculate it using a “While Loop”. In this case we set a maximum value in the series as the stop condition, so that the loop prints the Fibonacci series only for numbers below 100. When a series element (which ever it is) becomes bigger than 100, the loop cycle ends. [1] 0[1] 1[1] 1[1] 2[1] 3[1] 5[1] 8[1] 13[1] 21[1] 34[1] 55[1] 89 Example 3 Another way of generating the Fibonacci series with a “While Loop” is, instead of setting the maximum value of the series as a stop condition, setting the number of series elements you want to generate. This “While Loop” appends the next element of the series to the end of the previous element, until reaching a stop condition. In this case, when the series reaches 10 elements (no matter which values), the loop cylce ends. Output [1] 0 1 1 2 3 5 8 13 21 34 Closely linked to “While Loops”, “Repeat Loops” execute statements iteratively, but until a stop condition is met. This way, statements are executed at least once, no matter what the result of the condition is, and the loop is exited only when certain condition becomes TRUE: The syntax of “Repeat Loops” is: “Repeat Loops” use “Break statements” as a stop condition. “Break statements” are combined with the test of a condition to interrupt cycles within loops, since when the program hits a break, it will pass control to the instruction immediately after the end of the loop (if any). “Repeat Loops” will run forever if the break condition is not met. See these 2 examples Example 1 First we create a variable (x) and assign it the value of 5. Then we set a “Repeat Loop” to iteratively print the value of the variable, modify the value of the variable (increase it by 1), and test a condition over that variable (if it equals 10) until the condition test results TRUE. The “breaking condition” triggers when the variable (x) reaches 10, and the loop ends. Output [1] 5[1] 6[1] 7[1] 8[1] 9 Example 2 Now let’s suppose we produce a list of random numbers, for which we don’t know the order or sequence of generation. In this example we will use a “Repeat Loop” to generate a sequence of normally distributed random numbers (you can generate random with any other distribution, we just pick this one), and break the sequence once one of those numbers is bigger than 1. Since we don’t know which numbers will come first, we don’t know how long the sequence will be: we just know the breaking condition. First, we use the “set.seed” instruction to fix the random numbers (generate always the same random numbers), and make this example reproduceable. Then we initiate the “Repeat Loop” by generating a normally distributed random number, printing it, and checking if that number is bigger than 1. Only when this condition becomes TRUE (could be with the first generated number, or not), the loop cycle will pass to the break statement and end. Output [1] -0.9619334[1] -0.2925257[1] 0.2587882[1] -1.152132[1] 0.1957828[1] 0.03012394[1] 0.08541773[1] 1.11661 This shows once again the importance of setting a proper breaking condition. Failing to do so will result in an infinite loop. We’ve seen and explained concepts in isolation, but “Control Structures” can be combined anyway you want: Loops may contain several internal Loops; Conditionals may contain Loops and Conditionals, the options are endless. (in fact, when reviewing “Repeat Loops” we found that the examples contained nested “If statements”). You can develop advanced solutions just by combining the “Control Structures” we explained in this article. Like Minsky stated, we can reach complex outcomes as a result of the interaction of simpler components. Control Structures constitute the basic blocks for decision making processes in computing. They change the flow of programs and enable us to construct complex sets of instructions out of simpler building blocks. My advice is: learn about them. It will ease your path to coding and understanding of programs, and will help you to find new ways of solving problems. Interested in these topics? Follow me on Linkedin or Twitter
[ { "code": null, "e": 856, "s": 172, "text": "If you want to start programming, I must admit that the outlook is not good: different operating systems, so many programming languages, and endless ways of reaching the same results. These are the type of situations that will make you either run away (as fast and as far as you can, hoping you’ll never bump into programming again), or face the beast. If you decide to face it, then you won’t know where to start from, or how to handle it. You’ll only have questions and probably not even one answer, but you know what? This is a great way to start. Actually this is how I started programming. I believed that if I ever wanted to understand programs I had to answer the question of:" }, { "code": null, "e": 906, "s": 856, "text": "How do programs work, and how can you build them?" }, { "code": null, "e": 1618, "s": 906, "text": "Certainly not a simple issue, but come on, harder questions have been answered, right? Take a look at Marvin Minsky. Minsky, who is considered one of the fathers of AI, wrote “The Society of Mind” to answer one of the most difficult questions of our time: what is the human mind, and how does it work? With a revolutionary perspective, Minsky suggested that our minds consist of the aggregation of small-minds (or more basic components) that have evolved to perform highly specific tasks. According to him, most of these tiny-minds lack the attributes we think of as intelligence and are severely limited, and can only reach feelings, thoughts or purposeful action through the interaction with other components." }, { "code": null, "e": 2028, "s": 1618, "text": "This idea contains a powerful concept: complex matters can be thought as groups of simpler subjects, that can also be partitioned into more basic things, until you reach a proper understanding. If you think about it this way, any efficient system can be explained as a set of simpler functions that when put together perform in a way that reach superior results in comparison to their individual performances." }, { "code": null, "e": 2577, "s": 2028, "text": "For this reason, if I wanted to understand computer programs (and learn how to make them) I needed to understand their building blocks. You see, when a program runs, the code is read by the computer line by line (from top to bottom, and from left to right), just like you would read a book. At some point, the program may reach a situation where it needs to make a decision such as jump to a different part of the program or re-run a certain piece again. These decisions that affect the flow of the program’s code are known as a Control Structures." }, { "code": null, "e": 3017, "s": 2577, "text": "Control Structures can be considered as the building blocks of computer programs. They are commands that enable a program to “take decisions”, following one path or another. A program is usually not limited to a linear sequence of instructions since during its process it may bifurcate, repeat code or bypass sections. Control Structures are the blocks that analyze variables and choose directions in which to go based on given parameters." }, { "code": null, "e": 3076, "s": 3017, "text": "The basic Control Structures in programming languages are:" }, { "code": null, "e": 3177, "s": 3076, "text": "Conditionals (or Selection): which are used to execute one or more statements if a condition is met." }, { "code": null, "e": 3299, "s": 3177, "text": "Loops (or Iteration): which purpose is to repeat a statement a certain number of times or while a condition is fulfilled." }, { "code": null, "e": 3540, "s": 3299, "text": "Now let’s take a look at each one of these concepts. Down below we will deep dive using R programming language (one of the mostly used languages for data science), but the same ideas and explanations apply to any other programming language." }, { "code": null, "e": 3944, "s": 3540, "text": "“Conditionals” are at the very core of programming. The idea behind them is that they allow you to control the flow of the code that is executed based on different conditions in the program (e.g. an input taken from the user, or the internal state of the machine the program is running on). In this article we will explore the Conditionals Control Structures of “If statements” and “If-Else statements”." }, { "code": null, "e": 4176, "s": 3944, "text": "“If statements” execute one or more statements when a condition is met. If the testing of that condition is TRUE, the statement gets executed. But if it’s FALSE (the condition is not met), then nothing happens. Let ́s visualize it:" }, { "code": null, "e": 4210, "s": 4176, "text": "The syntax of “If statements” is:" }, { "code": null, "e": 4218, "s": 4210, "text": "Example" }, { "code": null, "e": 4314, "s": 4218, "text": "To show a simple case, let’s say you want to verify if the value of a variable (x) is positive:" }, { "code": null, "e": 4578, "s": 4314, "text": "In this example, first we assign the value of 4 to the variable (x) and use the “If statement” to verify if that value is equal or greater than 0. If the test results TRUE (as in this case), the function will print the sentence: “variable x is a positive number”." }, { "code": null, "e": 4585, "s": 4578, "text": "Output" }, { "code": null, "e": 4623, "s": 4585, "text": "[1] \"variable x is a positive number\"" }, { "code": null, "e": 4873, "s": 4623, "text": "But since the “If statement” only executes a statement if the tested condition is TRUE, what would had happened if the variable value was negative? To execute a statement on a tested condition with a FALSE result, we need to use “If-Else statement”." }, { "code": null, "e": 4990, "s": 4873, "text": "This Control Structure allows a program to follow alternative paths of execution, whether a condition is met or not." }, { "code": null, "e": 5029, "s": 4990, "text": "The syntax of “If-Else statements” is:" }, { "code": null, "e": 5125, "s": 5029, "text": "The “else part” of the instruction is optional and only evaluated if the condition tests FALSE." }, { "code": null, "e": 5135, "s": 5125, "text": "Example 1" }, { "code": null, "e": 5359, "s": 5135, "text": "Following our example, we extend the previous conditional “If statement” by adding the “else part” to test if a the value of a variable is positive or negative and perform an action whether the test result is TRUE or FALSE." }, { "code": null, "e": 5767, "s": 5359, "text": "In this example, we assign the value of -4 to the variable (x) and use the “If statement” to verify if that value is equal or greater than 0. If the test results TRUE, the function will print the sentence: “variable x is a positive number”. But in case the test results FALSE (as in this case), the function continues to the alternative expression and prints the sentence: “variable x is a negative number”." }, { "code": null, "e": 5774, "s": 5767, "text": "Output" }, { "code": null, "e": 5812, "s": 5774, "text": "[1] \"variable x is a negative number\"" }, { "code": null, "e": 5822, "s": 5812, "text": "Example 2" }, { "code": null, "e": 5992, "s": 5822, "text": "Let’s say you need to define more than 2 conditions, as in the event of grading an exam. In that case you can grade A, B, C, D or F (5 options), so, how would you do it?" }, { "code": null, "e": 6240, "s": 5992, "text": "“If-Else statements” can have multiple alternative statements. In the below example we define an initial score, and an “If-Else statement” of 5 rating categories. This piece of code will go through each condition until reaching a TRUE test result." }, { "code": null, "e": 6247, "s": 6240, "text": "Output" }, { "code": null, "e": 6255, "s": 6247, "text": "[1] “C”" }, { "code": null, "e": 6646, "s": 6255, "text": "“Loop statements” are nothing more than the automation of multi-step processes by organizing sequences of actions, and grouping the parts that need to be repeated. Also a central part of programming, iteration (or Looping) gives computers much of their power. They can repeat a sequence of steps as often as necessary, and appropriate repetitions of simple steps can solve complex problems." }, { "code": null, "e": 6709, "s": 6646, "text": "In general terms, there are two types of “Looping techniques”:" }, { "code": null, "e": 6990, "s": 6709, "text": "“For Loops”: are the ones that execute for a prescribed number of times, as controlled by a counter or an index.“While Loops” and “Repeat Loops”: are based on the onset and verification of a logical condition. The condition is tested at the start or the end of the loop construct." }, { "code": null, "e": 7103, "s": 6990, "text": "“For Loops”: are the ones that execute for a prescribed number of times, as controlled by a counter or an index." }, { "code": null, "e": 7272, "s": 7103, "text": "“While Loops” and “Repeat Loops”: are based on the onset and verification of a logical condition. The condition is tested at the start or the end of the loop construct." }, { "code": null, "e": 7299, "s": 7272, "text": "Let’s take a look at them:" }, { "code": null, "e": 7567, "s": 7299, "text": "In this Control Structure, statements are executed one after another in a consecutive order over a sequence of values that gets evaluated only when the “For Loop” is initiated (never re-evaluated). In this case, the number of iterations is fixed and known in advance." }, { "code": null, "e": 8041, "s": 7567, "text": "If the evaluation of the condition on a variable (which can assume values within a specified sequence) results TRUE, one or more statements will be executed sequentially over that string of values. Once the first condition test is done (and results TRUE), the statement is executed and the condition is evaluated again, going through an iterative process. The “variable in sequence” section performs this test on each value of the sequence until it covers the last element." }, { "code": null, "e": 8313, "s": 8041, "text": "If the condition is not met and the resulting outcome is FALSE (e.g. the “variable in sequence” part has finished going through all the elements of the sequence), the loop ends. If the condition test results FALSE in the first iteration, the “For Loop” is never executed." }, { "code": null, "e": 8343, "s": 8313, "text": "The syntax of “For Loops” is:" }, { "code": null, "e": 8353, "s": 8343, "text": "Example 1" }, { "code": null, "e": 8498, "s": 8353, "text": "To show how “For Loops” work, first we will create a sequence by concatenating different names of fruits to create a list (called “fruit_list”):" }, { "code": null, "e": 8718, "s": 8498, "text": "We will use this fruit list as the “sequence” in a“For Loop”, and make the “For Loop” run a statement once (print the name of each value) for each provided value in the sequence (the different fruits in the fruit list):" }, { "code": null, "e": 8773, "s": 8718, "text": "This way, the outcome of the “For Loop” is as follows:" }, { "code": null, "e": 8831, "s": 8773, "text": "## [1] \"Apple\"## [1] \"Kiwi\"## [1] \"Orange\"## [1] \"Banana\"" }, { "code": null, "e": 9030, "s": 8831, "text": "OK, so we printed the name of each value in the list. Not a big deal, right? The good thing is that “For Loops” can be used to produce more interesting results. Take a look at the following example." }, { "code": null, "e": 9040, "s": 9030, "text": "Example 2" }, { "code": null, "e": 9279, "s": 9040, "text": "What if we want to modify values, or perform calculations sequentially? You can use “For Loops” to perform mathematical operations sequentially over each value of a vector (elements of the same type, which in this case will be numerical)." }, { "code": null, "e": 9441, "s": 9279, "text": "In this example, we will create a sequence of numbers (from 1 to 10), and set a “For Loop” to calculate and print the square root of each value in that sequence:" }, { "code": null, "e": 9489, "s": 9441, "text": "In this case, the outcome of the “For Loop” is:" }, { "code": null, "e": 9589, "s": 9489, "text": "[1] 1[1] 1.414214[1] 1.732051[1] 2[1] 2.236068[1] 2.449490[1] 2.645751[1] 2.828427[1] 3[1] 3.162278" }, { "code": null, "e": 9803, "s": 9589, "text": "You can use any type of mathematical operator over a numerical sequence, and as we will see later in this article, make all sorts of combinations between different Control Structures to reach more complex results." }, { "code": null, "e": 9988, "s": 9803, "text": "In “While Loops” a condition is first evaluated, and if the result of testing that condition is TRUE, one or more statements are repeatedly executed until that condition becomes FALSE." }, { "code": null, "e": 10452, "s": 9988, "text": "Unlike “If statements”, in which a condition tested as TRUE executes an expression only once and ends, “While Loops” are iterative statements that execute some expression over and over again until the condition becomes FALSE. If the condition never turns out to be FALSE, the “While Loop” will go on forever and the program will crash. The other way around, if the condition test results FALSE in the beginning of the loop, the expression will never get executed." }, { "code": null, "e": 10484, "s": 10452, "text": "The syntax of “While Loops” is:" }, { "code": null, "e": 10494, "s": 10484, "text": "Example 1" }, { "code": null, "e": 10700, "s": 10494, "text": "Let’s see an example. First we will create a variable (x) and assign it the value of 1. Then we set a “While Loop” to iteratively test a condition over that variable until the condition test results FALSE:" }, { "code": null, "e": 11108, "s": 10700, "text": "This is how it works: the initial value of the variable (x) is 1, so when we test the condition “is the variable (x) less than 10?”, the result evaluates to TRUE and the expression is executed, printing the result of the variable (x), which in the first case is 1. But then something happens: the variable (x) is incremented by 1 before the function ends, and in the next iteration the value of x will be 2." }, { "code": null, "e": 11352, "s": 11108, "text": "This variable reassignment is important because it will eventually reach the FALSE condition and the loop exit (value of x = 10). Failing to change the initial conditions in a “While Loop” will result into an infinite loop and a program crash." }, { "code": null, "e": 11359, "s": 11352, "text": "Output" }, { "code": null, "e": 11405, "s": 11359, "text": "[1] 1[1] 2[1] 3[1] 4[1] 5[1] 6[1] 7[1] 8[1] 9" }, { "code": null, "e": 11415, "s": 11405, "text": "Example 2" }, { "code": null, "e": 11770, "s": 11415, "text": "Have you heard of the Fibonacci sequence? This is a series of numbers with the characteristic that the next number in the sequence is found by adding up the two numbers before it: 0, 1, 1, 2, 3, 5, 8, 13, 21,... This sequence can be found in several nature phenomena, and has different applications in finance, music, architecture, and other disciplines." }, { "code": null, "e": 11811, "s": 11770, "text": "Let’s calculate it using a “While Loop”." }, { "code": null, "e": 12044, "s": 11811, "text": "In this case we set a maximum value in the series as the stop condition, so that the loop prints the Fibonacci series only for numbers below 100. When a series element (which ever it is) becomes bigger than 100, the loop cycle ends." }, { "code": null, "e": 12110, "s": 12044, "text": "[1] 0[1] 1[1] 1[1] 2[1] 3[1] 5[1] 8[1] 13[1] 21[1] 34[1] 55[1] 89" }, { "code": null, "e": 12120, "s": 12110, "text": "Example 3" }, { "code": null, "e": 12323, "s": 12120, "text": "Another way of generating the Fibonacci series with a “While Loop” is, instead of setting the maximum value of the series as a stop condition, setting the number of series elements you want to generate." }, { "code": null, "e": 12546, "s": 12323, "text": "This “While Loop” appends the next element of the series to the end of the previous element, until reaching a stop condition. In this case, when the series reaches 10 elements (no matter which values), the loop cylce ends." }, { "code": null, "e": 12553, "s": 12546, "text": "Output" }, { "code": null, "e": 12580, "s": 12553, "text": "[1] 0 1 1 2 3 5 8 13 21 34" }, { "code": null, "e": 12856, "s": 12580, "text": "Closely linked to “While Loops”, “Repeat Loops” execute statements iteratively, but until a stop condition is met. This way, statements are executed at least once, no matter what the result of the condition is, and the loop is exited only when certain condition becomes TRUE:" }, { "code": null, "e": 12889, "s": 12856, "text": "The syntax of “Repeat Loops” is:" }, { "code": null, "e": 13168, "s": 12889, "text": "“Repeat Loops” use “Break statements” as a stop condition. “Break statements” are combined with the test of a condition to interrupt cycles within loops, since when the program hits a break, it will pass control to the instruction immediately after the end of the loop (if any)." }, { "code": null, "e": 13256, "s": 13168, "text": "“Repeat Loops” will run forever if the break condition is not met. See these 2 examples" }, { "code": null, "e": 13266, "s": 13256, "text": "Example 1" }, { "code": null, "e": 13553, "s": 13266, "text": "First we create a variable (x) and assign it the value of 5. Then we set a “Repeat Loop” to iteratively print the value of the variable, modify the value of the variable (increase it by 1), and test a condition over that variable (if it equals 10) until the condition test results TRUE." }, { "code": null, "e": 13640, "s": 13553, "text": "The “breaking condition” triggers when the variable (x) reaches 10, and the loop ends." }, { "code": null, "e": 13647, "s": 13640, "text": "Output" }, { "code": null, "e": 13673, "s": 13647, "text": "[1] 5[1] 6[1] 7[1] 8[1] 9" }, { "code": null, "e": 13683, "s": 13673, "text": "Example 2" }, { "code": null, "e": 13799, "s": 13683, "text": "Now let’s suppose we produce a list of random numbers, for which we don’t know the order or sequence of generation." }, { "code": null, "e": 14183, "s": 13799, "text": "In this example we will use a “Repeat Loop” to generate a sequence of normally distributed random numbers (you can generate random with any other distribution, we just pick this one), and break the sequence once one of those numbers is bigger than 1. Since we don’t know which numbers will come first, we don’t know how long the sequence will be: we just know the breaking condition." }, { "code": null, "e": 14330, "s": 14183, "text": "First, we use the “set.seed” instruction to fix the random numbers (generate always the same random numbers), and make this example reproduceable." }, { "code": null, "e": 14623, "s": 14330, "text": "Then we initiate the “Repeat Loop” by generating a normally distributed random number, printing it, and checking if that number is bigger than 1. Only when this condition becomes TRUE (could be with the first generated number, or not), the loop cycle will pass to the break statement and end." }, { "code": null, "e": 14630, "s": 14623, "text": "Output" }, { "code": null, "e": 14737, "s": 14630, "text": "[1] -0.9619334[1] -0.2925257[1] 0.2587882[1] -1.152132[1] 0.1957828[1] 0.03012394[1] 0.08541773[1] 1.11661" }, { "code": null, "e": 14864, "s": 14737, "text": "This shows once again the importance of setting a proper breaking condition. Failing to do so will result in an infinite loop." }, { "code": null, "e": 15188, "s": 14864, "text": "We’ve seen and explained concepts in isolation, but “Control Structures” can be combined anyway you want: Loops may contain several internal Loops; Conditionals may contain Loops and Conditionals, the options are endless. (in fact, when reviewing “Repeat Loops” we found that the examples contained nested “If statements”)." }, { "code": null, "e": 15612, "s": 15188, "text": "You can develop advanced solutions just by combining the “Control Structures” we explained in this article. Like Minsky stated, we can reach complex outcomes as a result of the interaction of simpler components. Control Structures constitute the basic blocks for decision making processes in computing. They change the flow of programs and enable us to construct complex sets of instructions out of simpler building blocks." }, { "code": null, "e": 15644, "s": 15612, "text": "My advice is: learn about them." }, { "code": null, "e": 15764, "s": 15644, "text": "It will ease your path to coding and understanding of programs, and will help you to find new ways of solving problems." } ]
Multicollinearity in Regression. Why it is a problem? How to track and... | by Songhao Wu | Towards Data Science
Multicollinearity happens when independent variables in the regression model are highly correlated to each other. It makes it hard to interpret of model and also creates an overfitting problem. It is a common assumption that people test before selecting the variables into the regression model. I encountered a serious multicollinearity issue before when I built the regression model for time series data. I created multiple features based on different time periods like 1-month total return, 6-month total return, and 1-year total return to have more input variables. However, these features are highly correlated with each other. For example, if one stock has performed well for the past year, then it is very likely to have done well for the recent month. I would need to either drop some of these variables or find a way to make them less correlated. I will explain later in the article different ways to solve the problem. When independent variables are highly correlated, change in one variable would cause change to another and so the model results fluctuate significantly. The model results will be unstable and vary a lot given a small change in the data or model. This will create the following problems: It would be hard for you to choose the list of significant variables for the model if the model gives you different results every time.Coefficient Estimates would not be stable and it would be hard for you to interpret the model. In other words, you cannot tell the scale of changes to the output if one of your predicting factors changes by 1 unit.The unstable nature of the model may cause overfitting. If you apply the model to another sample of data, the accuracy will drop significantly compared to the accuracy of your training dataset. It would be hard for you to choose the list of significant variables for the model if the model gives you different results every time. Coefficient Estimates would not be stable and it would be hard for you to interpret the model. In other words, you cannot tell the scale of changes to the output if one of your predicting factors changes by 1 unit. The unstable nature of the model may cause overfitting. If you apply the model to another sample of data, the accuracy will drop significantly compared to the accuracy of your training dataset. Depending on the situation, it may not be a problem for your model if only slight or moderate collinearity issue occurs. However, it is strongly advised to solve the issue if severe collinearity issue exists(e.g. correlation >0.8 between 2 variables or Variance inflation factor(VIF) >20 ) The first simple method is to plot the correlation matrix of all the independent variables. I used the housing data from the Kaggle competition. The goal of the competition is to use the housing data input to correctly predict the sales price. I have selected a few numerical variables to be included in my model here. #plot color scaled correlation matrixcorr=house_selected.corr()corr.style.background_gradient(cmap='coolwarm') After plotting the correlation matrix and color scaling the background, we can see the pairwise correlation between all the variables. I have included the dependent variable ‘SalePrice’ here as well. This is because it is a secret trick for me when I try to select the independent variables to be included in the model. When you are clueless about which variables to include in the model, just do a correlation matrix and select those independent variables with high correlation with dependent variable. Back to the Multi-Collinearity issue, we can see that from the correlation matrix, quite a few variables are correlated to each other. There is one pair of independent variables with more than 0.8 correlation which are total basement surface area and first-floor surface area. Houses with larger basement areas tend to have bigger first-floor areas as well and so a high correlation should be expected. The second method to check multi-collinearity is to use the Variance Inflation Factor(VIF) for each independent variable. It is a measure of multicollinearity in the set of multiple regression variables. The higher the value of VIF the higher correlation between this variable and the rest. #Compute VIF data for each independent variablefrom statsmodels.stats.outliers_influence import variance_inflation_factorvif = pd.DataFrame()vif["features"] = house_selected.columnsvif["vif_Factor"] = [variance_inflation_factor(house_selected.values, i) for i in range(house_selected.shape[1])]vif If the VIF value is higher than 10, it is usually considered to have a high correlation with other independent variables. However, the acceptance range is subject to requirements and constraints. From the results, we can see that most features are highly correlated with other independent variables and only two features can pass the below 10 threshold. Variable Selection Variable Selection The most straightforward method is to remove some variables that are highly correlated to others and leave the more significant ones in the set. For example, when we plot the correlation matrix with ‘SalePrice’ included, we can see that Overall Quality and Ground living area have the two highest correlations with the dependent variable ‘SalePrice’ and thus I will try to include them in the model. We can see that using simple elimination, we are able to reduce the VIF value significantly while keeping the important variables. However, some of the variables like Overall Quality and Years of Built still have high VIF value and they are important in predicting housing price. How? Sometimes we can use small tricks as described in the second method later to transform the variable. 2. Variable Transformation The second method is to transform some of the variables to make them less correlated but still maintain their feature. What do I mean by this? In the housing model example, I can transfer ‘years of built’ to ‘age of the house’ by subtracting current year by years of built. For example, if the year of building is1994, then the age of the house is 2020–1994=26 years. After I convert the years of building to house age, the VIF for the new ‘House_age’ factor drops to an acceptable range and the VIF value for overall quality also drops. In the example of time series analysis which I mentioned at the beginning, I also converted variables to make them less correlated. For example, the total return for the past 1 month is highly correlated with the past 6 months' total return. I subtracted the past 1-month return from the past 6-month return to get the new variable on the previous 5-month return which does not include the past month. The correlation results are much more acceptable and I was able to include both variables as my model features. 3. Principal Component Analysis Principal Component Analysis(PCA) is commonly used to reduce the dimension of data by decomposing data into a number of independent factors. It has many applications like simplifying model calculation by reducing the number of predicting factors. However, in our case here, we will just use the character of variable independence for PCA to remove the multi-collinearity issue in the model. #Create the new data frame by transforming data using PCAimport numpy as npfrom sklearn.decomposition import PCApca = PCA(n_components=6)components=pca.fit_transform(house_adjusted)componentsDf=pd.DataFrame(data=components,columns=['component 1','component 2','component 3','component 4','component 5','component 6'])#Calculate VIF for each variable in the new data framevif = pd.DataFrame()vif["features"] = componentsDf.columnsvif["vif_value"] = [variance_inflation_factor(componentsDf.values, i) for i in range(componentsDf.shape[1])]vif I still keep the same number of variables compared to the original data and we can see that now the 6 variables are not correlated to each other at all. We can use the new 6 variables as the independent variables to predict housing prices. The drawback of this method is also very obvious. After PCA transformation, we do not have the identity for each variable and it will be hard to interpret the results. We should check the issue of Multi-Collinearity every time before we build the regression model. VIF would be an easy way to look at each independent variable to see whether they have a high correlation with the rest. A correlation matrix would be useful to select important factors when you are not sure which variables to select for the model. The correlation matrix also helps to understand why certain variables have high VIF values. In terms of methods to fix the multi-collinearity issue, I personally do not prefer PCA here because model interpretation will be lost and when you want to apply the model to another set of data you need to PCA transform again. Thus, we should try our best to reduce the correlation by selecting the right variables and transform them if needed. It is your call to decide whether to keep the variable or not when it has a relatively high VIF value but also important in predicting the result. Trial and error is always the case to include different sets of variables, build the model and test it against testing data to see whether there is any overfitting. Do you think you are finally done with all the checks with statistical assumptions before constructing a model? No, you are not! If you want to know more about other statistical assumptions in a regression model, refer to my other article below on Normality Assumption in the regression model.
[ { "code": null, "e": 467, "s": 172, "text": "Multicollinearity happens when independent variables in the regression model are highly correlated to each other. It makes it hard to interpret of model and also creates an overfitting problem. It is a common assumption that people test before selecting the variables into the regression model." }, { "code": null, "e": 1100, "s": 467, "text": "I encountered a serious multicollinearity issue before when I built the regression model for time series data. I created multiple features based on different time periods like 1-month total return, 6-month total return, and 1-year total return to have more input variables. However, these features are highly correlated with each other. For example, if one stock has performed well for the past year, then it is very likely to have done well for the recent month. I would need to either drop some of these variables or find a way to make them less correlated. I will explain later in the article different ways to solve the problem." }, { "code": null, "e": 1387, "s": 1100, "text": "When independent variables are highly correlated, change in one variable would cause change to another and so the model results fluctuate significantly. The model results will be unstable and vary a lot given a small change in the data or model. This will create the following problems:" }, { "code": null, "e": 1930, "s": 1387, "text": "It would be hard for you to choose the list of significant variables for the model if the model gives you different results every time.Coefficient Estimates would not be stable and it would be hard for you to interpret the model. In other words, you cannot tell the scale of changes to the output if one of your predicting factors changes by 1 unit.The unstable nature of the model may cause overfitting. If you apply the model to another sample of data, the accuracy will drop significantly compared to the accuracy of your training dataset." }, { "code": null, "e": 2066, "s": 1930, "text": "It would be hard for you to choose the list of significant variables for the model if the model gives you different results every time." }, { "code": null, "e": 2281, "s": 2066, "text": "Coefficient Estimates would not be stable and it would be hard for you to interpret the model. In other words, you cannot tell the scale of changes to the output if one of your predicting factors changes by 1 unit." }, { "code": null, "e": 2475, "s": 2281, "text": "The unstable nature of the model may cause overfitting. If you apply the model to another sample of data, the accuracy will drop significantly compared to the accuracy of your training dataset." }, { "code": null, "e": 2765, "s": 2475, "text": "Depending on the situation, it may not be a problem for your model if only slight or moderate collinearity issue occurs. However, it is strongly advised to solve the issue if severe collinearity issue exists(e.g. correlation >0.8 between 2 variables or Variance inflation factor(VIF) >20 )" }, { "code": null, "e": 2857, "s": 2765, "text": "The first simple method is to plot the correlation matrix of all the independent variables." }, { "code": null, "e": 3084, "s": 2857, "text": "I used the housing data from the Kaggle competition. The goal of the competition is to use the housing data input to correctly predict the sales price. I have selected a few numerical variables to be included in my model here." }, { "code": null, "e": 3195, "s": 3084, "text": "#plot color scaled correlation matrixcorr=house_selected.corr()corr.style.background_gradient(cmap='coolwarm')" }, { "code": null, "e": 3515, "s": 3195, "text": "After plotting the correlation matrix and color scaling the background, we can see the pairwise correlation between all the variables. I have included the dependent variable ‘SalePrice’ here as well. This is because it is a secret trick for me when I try to select the independent variables to be included in the model." }, { "code": null, "e": 3699, "s": 3515, "text": "When you are clueless about which variables to include in the model, just do a correlation matrix and select those independent variables with high correlation with dependent variable." }, { "code": null, "e": 4102, "s": 3699, "text": "Back to the Multi-Collinearity issue, we can see that from the correlation matrix, quite a few variables are correlated to each other. There is one pair of independent variables with more than 0.8 correlation which are total basement surface area and first-floor surface area. Houses with larger basement areas tend to have bigger first-floor areas as well and so a high correlation should be expected." }, { "code": null, "e": 4393, "s": 4102, "text": "The second method to check multi-collinearity is to use the Variance Inflation Factor(VIF) for each independent variable. It is a measure of multicollinearity in the set of multiple regression variables. The higher the value of VIF the higher correlation between this variable and the rest." }, { "code": null, "e": 4691, "s": 4393, "text": "#Compute VIF data for each independent variablefrom statsmodels.stats.outliers_influence import variance_inflation_factorvif = pd.DataFrame()vif[\"features\"] = house_selected.columnsvif[\"vif_Factor\"] = [variance_inflation_factor(house_selected.values, i) for i in range(house_selected.shape[1])]vif" }, { "code": null, "e": 5045, "s": 4691, "text": "If the VIF value is higher than 10, it is usually considered to have a high correlation with other independent variables. However, the acceptance range is subject to requirements and constraints. From the results, we can see that most features are highly correlated with other independent variables and only two features can pass the below 10 threshold." }, { "code": null, "e": 5064, "s": 5045, "text": "Variable Selection" }, { "code": null, "e": 5083, "s": 5064, "text": "Variable Selection" }, { "code": null, "e": 5483, "s": 5083, "text": "The most straightforward method is to remove some variables that are highly correlated to others and leave the more significant ones in the set. For example, when we plot the correlation matrix with ‘SalePrice’ included, we can see that Overall Quality and Ground living area have the two highest correlations with the dependent variable ‘SalePrice’ and thus I will try to include them in the model." }, { "code": null, "e": 5869, "s": 5483, "text": "We can see that using simple elimination, we are able to reduce the VIF value significantly while keeping the important variables. However, some of the variables like Overall Quality and Years of Built still have high VIF value and they are important in predicting housing price. How? Sometimes we can use small tricks as described in the second method later to transform the variable." }, { "code": null, "e": 5896, "s": 5869, "text": "2. Variable Transformation" }, { "code": null, "e": 6264, "s": 5896, "text": "The second method is to transform some of the variables to make them less correlated but still maintain their feature. What do I mean by this? In the housing model example, I can transfer ‘years of built’ to ‘age of the house’ by subtracting current year by years of built. For example, if the year of building is1994, then the age of the house is 2020–1994=26 years." }, { "code": null, "e": 6434, "s": 6264, "text": "After I convert the years of building to house age, the VIF for the new ‘House_age’ factor drops to an acceptable range and the VIF value for overall quality also drops." }, { "code": null, "e": 6948, "s": 6434, "text": "In the example of time series analysis which I mentioned at the beginning, I also converted variables to make them less correlated. For example, the total return for the past 1 month is highly correlated with the past 6 months' total return. I subtracted the past 1-month return from the past 6-month return to get the new variable on the previous 5-month return which does not include the past month. The correlation results are much more acceptable and I was able to include both variables as my model features." }, { "code": null, "e": 6980, "s": 6948, "text": "3. Principal Component Analysis" }, { "code": null, "e": 7371, "s": 6980, "text": "Principal Component Analysis(PCA) is commonly used to reduce the dimension of data by decomposing data into a number of independent factors. It has many applications like simplifying model calculation by reducing the number of predicting factors. However, in our case here, we will just use the character of variable independence for PCA to remove the multi-collinearity issue in the model." }, { "code": null, "e": 7912, "s": 7371, "text": "#Create the new data frame by transforming data using PCAimport numpy as npfrom sklearn.decomposition import PCApca = PCA(n_components=6)components=pca.fit_transform(house_adjusted)componentsDf=pd.DataFrame(data=components,columns=['component 1','component 2','component 3','component 4','component 5','component 6'])#Calculate VIF for each variable in the new data framevif = pd.DataFrame()vif[\"features\"] = componentsDf.columnsvif[\"vif_value\"] = [variance_inflation_factor(componentsDf.values, i) for i in range(componentsDf.shape[1])]vif" }, { "code": null, "e": 8152, "s": 7912, "text": "I still keep the same number of variables compared to the original data and we can see that now the 6 variables are not correlated to each other at all. We can use the new 6 variables as the independent variables to predict housing prices." }, { "code": null, "e": 8320, "s": 8152, "text": "The drawback of this method is also very obvious. After PCA transformation, we do not have the identity for each variable and it will be hard to interpret the results." }, { "code": null, "e": 8758, "s": 8320, "text": "We should check the issue of Multi-Collinearity every time before we build the regression model. VIF would be an easy way to look at each independent variable to see whether they have a high correlation with the rest. A correlation matrix would be useful to select important factors when you are not sure which variables to select for the model. The correlation matrix also helps to understand why certain variables have high VIF values." }, { "code": null, "e": 9416, "s": 8758, "text": "In terms of methods to fix the multi-collinearity issue, I personally do not prefer PCA here because model interpretation will be lost and when you want to apply the model to another set of data you need to PCA transform again. Thus, we should try our best to reduce the correlation by selecting the right variables and transform them if needed. It is your call to decide whether to keep the variable or not when it has a relatively high VIF value but also important in predicting the result. Trial and error is always the case to include different sets of variables, build the model and test it against testing data to see whether there is any overfitting." } ]
How to fetch elements with iterator in Java?
Let us first create a List and add elements − List<String>list = Arrays.asList(new String[] { "P", "Q", "R", "S", "T", "U", "V", "W" }); Now, use Iterator to fetch each element − Iterator<String>i = list.iterator(); Display the elements − while (i.hasNext()) { System.out.println(i.next()); } Live Demo import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Demo { public static void main(String[] a) { List<String>list = Arrays.asList(new String[] { "P", "Q", "R", "S", "T", "U", "V", "W" }); Iterator<String>i = list.iterator(); System.out.println("Displaying elements..."); while (i.hasNext()) { System.out.println(i.next()); } } } Displaying elements... P Q R S T U V W
[ { "code": null, "e": 1108, "s": 1062, "text": "Let us first create a List and add elements −" }, { "code": null, "e": 1199, "s": 1108, "text": "List<String>list = Arrays.asList(new String[] { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\" });" }, { "code": null, "e": 1241, "s": 1199, "text": "Now, use Iterator to fetch each element −" }, { "code": null, "e": 1278, "s": 1241, "text": "Iterator<String>i = list.iterator();" }, { "code": null, "e": 1301, "s": 1278, "text": "Display the elements −" }, { "code": null, "e": 1358, "s": 1301, "text": "while (i.hasNext()) {\n System.out.println(i.next());\n}" }, { "code": null, "e": 1369, "s": 1358, "text": " Live Demo" }, { "code": null, "e": 1779, "s": 1369, "text": "import java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] a) {\n List<String>list = Arrays.asList(new String[] { \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\" });\n Iterator<String>i = list.iterator();\n System.out.println(\"Displaying elements...\");\n while (i.hasNext()) {\n System.out.println(i.next());\n }\n }\n}" }, { "code": null, "e": 1818, "s": 1779, "text": "Displaying elements...\nP\nQ\nR\nS\nT\nU\nV\nW" } ]
How to zoom-in and zoom-out image using JavaScript ?
20 Sep, 2019 Given an image and the task is to increase and decrease the image size using JavaScript. Use the following property to increase and decrease the image. Using Width property: It is used to change the new values to resize the width of the element. Syntax: object.style.width = "auto|length|%|initial|inherit" Approach: Get the selector of the required image using .getElementById(selector). Store the current width value in the variable using .clientWidth. Now change the width value to new using .style.width. It will proportionally increase and decrease the dimension of an image. Example: <!DOCTYPE html><html> <head> <title> How to zoom-in and zoom-out image using JavaScript ? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> JavaScript | Increase and Decrease image size </h3> <hr> <div class="box"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190912174307/qwe1.png" id="geeks" GFG="250" alt="Geeksforgeeks"> </div> <hr> <button type="button" onclick="zoomin()"> Zoom-In </button> <button type="button" onclick="zoomout()"> Zoom-Out </button> <script type="text/javascript"> function zoomin() { var GFG = document.getElementById("geeks"); var currWidth = GFG.clientWidth; GFG.style.width = (currWidth + 100) + "px"; } function zoomout() { var GFG = document.getElementById("geeks"); var currWidth = GFG.clientWidth; GFG.style.width = (currWidth - 100) + "px"; } </script></body> </html> Output: Before click on button: After click on Zoom-In Button: After click on Zoom-Out Button: Using Height property: It is used to change the new values to resize the height of the element. Syntax: object.style.height = "auto|length|%|initial|inherit" Approach: Get the selector of the required image using .getElementById(selector). Store the current height value in the variable using .clientHeight. Now change the width value to new using .style.height. It will proportionally increase and decrease the dimension of an image. Example: <!DOCTYPE html><html> <head> <title> How to zoom-in and zoom-out image using JavaScript ? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> JavaScript | Increase and Decrease image size </h3> <hr> <div class="box"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190912174307/qwe1.png" id="geeks" GFG="250" alt="Geeksforgeeks"> </div> <hr> <button type="button" onclick="zoomin()"> Zoom-In </button> <button type="button" onclick="zoomout()"> Zoom-Out </button> <script type="text/javascript"> function zoomin() { var GFG = document.getElementById("geeks"); var currHeight = GFG.clientHeight; GFG.style.height = (currHeight + 40) + "px"; } function zoomout() { var GFG = document.getElementById("geeks"); var currHeight = GFG.clientHeight; GFG.style.height = (currHeight - 40) + "px"; } </script></body> </html> Output: Before click on button: After click on Zoom-In Button: After click on Zoom-Out Button: 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": 28, "s": 0, "text": "\n20 Sep, 2019" }, { "code": null, "e": 180, "s": 28, "text": "Given an image and the task is to increase and decrease the image size using JavaScript. Use the following property to increase and decrease the image." }, { "code": null, "e": 274, "s": 180, "text": "Using Width property: It is used to change the new values to resize the width of the element." }, { "code": null, "e": 282, "s": 274, "text": "Syntax:" }, { "code": null, "e": 335, "s": 282, "text": "object.style.width = \"auto|length|%|initial|inherit\"" }, { "code": null, "e": 345, "s": 335, "text": "Approach:" }, { "code": null, "e": 417, "s": 345, "text": "Get the selector of the required image using .getElementById(selector)." }, { "code": null, "e": 483, "s": 417, "text": "Store the current width value in the variable using .clientWidth." }, { "code": null, "e": 537, "s": 483, "text": "Now change the width value to new using .style.width." }, { "code": null, "e": 609, "s": 537, "text": "It will proportionally increase and decrease the dimension of an image." }, { "code": null, "e": 618, "s": 609, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to zoom-in and zoom-out image using JavaScript ? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> JavaScript | Increase and Decrease image size </h3> <hr> <div class=\"box\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190912174307/qwe1.png\" id=\"geeks\" GFG=\"250\" alt=\"Geeksforgeeks\"> </div> <hr> <button type=\"button\" onclick=\"zoomin()\"> Zoom-In </button> <button type=\"button\" onclick=\"zoomout()\"> Zoom-Out </button> <script type=\"text/javascript\"> function zoomin() { var GFG = document.getElementById(\"geeks\"); var currWidth = GFG.clientWidth; GFG.style.width = (currWidth + 100) + \"px\"; } function zoomout() { var GFG = document.getElementById(\"geeks\"); var currWidth = GFG.clientWidth; GFG.style.width = (currWidth - 100) + \"px\"; } </script></body> </html> ", "e": 1859, "s": 618, "text": null }, { "code": null, "e": 1867, "s": 1859, "text": "Output:" }, { "code": null, "e": 1891, "s": 1867, "text": "Before click on button:" }, { "code": null, "e": 1922, "s": 1891, "text": "After click on Zoom-In Button:" }, { "code": null, "e": 1954, "s": 1922, "text": "After click on Zoom-Out Button:" }, { "code": null, "e": 2050, "s": 1954, "text": "Using Height property: It is used to change the new values to resize the height of the element." }, { "code": null, "e": 2058, "s": 2050, "text": "Syntax:" }, { "code": null, "e": 2112, "s": 2058, "text": "object.style.height = \"auto|length|%|initial|inherit\"" }, { "code": null, "e": 2122, "s": 2112, "text": "Approach:" }, { "code": null, "e": 2194, "s": 2122, "text": "Get the selector of the required image using .getElementById(selector)." }, { "code": null, "e": 2262, "s": 2194, "text": "Store the current height value in the variable using .clientHeight." }, { "code": null, "e": 2317, "s": 2262, "text": "Now change the width value to new using .style.height." }, { "code": null, "e": 2389, "s": 2317, "text": "It will proportionally increase and decrease the dimension of an image." }, { "code": null, "e": 2398, "s": 2389, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to zoom-in and zoom-out image using JavaScript ? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> JavaScript | Increase and Decrease image size </h3> <hr> <div class=\"box\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190912174307/qwe1.png\" id=\"geeks\" GFG=\"250\" alt=\"Geeksforgeeks\"> </div> <hr> <button type=\"button\" onclick=\"zoomin()\"> Zoom-In </button> <button type=\"button\" onclick=\"zoomout()\"> Zoom-Out </button> <script type=\"text/javascript\"> function zoomin() { var GFG = document.getElementById(\"geeks\"); var currHeight = GFG.clientHeight; GFG.style.height = (currHeight + 40) + \"px\"; } function zoomout() { var GFG = document.getElementById(\"geeks\"); var currHeight = GFG.clientHeight; GFG.style.height = (currHeight - 40) + \"px\"; } </script></body> </html>", "e": 3627, "s": 2398, "text": null }, { "code": null, "e": 3635, "s": 3627, "text": "Output:" }, { "code": null, "e": 3659, "s": 3635, "text": "Before click on button:" }, { "code": null, "e": 3690, "s": 3659, "text": "After click on Zoom-In Button:" }, { "code": null, "e": 3722, "s": 3690, "text": "After click on Zoom-Out Button:" }, { "code": null, "e": 3733, "s": 3722, "text": "JavaScript" }, { "code": null, "e": 3750, "s": 3733, "text": "Web Technologies" }, { "code": null, "e": 3777, "s": 3750, "text": "Web technologies Questions" }, { "code": null, "e": 3875, "s": 3777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3936, "s": 3875, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4008, "s": 3936, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4048, "s": 4008, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4089, "s": 4048, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4141, "s": 4089, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 4174, "s": 4141, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4236, "s": 4174, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4297, "s": 4236, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4347, "s": 4297, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Keras - Installation
This chapter explains about how to install Keras on your machine. Before moving to installation, let us go through the basic requirements of Keras. You must satisfy the following requirements − Any kind of OS (Windows, Linux or Mac) Python version 3.5 or higher. Keras is python based neural network library so python must be installed on your machine. If python is properly installed on your machine, then open your terminal and type python, you could see the response similar as specified below, Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> As of now the latest version is ‘3.7.2’. If Python is not installed, then visit the official python link - www.python.org and download the latest version based on your OS and install it immediately on your system. Keras installation is quite easy. Follow below steps to properly install Keras on your system. Virtualenv is used to manage Python packages for different projects. This will be helpful to avoid breaking the packages installed in the other environments. So, it is always recommended to use a virtual environment while developing Python applications. Linux/Mac OS Linux or mac OS users, go to your project root directory and type the below command to create virtual environment, python3 -m venv kerasenv After executing the above command, “kerasenv” directory is created with bin,lib and include folders in your installation location. Windows Windows user can use the below command, py -m venv keras This step will configure python and pip executables in your shell path. Linux/Mac OS Now we have created a virtual environment named “kerasvenv”. Move to the folder and type the below command, $ cd kerasvenv kerasvenv $ source bin/activate Windows Windows users move inside the “kerasenv” folder and type the below command, .\env\Scripts\activate Keras depends on the following python libraries. Numpy Pandas Scikit-learn Matplotlib Scipy Seaborn Hopefully, you have installed all the above libraries on your system. If these libraries are not installed, then use the below command to install one by one. numpy pip install numpy you could see the following response, Collecting numpy Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ numpy-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s pandas pip install pandas We could see the following response, Collecting pandas Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ pandas-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s matplotlib pip install matplotlib We could see the following response, Collecting matplotlib Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ matplotlib-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s scipy pip install scipy We could see the following response, Collecting scipy Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8 /scipy-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s scikit-learn It is an open source machine learning library. It is used for classification, regression and clustering algorithms. Before moving to the installation, it requires the following − Python version 3.5 or higher NumPy version 1.11.0 or higher SciPy version 0.17.0 or higher joblib 0.11 or higher. Now, we install scikit-learn using the below command − pip install -U scikit-learn Seaborn Seaborn is an amazing library that allows you to easily visualize your data. Use the below command to install − pip install seaborn You could see the message similar as specified below − Collecting seaborn Downloading https://files.pythonhosted.org/packages/a8/76/220ba4420459d9c4c9c9587c6ce607bf56c25b3d3d2de62056efe482dadc /seaborn-0.9.0-py3-none-any.whl (208kB) 100% |████████████████████████████████| 215kB 4.0MB/s Requirement already satisfied: numpy> = 1.9.3 in ./lib/python3.7/site-packages (from seaborn) (1.17.0) Collecting pandas> = 0.15.2 (from seaborn) Downloading https://files.pythonhosted.org/packages/39/b7/441375a152f3f9929ff8bc2915218ff1a063a59d7137ae0546db616749f9/ pandas-0.25.0-cp37-cp37m-macosx_10_9_x86_64. macosx_10_10_x86_64.whl (10.1MB) 100% |████████████████████████████████| 10.1MB 1.8MB/s Requirement already satisfied: scipy>=0.14.0 in ./lib/python3.7/site-packages (from seaborn) (1.3.0) Collecting matplotlib> = 1.4.3 (from seaborn) Downloading https://files.pythonhosted.org/packages/c3/8b/af9e0984f 5c0df06d3fab0bf396eb09cbf05f8452de4e9502b182f59c33b/ matplotlib-3.1.1-cp37-cp37m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64 .macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) 100% |████████████████████████████████| 14.4MB 1.4MB/s ...................................... ...................................... Successfully installed cycler-0.10.0 kiwisolver-1.1.0 matplotlib-3.1.1 pandas-0.25.0 pyparsing-2.4.2 python-dateutil-2.8.0 pytz-2019.2 seaborn-0.9.0 As of now, we have completed basic requirements for the installtion of Kera. Now, install the Keras using same procedure as specified below − pip install keras After finishing all your changes in your project, then simply run the below command to quit the environment − deactivate We believe that you have installed anaconda cloud on your machine. If anaconda is not installed, then visit the official link, www.anaconda.com/distribution and choose download based on your OS. Launch anaconda prompt, this will open base Anaconda environment. Let us create a new conda environment. This process is similar to virtualenv. Type the below command in your conda terminal − conda create --name PythonCPU If you want, you can create and install modules using GPU also. In this tutorial, we follow CPU instructions. To activate the environment, use the below command − activate PythonCPU Spyder is an IDE for executing python applications. Let us install this IDE in our conda environment using the below command − conda install spyder We have already known the python libraries numpy, pandas, etc., needed for keras. You can install all the modules by using the below syntax − Syntax conda install -c anaconda <module-name> For example, you want to install pandas − conda install -c anaconda pandas Like the same method, try it yourself to install the remaining modules. Now, everything looks good so you can start keras installation using the below command − conda install -c anaconda keras Finally, launch spyder in your conda terminal using the below command − spyder To ensure everything was installed correctly, import all the modules, it will add everything and if anything went wrong, you will get module not found error message.
[ { "code": null, "e": 2333, "s": 2185, "text": "This chapter explains about how to install Keras on your machine. Before moving to installation, let us go through the basic requirements of Keras." }, { "code": null, "e": 2379, "s": 2333, "text": "You must satisfy the following requirements −" }, { "code": null, "e": 2418, "s": 2379, "text": "Any kind of OS (Windows, Linux or Mac)" }, { "code": null, "e": 2448, "s": 2418, "text": "Python version 3.5 or higher." }, { "code": null, "e": 2683, "s": 2448, "text": "Keras is python based neural network library so python must be installed on your machine. If python is properly installed on your machine, then open your terminal and type python, you could see the response similar as specified below," }, { "code": null, "e": 2855, "s": 2683, "text": "Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) \n[MSC v.1900 64 bit (AMD64)] on win32 \nType \"help\", \"copyright\", \"credits\" or \"license\" for more information. \n>>>\n" }, { "code": null, "e": 3069, "s": 2855, "text": "As of now the latest version is ‘3.7.2’. If Python is not installed, then visit the official python link - www.python.org and download the latest version based on your OS and install it immediately on your system." }, { "code": null, "e": 3164, "s": 3069, "text": "Keras installation is quite easy. Follow below steps to properly install Keras on your system." }, { "code": null, "e": 3418, "s": 3164, "text": "Virtualenv is used to manage Python packages for different projects. This will be helpful to avoid breaking the packages installed in the other environments. So, it is always recommended to use a virtual environment while developing Python applications." }, { "code": null, "e": 3431, "s": 3418, "text": "Linux/Mac OS" }, { "code": null, "e": 3546, "s": 3431, "text": "Linux or mac OS users, go to your project root directory and type the below command to create virtual environment," }, { "code": null, "e": 3572, "s": 3546, "text": "python3 -m venv kerasenv\n" }, { "code": null, "e": 3703, "s": 3572, "text": "After executing the above command, “kerasenv” directory is created with bin,lib and include folders in your installation location." }, { "code": null, "e": 3711, "s": 3703, "text": "Windows" }, { "code": null, "e": 3751, "s": 3711, "text": "Windows user can use the below command," }, { "code": null, "e": 3769, "s": 3751, "text": "py -m venv keras\n" }, { "code": null, "e": 3841, "s": 3769, "text": "This step will configure python and pip executables in your shell path." }, { "code": null, "e": 3854, "s": 3841, "text": "Linux/Mac OS" }, { "code": null, "e": 3962, "s": 3854, "text": "Now we have created a virtual environment named “kerasvenv”. Move to the folder and type the below command," }, { "code": null, "e": 4010, "s": 3962, "text": "$ cd kerasvenv kerasvenv $ source bin/activate\n" }, { "code": null, "e": 4018, "s": 4010, "text": "Windows" }, { "code": null, "e": 4094, "s": 4018, "text": "Windows users move inside the “kerasenv” folder and type the below command," }, { "code": null, "e": 4118, "s": 4094, "text": ".\\env\\Scripts\\activate\n" }, { "code": null, "e": 4167, "s": 4118, "text": "Keras depends on the following python libraries." }, { "code": null, "e": 4173, "s": 4167, "text": "Numpy" }, { "code": null, "e": 4180, "s": 4173, "text": "Pandas" }, { "code": null, "e": 4193, "s": 4180, "text": "Scikit-learn" }, { "code": null, "e": 4204, "s": 4193, "text": "Matplotlib" }, { "code": null, "e": 4210, "s": 4204, "text": "Scipy" }, { "code": null, "e": 4218, "s": 4210, "text": "Seaborn" }, { "code": null, "e": 4376, "s": 4218, "text": "Hopefully, you have installed all the above libraries on your system. If these libraries are not installed, then use the below command to install one by one." }, { "code": null, "e": 4382, "s": 4376, "text": "numpy" }, { "code": null, "e": 4401, "s": 4382, "text": "pip install numpy\n" }, { "code": null, "e": 4439, "s": 4401, "text": "you could see the following response," }, { "code": null, "e": 4779, "s": 4439, "text": "Collecting numpy \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ \n numpy-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 4786, "s": 4779, "text": "pandas" }, { "code": null, "e": 4806, "s": 4786, "text": "pip install pandas\n" }, { "code": null, "e": 4843, "s": 4806, "text": "We could see the following response," }, { "code": null, "e": 5182, "s": 4843, "text": "Collecting pandas \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ \npandas-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 5193, "s": 5182, "text": "matplotlib" }, { "code": null, "e": 5217, "s": 5193, "text": "pip install matplotlib\n" }, { "code": null, "e": 5254, "s": 5217, "text": "We could see the following response," }, { "code": null, "e": 5601, "s": 5254, "text": "Collecting matplotlib \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ \nmatplotlib-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 5607, "s": 5601, "text": "scipy" }, { "code": null, "e": 5626, "s": 5607, "text": "pip install scipy\n" }, { "code": null, "e": 5663, "s": 5626, "text": "We could see the following response," }, { "code": null, "e": 6000, "s": 5663, "text": "Collecting scipy \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8 \n/scipy-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 6013, "s": 6000, "text": "scikit-learn" }, { "code": null, "e": 6192, "s": 6013, "text": "It is an open source machine learning library. It is used for classification, regression and clustering algorithms. Before moving to the installation, it requires the following −" }, { "code": null, "e": 6221, "s": 6192, "text": "Python version 3.5 or higher" }, { "code": null, "e": 6252, "s": 6221, "text": "NumPy version 1.11.0 or higher" }, { "code": null, "e": 6283, "s": 6252, "text": "SciPy version 0.17.0 or higher" }, { "code": null, "e": 6306, "s": 6283, "text": "joblib 0.11 or higher." }, { "code": null, "e": 6361, "s": 6306, "text": "Now, we install scikit-learn using the below command −" }, { "code": null, "e": 6390, "s": 6361, "text": "pip install -U scikit-learn\n" }, { "code": null, "e": 6398, "s": 6390, "text": "Seaborn" }, { "code": null, "e": 6510, "s": 6398, "text": "Seaborn is an amazing library that allows you to easily visualize your data. Use the below command to install −" }, { "code": null, "e": 6531, "s": 6510, "text": "pip install seaborn\n" }, { "code": null, "e": 6586, "s": 6531, "text": "You could see the message similar as specified below −" }, { "code": null, "e": 7947, "s": 6586, "text": "Collecting seaborn \n Downloading \nhttps://files.pythonhosted.org/packages/a8/76/220ba4420459d9c4c9c9587c6ce607bf56c25b3d3d2de62056efe482dadc \n/seaborn-0.9.0-py3-none-any.whl (208kB) 100% \n |████████████████████████████████| 215kB 4.0MB/s \nRequirement already satisfied: numpy> = 1.9.3 in \n./lib/python3.7/site-packages (from seaborn) (1.17.0) \nCollecting pandas> = 0.15.2 (from seaborn) \n Downloading \nhttps://files.pythonhosted.org/packages/39/b7/441375a152f3f9929ff8bc2915218ff1a063a59d7137ae0546db616749f9/ \npandas-0.25.0-cp37-cp37m-macosx_10_9_x86_64.\nmacosx_10_10_x86_64.whl (10.1MB) 100% \n |████████████████████████████████| 10.1MB 1.8MB/s \nRequirement already satisfied: scipy>=0.14.0 in \n./lib/python3.7/site-packages (from seaborn) (1.3.0) \nCollecting matplotlib> = 1.4.3 (from seaborn) \n Downloading \nhttps://files.pythonhosted.org/packages/c3/8b/af9e0984f\n5c0df06d3fab0bf396eb09cbf05f8452de4e9502b182f59c33b/ \nmatplotlib-3.1.1-cp37-cp37m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64 \n.macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) 100% \n |████████████████████████████████| 14.4MB 1.4MB/s \n...................................... \n...................................... \nSuccessfully installed cycler-0.10.0 kiwisolver-1.1.0 \nmatplotlib-3.1.1 pandas-0.25.0 pyparsing-2.4.2 \npython-dateutil-2.8.0 pytz-2019.2 seaborn-0.9.0\n" }, { "code": null, "e": 8089, "s": 7947, "text": "As of now, we have completed basic requirements for the installtion of Kera. Now, install the Keras using same procedure as specified below −" }, { "code": null, "e": 8108, "s": 8089, "text": "pip install keras\n" }, { "code": null, "e": 8218, "s": 8108, "text": "After finishing all your changes in your project, then simply run the below command to quit the environment −" }, { "code": null, "e": 8230, "s": 8218, "text": "deactivate\n" }, { "code": null, "e": 8425, "s": 8230, "text": "We believe that you have installed anaconda cloud on your machine. If anaconda is not installed, then visit the official link, www.anaconda.com/distribution and choose download based on your OS." }, { "code": null, "e": 8617, "s": 8425, "text": "Launch anaconda prompt, this will open base Anaconda environment. Let us create a new conda environment. This process is similar to virtualenv. Type the below command in your conda terminal −" }, { "code": null, "e": 8648, "s": 8617, "text": "conda create --name PythonCPU\n" }, { "code": null, "e": 8758, "s": 8648, "text": "If you want, you can create and install modules using GPU also. In this tutorial, we follow CPU instructions." }, { "code": null, "e": 8811, "s": 8758, "text": "To activate the environment, use the below command −" }, { "code": null, "e": 8831, "s": 8811, "text": "activate PythonCPU\n" }, { "code": null, "e": 8958, "s": 8831, "text": "Spyder is an IDE for executing python applications. Let us install this IDE in our conda environment using the below command −" }, { "code": null, "e": 8980, "s": 8958, "text": "conda install spyder\n" }, { "code": null, "e": 9122, "s": 8980, "text": "We have already known the python libraries numpy, pandas, etc., needed for keras. You can install all the modules by using the below syntax −" }, { "code": null, "e": 9129, "s": 9122, "text": "Syntax" }, { "code": null, "e": 9170, "s": 9129, "text": "conda install -c anaconda <module-name>\n" }, { "code": null, "e": 9212, "s": 9170, "text": "For example, you want to install pandas −" }, { "code": null, "e": 9246, "s": 9212, "text": "conda install -c anaconda pandas\n" }, { "code": null, "e": 9318, "s": 9246, "text": "Like the same method, try it yourself to install the remaining modules." }, { "code": null, "e": 9407, "s": 9318, "text": "Now, everything looks good so you can start keras installation using the below command −" }, { "code": null, "e": 9440, "s": 9407, "text": "conda install -c anaconda keras\n" }, { "code": null, "e": 9512, "s": 9440, "text": "Finally, launch spyder in your conda terminal using the below command −" }, { "code": null, "e": 9520, "s": 9512, "text": "spyder\n" } ]
Maximum length substring having all same characters after k changes
23 Jun, 2022 We have a string of length n, which consist only UPPER and LOWER CASE characters and we have a number k (always less than n and greater than 0). We can make at most k changes in our string such that we can get a sub-string of maximum length which have all same characters.Examples: n = length of string k = changes you can make Input : n = 5 k = 2 str = ABABA Output : maximum length = 5 which will be (AAAAA) Input : n = 6 k = 4 str = HHHHHH Output : maximum length=6 which will be(HHHHHH) We check for each character of English alphabet (both upper and lower cases one by one). We are basically looking for maximum length of sub-string that can be formed by each character and whichever character will form the sub-string of maximum length then that length will be our answer. We check for maximum length of sub-string that can be formed by every character in a set of 52 characters (From ‘A’ to ‘Z’ and from ‘a’ to ‘z’).For doing this we traverse whole string and whenever we find a different character, we increase the count.If count becomes greater than k (at right index), we again start from 0th index and if we found different character we will decrease the count.When count will be equal to k (at left index) then at that point the length will be rightIndex-leftIndex+1.We repeat this process until we reach at the end of string and at that point we will return the maximum length.We do this for all characters and finally return the maximum length. We check for maximum length of sub-string that can be formed by every character in a set of 52 characters (From ‘A’ to ‘Z’ and from ‘a’ to ‘z’). For doing this we traverse whole string and whenever we find a different character, we increase the count. If count becomes greater than k (at right index), we again start from 0th index and if we found different character we will decrease the count. When count will be equal to k (at left index) then at that point the length will be rightIndex-leftIndex+1. We repeat this process until we reach at the end of string and at that point we will return the maximum length. We do this for all characters and finally return the maximum length. C++ Java Python3 C# PHP Javascript // C++ program to find maximum length equal// character string with k changes#include <iostream>using namespace std; // function to find the maximum length of// substring having character chint findLen(string& A, int n, int k, char ch){ int maxlen = 1; int cnt = 0; int l = 0, r = 0; // traverse the whole string while (r < n) { /* if character is not same as ch increase count */ if (A[r] != ch) ++cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while (cnt > k) { if (A[l] != ch) --cnt; ++l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ maxlen = max(maxlen, r - l + 1); ++r; } return maxlen;} // function which returns maximum length of substringint answer(string& A, int n, int k){ int maxlen = 1; for (int i = 0; i < 26; ++i) { maxlen = max(maxlen, findLen(A, n, k, i+'A')); maxlen = max(maxlen, findLen(A, n, k, i+'a')); } return maxlen;} // Driver codeint main(){ int n = 5, k = 2; string A = "ABABA"; cout << "Maximum length = " << answer(A, n, k) << endl; n = 6, k = 4; string B = "HHHHHH"; cout << "Maximum length = " << answer(B, n, k) << endl; return 0;} // Java program to find maximum length equal// character string with k changes public class GFG{ // method to find the maximum length of // substring having character ch static int findLen(String A, int n, int k, char ch) { int maxlen = 1; int cnt = 0; int l = 0, r = 0; // traverse the whole string while (r < n) { /* if character is not same as ch increase count */ if (A.charAt(r) != ch) ++cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while (cnt > k) { if (A.charAt(l) != ch) --cnt; ++l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ maxlen = Math.max(maxlen, r - l + 1); ++r; } return maxlen; } // method which returns maximum length of substring static int answer(String A, int n, int k) { int maxlen = 1; for (int i = 0; i < 26; ++i) { maxlen = Math.max(maxlen, findLen(A, n, k, (char) (i+'A'))); maxlen = Math.max(maxlen, findLen(A, n, k, (char) (i+'a'))); } return maxlen; } // Driver Method public static void main(String[] args) { int n = 5, k = 2; String A = "ABABA"; System.out.println("Maximum length = " + answer(A, n, k)); n = 6; k = 4; String B = "HHHHHH"; System.out.println("Maximum length = " + answer(B, n, k)); }} # Python3 program to find maximum length# equal character string with k changes # function to find the maximum length of# substring having character chdef findLen(A, n, k, ch): maxlen = 1 cnt = 0 l = 0 r = 0 # traverse the whole string while r < n: # if character is not same as ch # increase count if A[r] != ch: cnt += 1 # While count > k traverse the string # again until count becomes less than k # and decrease the count when characters # are not same while cnt > k: if A[l] != ch: cnt -= 1 l += 1 # length of substring will be rightIndex - # leftIndex + 1. Compare this with the # maximum length and return maximum length maxlen = max(maxlen, r - l + 1) r += 1 return maxlen # function which returns# maximum length of substringdef answer(A, n, k): maxlen = 1 for i in range(26): maxlen = max(maxlen, findLen(A, n, k, chr(i + ord('A')))) maxlen = max(maxlen, findLen(A, n, k, chr(i + ord('a')))) return maxlen # Driver Codeif __name__ == "__main__": n = 5 k = 2 A = "ABABA" print("Maximum length =", answer(A, n, k)) n = 6 k = 4 B = "HHHHHH" print("Maximum length =", answer(B, n, k)) # This code is contributed by# sanjeev2552 // C# program to find maximum length equal// character string with k changesusing System; class GFG{ // method to find the maximum length of // substring having character ch public static int findLen(string A, int n, int k, char ch) { int maxlen = 1; int cnt = 0; int l = 0, r = 0; // traverse the whole string while (r < n) { // if character is // not same as ch // increase count if (A[r] != ch) { ++cnt; } // While count > k traverse // the string again until // count becomes less than // k and decrease the // count when characters // are not same while (cnt > k) { if (A[l] != ch) { --cnt; } ++l; } // length of substring // will be rightIndex - // leftIndex + 1. // Compare this with the maximum // length and return maximum length maxlen = Math.Max(maxlen, r - l + 1); ++r; } return maxlen; } // method which returns // maximum length of substring public static int answer(string A, int n, int k) { int maxlen = 1; for (int i = 0; i < 26; ++i) { maxlen = Math.Max(maxlen, findLen(A, n, k, (char)(i + 'A'))); maxlen = Math.Max(maxlen, findLen(A, n, k, (char)(i + 'a'))); } return maxlen; } // Driver Methodpublic static void Main(string[] args){ int n = 5, k = 2; string A = "ABABA"; Console.WriteLine("Maximum length = " + answer(A, n, k)); n = 6; k = 4; string B = "HHHHHH"; Console.WriteLine("Maximum length = " + answer(B, n, k));}} // This code is contributed by Shrikant13 <?php// PHP program to find maximum length equal// character string with k changes // function to find the maximum length// of substring having character chfunction findLen($A, $n, $k, $ch){ $maxlen = 1; $cnt = 0; $l = 0; $r = 0; // traverse the whole string while ($r < $n) { /* if character is not same as ch increase count */ if ($A[$r] != $ch) ++$cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while ($cnt > $k) { if ($A[$l] != $ch) --$cnt; ++$l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ $maxlen = max($maxlen, $r - $l + 1); ++$r; } return $maxlen;} // function which returns maximum// length of substringfunction answer($A, $n, $k){ $maxlen = 1; for ($i = 0; $i < 26; ++$i) { $maxlen = max($maxlen, findLen($A, $n, $k, $i + 'A')); $maxlen = max($maxlen, findLen($A, $n, $k, $i + 'a')); } return $maxlen;} // Driver code$n = 5; $k = 2; $A = "ABABA";echo "Maximum length = " . answer($A, $n, $k) . "\n"; $n = 6; $k = 4; $B = "HHHHHH";echo "Maximum length = " . answer($B, $n, $k) . "\n"; // This code is contributed by ita_c?> <script>// Javascript program to find maximum length equal// character string with k changes // method to find the maximum length of // substring having character ch function findLen(A,n,k,ch) { let maxlen = 1; let cnt = 0; let l = 0, r = 0; // traverse the whole string while (r < n) { /* if character is not same as ch increase count */ if (A[r] != ch) ++cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while (cnt > k) { if (A[l] != ch) --cnt; ++l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ maxlen = Math.max(maxlen, r - l + 1); ++r; } return maxlen; } // method which returns maximum length of substring function answer(A,n,k) { let maxlen = 1; for (let i = 0; i < 26; ++i) { maxlen = Math.max(maxlen, findLen(A, n, k, String.fromCharCode(i+'A'.charCodeAt(0)))); maxlen = Math.max(maxlen, findLen(A, n, k, String.fromCharCode (i+'a'.charCodeAt(0)))); } return maxlen; } // Driver Method let n = 5, k = 2; let A = "ABABA"; document.write("Maximum length = " + answer(A, n, k)+"<br>"); n = 6; k = 4; let B = "HHHHHH"; document.write("Maximum length = " + answer(B, n, k)); //This code is contributed by rag2127 </script> Output: Maximum length = 5 Maximum length = 6 Time Complexity: O(n) Auxiliary Space: O(1)This article is contributed by Niteesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 ukasp sanjeev2552 rag2127 shivamanandrj9 Misc Strings Misc Strings Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write Regular Expressions? Association Rule OOPs | Object Oriented Design std::unique in C++ Software Engineering | Prototyping Model Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 336, "s": 52, "text": "We have a string of length n, which consist only UPPER and LOWER CASE characters and we have a number k (always less than n and greater than 0). We can make at most k changes in our string such that we can get a sub-string of maximum length which have all same characters.Examples: " }, { "code": null, "e": 562, "s": 336, "text": "n = length of string\nk = changes you can make\nInput : n = 5 k = 2\n str = ABABA\nOutput : maximum length = 5\nwhich will be (AAAAA)\n\nInput : n = 6 k = 4\n str = HHHHHH\nOutput : maximum length=6\nwhich will be(HHHHHH) " }, { "code": null, "e": 853, "s": 564, "text": "We check for each character of English alphabet (both upper and lower cases one by one). We are basically looking for maximum length of sub-string that can be formed by each character and whichever character will form the sub-string of maximum length then that length will be our answer. " }, { "code": null, "e": 1533, "s": 853, "text": "We check for maximum length of sub-string that can be formed by every character in a set of 52 characters (From ‘A’ to ‘Z’ and from ‘a’ to ‘z’).For doing this we traverse whole string and whenever we find a different character, we increase the count.If count becomes greater than k (at right index), we again start from 0th index and if we found different character we will decrease the count.When count will be equal to k (at left index) then at that point the length will be rightIndex-leftIndex+1.We repeat this process until we reach at the end of string and at that point we will return the maximum length.We do this for all characters and finally return the maximum length." }, { "code": null, "e": 1678, "s": 1533, "text": "We check for maximum length of sub-string that can be formed by every character in a set of 52 characters (From ‘A’ to ‘Z’ and from ‘a’ to ‘z’)." }, { "code": null, "e": 1785, "s": 1678, "text": "For doing this we traverse whole string and whenever we find a different character, we increase the count." }, { "code": null, "e": 1929, "s": 1785, "text": "If count becomes greater than k (at right index), we again start from 0th index and if we found different character we will decrease the count." }, { "code": null, "e": 2037, "s": 1929, "text": "When count will be equal to k (at left index) then at that point the length will be rightIndex-leftIndex+1." }, { "code": null, "e": 2149, "s": 2037, "text": "We repeat this process until we reach at the end of string and at that point we will return the maximum length." }, { "code": null, "e": 2218, "s": 2149, "text": "We do this for all characters and finally return the maximum length." }, { "code": null, "e": 2224, "s": 2220, "text": "C++" }, { "code": null, "e": 2229, "s": 2224, "text": "Java" }, { "code": null, "e": 2237, "s": 2229, "text": "Python3" }, { "code": null, "e": 2240, "s": 2237, "text": "C#" }, { "code": null, "e": 2244, "s": 2240, "text": "PHP" }, { "code": null, "e": 2255, "s": 2244, "text": "Javascript" }, { "code": "// C++ program to find maximum length equal// character string with k changes#include <iostream>using namespace std; // function to find the maximum length of// substring having character chint findLen(string& A, int n, int k, char ch){ int maxlen = 1; int cnt = 0; int l = 0, r = 0; // traverse the whole string while (r < n) { /* if character is not same as ch increase count */ if (A[r] != ch) ++cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while (cnt > k) { if (A[l] != ch) --cnt; ++l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ maxlen = max(maxlen, r - l + 1); ++r; } return maxlen;} // function which returns maximum length of substringint answer(string& A, int n, int k){ int maxlen = 1; for (int i = 0; i < 26; ++i) { maxlen = max(maxlen, findLen(A, n, k, i+'A')); maxlen = max(maxlen, findLen(A, n, k, i+'a')); } return maxlen;} // Driver codeint main(){ int n = 5, k = 2; string A = \"ABABA\"; cout << \"Maximum length = \" << answer(A, n, k) << endl; n = 6, k = 4; string B = \"HHHHHH\"; cout << \"Maximum length = \" << answer(B, n, k) << endl; return 0;}", "e": 3738, "s": 2255, "text": null }, { "code": "// Java program to find maximum length equal// character string with k changes public class GFG{ // method to find the maximum length of // substring having character ch static int findLen(String A, int n, int k, char ch) { int maxlen = 1; int cnt = 0; int l = 0, r = 0; // traverse the whole string while (r < n) { /* if character is not same as ch increase count */ if (A.charAt(r) != ch) ++cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while (cnt > k) { if (A.charAt(l) != ch) --cnt; ++l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ maxlen = Math.max(maxlen, r - l + 1); ++r; } return maxlen; } // method which returns maximum length of substring static int answer(String A, int n, int k) { int maxlen = 1; for (int i = 0; i < 26; ++i) { maxlen = Math.max(maxlen, findLen(A, n, k, (char) (i+'A'))); maxlen = Math.max(maxlen, findLen(A, n, k, (char) (i+'a'))); } return maxlen; } // Driver Method public static void main(String[] args) { int n = 5, k = 2; String A = \"ABABA\"; System.out.println(\"Maximum length = \" + answer(A, n, k)); n = 6; k = 4; String B = \"HHHHHH\"; System.out.println(\"Maximum length = \" + answer(B, n, k)); }}", "e": 5513, "s": 3738, "text": null }, { "code": "# Python3 program to find maximum length# equal character string with k changes # function to find the maximum length of# substring having character chdef findLen(A, n, k, ch): maxlen = 1 cnt = 0 l = 0 r = 0 # traverse the whole string while r < n: # if character is not same as ch # increase count if A[r] != ch: cnt += 1 # While count > k traverse the string # again until count becomes less than k # and decrease the count when characters # are not same while cnt > k: if A[l] != ch: cnt -= 1 l += 1 # length of substring will be rightIndex - # leftIndex + 1. Compare this with the # maximum length and return maximum length maxlen = max(maxlen, r - l + 1) r += 1 return maxlen # function which returns# maximum length of substringdef answer(A, n, k): maxlen = 1 for i in range(26): maxlen = max(maxlen, findLen(A, n, k, chr(i + ord('A')))) maxlen = max(maxlen, findLen(A, n, k, chr(i + ord('a')))) return maxlen # Driver Codeif __name__ == \"__main__\": n = 5 k = 2 A = \"ABABA\" print(\"Maximum length =\", answer(A, n, k)) n = 6 k = 4 B = \"HHHHHH\" print(\"Maximum length =\", answer(B, n, k)) # This code is contributed by# sanjeev2552", "e": 6941, "s": 5513, "text": null }, { "code": "// C# program to find maximum length equal// character string with k changesusing System; class GFG{ // method to find the maximum length of // substring having character ch public static int findLen(string A, int n, int k, char ch) { int maxlen = 1; int cnt = 0; int l = 0, r = 0; // traverse the whole string while (r < n) { // if character is // not same as ch // increase count if (A[r] != ch) { ++cnt; } // While count > k traverse // the string again until // count becomes less than // k and decrease the // count when characters // are not same while (cnt > k) { if (A[l] != ch) { --cnt; } ++l; } // length of substring // will be rightIndex - // leftIndex + 1. // Compare this with the maximum // length and return maximum length maxlen = Math.Max(maxlen, r - l + 1); ++r; } return maxlen; } // method which returns // maximum length of substring public static int answer(string A, int n, int k) { int maxlen = 1; for (int i = 0; i < 26; ++i) { maxlen = Math.Max(maxlen, findLen(A, n, k, (char)(i + 'A'))); maxlen = Math.Max(maxlen, findLen(A, n, k, (char)(i + 'a'))); } return maxlen; } // Driver Methodpublic static void Main(string[] args){ int n = 5, k = 2; string A = \"ABABA\"; Console.WriteLine(\"Maximum length = \" + answer(A, n, k)); n = 6; k = 4; string B = \"HHHHHH\"; Console.WriteLine(\"Maximum length = \" + answer(B, n, k));}} // This code is contributed by Shrikant13", "e": 8951, "s": 6941, "text": null }, { "code": "<?php// PHP program to find maximum length equal// character string with k changes // function to find the maximum length// of substring having character chfunction findLen($A, $n, $k, $ch){ $maxlen = 1; $cnt = 0; $l = 0; $r = 0; // traverse the whole string while ($r < $n) { /* if character is not same as ch increase count */ if ($A[$r] != $ch) ++$cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while ($cnt > $k) { if ($A[$l] != $ch) --$cnt; ++$l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ $maxlen = max($maxlen, $r - $l + 1); ++$r; } return $maxlen;} // function which returns maximum// length of substringfunction answer($A, $n, $k){ $maxlen = 1; for ($i = 0; $i < 26; ++$i) { $maxlen = max($maxlen, findLen($A, $n, $k, $i + 'A')); $maxlen = max($maxlen, findLen($A, $n, $k, $i + 'a')); } return $maxlen;} // Driver code$n = 5; $k = 2; $A = \"ABABA\";echo \"Maximum length = \" . answer($A, $n, $k) . \"\\n\"; $n = 6; $k = 4; $B = \"HHHHHH\";echo \"Maximum length = \" . answer($B, $n, $k) . \"\\n\"; // This code is contributed by ita_c?>", "e": 10415, "s": 8951, "text": null }, { "code": "<script>// Javascript program to find maximum length equal// character string with k changes // method to find the maximum length of // substring having character ch function findLen(A,n,k,ch) { let maxlen = 1; let cnt = 0; let l = 0, r = 0; // traverse the whole string while (r < n) { /* if character is not same as ch increase count */ if (A[r] != ch) ++cnt; /* While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same */ while (cnt > k) { if (A[l] != ch) --cnt; ++l; } /* length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length */ maxlen = Math.max(maxlen, r - l + 1); ++r; } return maxlen; } // method which returns maximum length of substring function answer(A,n,k) { let maxlen = 1; for (let i = 0; i < 26; ++i) { maxlen = Math.max(maxlen, findLen(A, n, k, String.fromCharCode(i+'A'.charCodeAt(0)))); maxlen = Math.max(maxlen, findLen(A, n, k, String.fromCharCode (i+'a'.charCodeAt(0)))); } return maxlen; } // Driver Method let n = 5, k = 2; let A = \"ABABA\"; document.write(\"Maximum length = \" + answer(A, n, k)+\"<br>\"); n = 6; k = 4; let B = \"HHHHHH\"; document.write(\"Maximum length = \" + answer(B, n, k)); //This code is contributed by rag2127 </script>", "e": 12169, "s": 10415, "text": null }, { "code": null, "e": 12179, "s": 12169, "text": "Output: " }, { "code": null, "e": 12217, "s": 12179, "text": "Maximum length = 5\nMaximum length = 6" }, { "code": null, "e": 12239, "s": 12217, "text": "Time Complexity: O(n)" }, { "code": null, "e": 12682, "s": 12239, "text": "Auxiliary Space: O(1)This article is contributed by Niteesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 12694, "s": 12682, "text": "shrikanth13" }, { "code": null, "e": 12700, "s": 12694, "text": "ukasp" }, { "code": null, "e": 12712, "s": 12700, "text": "sanjeev2552" }, { "code": null, "e": 12720, "s": 12712, "text": "rag2127" }, { "code": null, "e": 12735, "s": 12720, "text": "shivamanandrj9" }, { "code": null, "e": 12740, "s": 12735, "text": "Misc" }, { "code": null, "e": 12748, "s": 12740, "text": "Strings" }, { "code": null, "e": 12753, "s": 12748, "text": "Misc" }, { "code": null, "e": 12761, "s": 12753, "text": "Strings" }, { "code": null, "e": 12766, "s": 12761, "text": "Misc" }, { "code": null, "e": 12864, "s": 12766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12898, "s": 12864, "text": "How to write Regular Expressions?" }, { "code": null, "e": 12915, "s": 12898, "text": "Association Rule" }, { "code": null, "e": 12945, "s": 12915, "text": "OOPs | Object Oriented Design" }, { "code": null, "e": 12964, "s": 12945, "text": "std::unique in C++" }, { "code": null, "e": 13005, "s": 12964, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 13051, "s": 13005, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 13076, "s": 13051, "text": "Reverse a string in Java" }, { "code": null, "e": 13136, "s": 13076, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 13151, "s": 13136, "text": "C++ Data Types" } ]
numpy.var() in Python
03 Dec, 2018 numpy.var(arr, axis = None) : Compute the variance of the given data (array elements) along the specified axis(if any). Example : x = 1 1 1 1 1Standard Deviation = 0 . Variance = 0 y = 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 Step 1 : Mean of distribution 4 = 7Step 2 : Summation of (x – x.mean())**2 = 178Step 3 : Finding Mean = 178 /20 = 8.9This Result is Variance. Parameters : arr : [array_like] input array.axis : [int or tuples of int] axis along which we want to calculate the variance. Otherwise, it will consider arr to be flattened (works on all the axis). axis = 0 means variance along the column and axis = 1 means variance along the row.out : [ndarray, optional] Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional] Type we desire while computing variance. Results : Variance of the array (a scalar value if axis is none) or array with variance values along specified axis. Code #1: # Python Program illustrating # numpy.var() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print("arr : ", arr) print("var of arr : ", np.var(arr)) print("\nvar of arr : ", np.var(arr, dtype = np.float32)) print("\nvar of arr : ", np.var(arr, dtype = np.float64)) Output : arr : [20, 2, 7, 1, 34] var of arr : 158.16 var of arr : 158.16 var of arr : 158.16 Code #2: # Python Program illustrating # numpy.var() method import numpy as np # 2D array arr = [[2, 2, 2, 2, 2], [15, 6, 27, 8, 2], [23, 2, 54, 1, 2, ], [11, 44, 34, 7, 2]] # var of the flattened array print("\nvar of arr, axis = None : ", np.var(arr)) # var along the axis = 0 print("\nvar of arr, axis = 0 : ", np.var(arr, axis = 0)) # var along the axis = 1 print("\nvar of arr, axis = 1 : ", np.var(arr, axis = 1)) Output : var of arr, axis = None : 236.14000000000004 var of arr, axis = 0 : [ 57.1875 312.75 345.6875 9.25 0. ] var of arr, axis = 1 : [ 0. 77.04 421.84 269.04] Python numpy-Statistics Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2018" }, { "code": null, "e": 148, "s": 28, "text": "numpy.var(arr, axis = None) : Compute the variance of the given data (array elements) along the specified axis(if any)." }, { "code": null, "e": 158, "s": 148, "text": "Example :" }, { "code": null, "e": 209, "s": 158, "text": "x = 1 1 1 1 1Standard Deviation = 0 . Variance = 0" }, { "code": null, "e": 276, "s": 209, "text": "y = 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4" }, { "code": null, "e": 418, "s": 276, "text": "Step 1 : Mean of distribution 4 = 7Step 2 : Summation of (x – x.mean())**2 = 178Step 3 : Finding Mean = 178 /20 = 8.9This Result is Variance." }, { "code": null, "e": 431, "s": 418, "text": "Parameters :" }, { "code": null, "e": 910, "s": 431, "text": "arr : [array_like] input array.axis : [int or tuples of int] axis along which we want to calculate the variance. Otherwise, it will consider arr to be flattened (works on all the axis). axis = 0 means variance along the column and axis = 1 means variance along the row.out : [ndarray, optional] Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional] Type we desire while computing variance." }, { "code": null, "e": 1027, "s": 910, "text": "Results : Variance of the array (a scalar value if axis is none) or array with variance values along specified axis." }, { "code": null, "e": 1036, "s": 1027, "text": "Code #1:" }, { "code": "# Python Program illustrating # numpy.var() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print(\"arr : \", arr) print(\"var of arr : \", np.var(arr)) print(\"\\nvar of arr : \", np.var(arr, dtype = np.float32)) print(\"\\nvar of arr : \", np.var(arr, dtype = np.float64)) ", "e": 1325, "s": 1036, "text": null }, { "code": null, "e": 1334, "s": 1325, "text": "Output :" }, { "code": null, "e": 1424, "s": 1334, "text": "arr : [20, 2, 7, 1, 34]\nvar of arr : 158.16\n\nvar of arr : 158.16\n\nvar of arr : 158.16" }, { "code": null, "e": 1434, "s": 1424, "text": " Code #2:" }, { "code": "# Python Program illustrating # numpy.var() method import numpy as np # 2D array arr = [[2, 2, 2, 2, 2], [15, 6, 27, 8, 2], [23, 2, 54, 1, 2, ], [11, 44, 34, 7, 2]] # var of the flattened array print(\"\\nvar of arr, axis = None : \", np.var(arr)) # var along the axis = 0 print(\"\\nvar of arr, axis = 0 : \", np.var(arr, axis = 0)) # var along the axis = 1 print(\"\\nvar of arr, axis = 1 : \", np.var(arr, axis = 1)) ", "e": 1880, "s": 1434, "text": null }, { "code": null, "e": 1889, "s": 1880, "text": "Output :" }, { "code": null, "e": 2062, "s": 1889, "text": "var of arr, axis = None : 236.14000000000004\n\nvar of arr, axis = 0 : [ 57.1875 312.75 345.6875 9.25 0. ]\n\nvar of arr, axis = 1 : [ 0. 77.04 421.84 269.04]" }, { "code": null, "e": 2096, "s": 2062, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 2109, "s": 2096, "text": "Python-numpy" }, { "code": null, "e": 2116, "s": 2109, "text": "Python" } ]
JavaScript Array includes() Method
08 Jul, 2020 Below is the example of the Array includes() method. Example:<script> var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; a = name.includes('gfg') // Printing result of includes() document.write(a);</script> <script> var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; a = name.includes('gfg') // Printing result of includes() document.write(a);</script> Output:true true The array.includes() method is used to know either a particular element is present in the array or not and accordingly, it returns true or false i.e, if the element is present, then it returns true otherwise false. Syntax: array.includes(searchElement, start) Parameter: This method accepts two parameters as mentioned above and described below: searchElement: This parameter holds the element which will be searched. start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0. Return Value: It returns a Boolean value i.e, either True or False. Below examples illustrate the Array includes() method in JavaScript: Example 1: In this example the method will searched for the element 2 in that array.Input : [1, 2, 3, 4, 5].includes(2); Output: true Input : [1, 2, 3, 4, 5].includes(2); Output: true Example 2: In this example the method will searched for the element 9 in that array.Input : [1, 2, 3, 4, 5].includes(9); Output: false Input : [1, 2, 3, 4, 5].includes(9); Output: false Code for the above method is provided below: Program 1: <script> // Taking input as an array A // having some elements. var A = [ 1, 2, 3, 4, 5 ]; // includes() method is called to // test whether the searching element // is present in given array or not. a = A.includes(2) // Printing result of includes(). document.write(a);</script> Output: true Program 2: <script> // Taking input as an array A // having some elements. var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; // includes() method is called to // test whether the searching element // is present in given array or not. a = name.includes('cat') // Printing result of includes() document.write(a);</script> Output: false Supported Browsers: The browsers supported by JavaScript Array includes() method are listed below: Google Chrome 47.0 Microsoft Edge 14.0 Mozilla Firefox 43.0 Safari 9.0 Opera 34.0 nidhi_biet Akanksha_Rai javascript-array JavaScript-Methods JavaScript 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 How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript? How do you run JavaScript script through the Terminal? JavaScript | console.log() with Examples
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jul, 2020" }, { "code": null, "e": 106, "s": 53, "text": "Below is the example of the Array includes() method." }, { "code": null, "e": 273, "s": 106, "text": "Example:<script> var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; a = name.includes('gfg') // Printing result of includes() document.write(a);</script>" }, { "code": "<script> var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; a = name.includes('gfg') // Printing result of includes() document.write(a);</script>", "e": 432, "s": 273, "text": null }, { "code": null, "e": 444, "s": 432, "text": "Output:true" }, { "code": null, "e": 449, "s": 444, "text": "true" }, { "code": null, "e": 664, "s": 449, "text": "The array.includes() method is used to know either a particular element is present in the array or not and accordingly, it returns true or false i.e, if the element is present, then it returns true otherwise false." }, { "code": null, "e": 672, "s": 664, "text": "Syntax:" }, { "code": null, "e": 709, "s": 672, "text": "array.includes(searchElement, start)" }, { "code": null, "e": 795, "s": 709, "text": "Parameter: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 867, "s": 795, "text": "searchElement: This parameter holds the element which will be searched." }, { "code": null, "e": 997, "s": 867, "text": "start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0." }, { "code": null, "e": 1065, "s": 997, "text": "Return Value: It returns a Boolean value i.e, either True or False." }, { "code": null, "e": 1134, "s": 1065, "text": "Below examples illustrate the Array includes() method in JavaScript:" }, { "code": null, "e": 1268, "s": 1134, "text": "Example 1: In this example the method will searched for the element 2 in that array.Input : [1, 2, 3, 4, 5].includes(2);\nOutput: true" }, { "code": null, "e": 1318, "s": 1268, "text": "Input : [1, 2, 3, 4, 5].includes(2);\nOutput: true" }, { "code": null, "e": 1453, "s": 1318, "text": "Example 2: In this example the method will searched for the element 9 in that array.Input : [1, 2, 3, 4, 5].includes(9);\nOutput: false" }, { "code": null, "e": 1504, "s": 1453, "text": "Input : [1, 2, 3, 4, 5].includes(9);\nOutput: false" }, { "code": null, "e": 1549, "s": 1504, "text": "Code for the above method is provided below:" }, { "code": null, "e": 1560, "s": 1549, "text": "Program 1:" }, { "code": "<script> // Taking input as an array A // having some elements. var A = [ 1, 2, 3, 4, 5 ]; // includes() method is called to // test whether the searching element // is present in given array or not. a = A.includes(2) // Printing result of includes(). document.write(a);</script>", "e": 1873, "s": 1560, "text": null }, { "code": null, "e": 1881, "s": 1873, "text": "Output:" }, { "code": null, "e": 1886, "s": 1881, "text": "true" }, { "code": null, "e": 1897, "s": 1886, "text": "Program 2:" }, { "code": "<script> // Taking input as an array A // having some elements. var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; // includes() method is called to // test whether the searching element // is present in given array or not. a = name.includes('cat') // Printing result of includes() document.write(a);</script>", "e": 2235, "s": 1897, "text": null }, { "code": null, "e": 2243, "s": 2235, "text": "Output:" }, { "code": null, "e": 2249, "s": 2243, "text": "false" }, { "code": null, "e": 2348, "s": 2249, "text": "Supported Browsers: The browsers supported by JavaScript Array includes() method are listed below:" }, { "code": null, "e": 2367, "s": 2348, "text": "Google Chrome 47.0" }, { "code": null, "e": 2387, "s": 2367, "text": "Microsoft Edge 14.0" }, { "code": null, "e": 2408, "s": 2387, "text": "Mozilla Firefox 43.0" }, { "code": null, "e": 2419, "s": 2408, "text": "Safari 9.0" }, { "code": null, "e": 2430, "s": 2419, "text": "Opera 34.0" }, { "code": null, "e": 2441, "s": 2430, "text": "nidhi_biet" }, { "code": null, "e": 2454, "s": 2441, "text": "Akanksha_Rai" }, { "code": null, "e": 2471, "s": 2454, "text": "javascript-array" }, { "code": null, "e": 2490, "s": 2471, "text": "JavaScript-Methods" }, { "code": null, "e": 2501, "s": 2490, "text": "JavaScript" }, { "code": null, "e": 2599, "s": 2501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2660, "s": 2599, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2732, "s": 2660, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2772, "s": 2732, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2824, "s": 2772, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2865, "s": 2824, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2911, "s": 2865, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 2953, "s": 2911, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3007, "s": 2953, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 3062, "s": 3007, "text": "How do you run JavaScript script through the Terminal?" } ]
Groovy - File I/O
Groovy provides a number of helper methods when working with I/O. Groovy provides easier classes to provide the following functionalities for files. Reading files Writing to files Traversing file trees Reading and writing data objects to files In addition to this, you can always use the normal Java classes listed below for File I/O operations. java.io.File java.io.InputStream java.io.OutputStream java.io.Reader java.io.Writer The following example will output all the lines of a text file in Groovy. The method eachLine is in-built in the File class in Groovy for the purpose of ensuring that each line of the text file is read. import java.io.File class Example { static void main(String[] args) { new File("E:/Example.txt").eachLine { line -> println "line : $line"; } } } The File class is used to instantiate a new object which takes the file name as the parameter. It then takes the function of eachLine, puts it to a variable called line and prints it accordingly. If the file contains the following lines, they will be printed. line : Example1 line : Example2 If you want to get the entire contents of the file as a string, you can use the text property of the file class. The following example shows how this can be done. class Example { static void main(String[] args) { File file = new File("E:/Example.txt") println file.text } } If the file contains the following lines, they will be printed. line : Example1 line : Example2 If you want to write to files, you need to use the writer class to output text to a file. The following example shows how this can be done. import java.io.File class Example { static void main(String[] args) { new File('E:/','Example.txt').withWriter('utf-8') { writer -> writer.writeLine 'Hello World' } } } If you open the file Example.txt, you will see the words “Hello World” printed to the file. If you want to get the size of the file one can use the length property of the file class to get the size of the file. The following example shows how this can be done. class Example { static void main(String[] args) { File file = new File("E:/Example.txt") println "The file ${file.absolutePath} has ${file.length()} bytes" } } The above code would show the size of the file in bytes. If you want to see if a path is a file or a directory, one can use the isFile and isDirectory option of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { def file = new File('E:/') println "File? ${file.isFile()}" println "Directory? ${file.isDirectory()}" } } The above code would show the following output − File? false Directory? True If you want to create a new directory you can use the mkdir function of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { def file = new File('E:/Directory') file.mkdir() } } The directory E:\Directory will be created if it does not exist. If you want to delete a file you can use the delete function of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { def file = new File('E:/Example.txt') file.delete() } } The file will be deleted if it exists. Groovy also provides the functionality to copy the contents from one file to another. The following example shows how this can be done. class Example { static void main(String[] args) { def src = new File("E:/Example.txt") def dst = new File("E:/Example1.txt") dst << src.text } } The file Example1.txt will be created and all of the contents of the file Example.txt will be copied to this file. Groovy also provides the functionality to list the drives and files in a drive. The following example shows how the drives on a machine can be displayed by using the listRoots function of the File class. class Example { static void main(String[] args) { def rootFiles = new File("test").listRoots() rootFiles.each { file -> println file.absolutePath } } } Depending on the drives available on your machine, the output could vary. On a standard machine the output would be similar to the following one − C:\ D:\ The following example shows how to list the files in a particular directory by using the eachFile function of the File class. class Example { static void main(String[] args) { new File("E:/Temp").eachFile() { file->println file.getAbsolutePath() } } } The output would display all of the files in the directory E:\Temp If you want to recursively display all of files in a directory and its subdirectories, then you would use the eachFileRecurse function of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { new File("E:/temp").eachFileRecurse() { file -> println file.getAbsolutePath() } } } The output would display all of the files in the directory E:\Temp and in its subdirectories if they exist.
[ { "code": null, "e": 2521, "s": 2372, "text": "Groovy provides a number of helper methods when working with I/O. Groovy provides easier classes to provide the following functionalities for files." }, { "code": null, "e": 2535, "s": 2521, "text": "Reading files" }, { "code": null, "e": 2552, "s": 2535, "text": "Writing to files" }, { "code": null, "e": 2574, "s": 2552, "text": "Traversing file trees" }, { "code": null, "e": 2616, "s": 2574, "text": "Reading and writing data objects to files" }, { "code": null, "e": 2718, "s": 2616, "text": "In addition to this, you can always use the normal Java classes listed below for File I/O operations." }, { "code": null, "e": 2731, "s": 2718, "text": "java.io.File" }, { "code": null, "e": 2751, "s": 2731, "text": "java.io.InputStream" }, { "code": null, "e": 2772, "s": 2751, "text": "java.io.OutputStream" }, { "code": null, "e": 2787, "s": 2772, "text": "java.io.Reader" }, { "code": null, "e": 2802, "s": 2787, "text": "java.io.Writer" }, { "code": null, "e": 3005, "s": 2802, "text": "The following example will output all the lines of a text file in Groovy. The method eachLine is in-built in the File class in Groovy for the purpose of ensuring that each line of the text file is read." }, { "code": null, "e": 3186, "s": 3005, "text": "import java.io.File \nclass Example { \n static void main(String[] args) { \n new File(\"E:/Example.txt\").eachLine { \n line -> println \"line : $line\"; \n } \n } \n}" }, { "code": null, "e": 3382, "s": 3186, "text": "The File class is used to instantiate a new object which takes the file name as the parameter. It then takes the function of eachLine, puts it to a variable called line and prints it accordingly." }, { "code": null, "e": 3446, "s": 3382, "text": "If the file contains the following lines, they will be printed." }, { "code": null, "e": 3479, "s": 3446, "text": "line : Example1\nline : Example2\n" }, { "code": null, "e": 3642, "s": 3479, "text": "If you want to get the entire contents of the file as a string, you can use the text property of the file class. The following example shows how this can be done." }, { "code": null, "e": 3776, "s": 3642, "text": "class Example { \n static void main(String[] args) { \n File file = new File(\"E:/Example.txt\") \n println file.text \n } \n}" }, { "code": null, "e": 3840, "s": 3776, "text": "If the file contains the following lines, they will be printed." }, { "code": null, "e": 3874, "s": 3840, "text": "line : Example1 \nline : Example2\n" }, { "code": null, "e": 4014, "s": 3874, "text": "If you want to write to files, you need to use the writer class to output text to a file. The following example shows how this can be done." }, { "code": null, "e": 4218, "s": 4014, "text": "import java.io.File \nclass Example { \n static void main(String[] args) { \n new File('E:/','Example.txt').withWriter('utf-8') { \n writer -> writer.writeLine 'Hello World' \n } \n } \n}" }, { "code": null, "e": 4310, "s": 4218, "text": "If you open the file Example.txt, you will see the words “Hello World” printed to the file." }, { "code": null, "e": 4479, "s": 4310, "text": "If you want to get the size of the file one can use the length property of the file class to get the size of the file. The following example shows how this can be done." }, { "code": null, "e": 4658, "s": 4479, "text": "class Example {\n static void main(String[] args) {\n File file = new File(\"E:/Example.txt\")\n println \"The file ${file.absolutePath} has ${file.length()} bytes\"\n } \n}" }, { "code": null, "e": 4715, "s": 4658, "text": "The above code would show the size of the file in bytes." }, { "code": null, "e": 4885, "s": 4715, "text": "If you want to see if a path is a file or a directory, one can use the isFile and isDirectory option of the File class. The following example shows how this can be done." }, { "code": null, "e": 5072, "s": 4885, "text": "class Example { \n static void main(String[] args) { \n def file = new File('E:/') \n println \"File? ${file.isFile()}\" \n println \"Directory? ${file.isDirectory()}\" \n } \n}" }, { "code": null, "e": 5121, "s": 5072, "text": "The above code would show the following output −" }, { "code": null, "e": 5151, "s": 5121, "text": "File? false \nDirectory? True\n" }, { "code": null, "e": 5289, "s": 5151, "text": "If you want to create a new directory you can use the mkdir function of the File class. The following example shows how this can be done." }, { "code": null, "e": 5411, "s": 5289, "text": "class Example {\n static void main(String[] args) {\n def file = new File('E:/Directory')\n file.mkdir()\n } \n}" }, { "code": null, "e": 5476, "s": 5411, "text": "The directory E:\\Directory will be created if it does not exist." }, { "code": null, "e": 5606, "s": 5476, "text": "If you want to delete a file you can use the delete function of the File class. The following example shows how this can be done." }, { "code": null, "e": 5731, "s": 5606, "text": "class Example {\n static void main(String[] args) {\n def file = new File('E:/Example.txt')\n file.delete()\n } \n}" }, { "code": null, "e": 5770, "s": 5731, "text": "The file will be deleted if it exists." }, { "code": null, "e": 5906, "s": 5770, "text": "Groovy also provides the functionality to copy the contents from one file to another. The following example shows how this can be done." }, { "code": null, "e": 6076, "s": 5906, "text": "class Example {\n static void main(String[] args) {\n def src = new File(\"E:/Example.txt\")\n def dst = new File(\"E:/Example1.txt\")\n dst << src.text\n } \n}" }, { "code": null, "e": 6191, "s": 6076, "text": "The file Example1.txt will be created and all of the contents of the file Example.txt will be copied to this file." }, { "code": null, "e": 6271, "s": 6191, "text": "Groovy also provides the functionality to list the drives and files in a drive." }, { "code": null, "e": 6395, "s": 6271, "text": "The following example shows how the drives on a machine can be displayed by using the listRoots function of the File class." }, { "code": null, "e": 6585, "s": 6395, "text": "class Example { \n static void main(String[] args) { \n def rootFiles = new File(\"test\").listRoots() \n rootFiles.each { \n file -> println file.absolutePath \n }\n }\n}" }, { "code": null, "e": 6732, "s": 6585, "text": "Depending on the drives available on your machine, the output could vary. On a standard machine the output would be similar to the following one −" }, { "code": null, "e": 6742, "s": 6732, "text": "C:\\ \nD:\\\n" }, { "code": null, "e": 6868, "s": 6742, "text": "The following example shows how to list the files in a particular directory by using the eachFile function of the File class." }, { "code": null, "e": 7024, "s": 6868, "text": "class Example {\n static void main(String[] args) {\n new File(\"E:/Temp\").eachFile() { \n file->println file.getAbsolutePath()\n }\n } \n}" }, { "code": null, "e": 7091, "s": 7024, "text": "The output would display all of the files in the directory E:\\Temp" }, { "code": null, "e": 7295, "s": 7091, "text": "If you want to recursively display all of files in a directory and its subdirectories, then you would use the eachFileRecurse function of the File class. The following example shows how this can be done." }, { "code": null, "e": 7459, "s": 7295, "text": "class Example { \n static void main(String[] args) {\n new File(\"E:/temp\").eachFileRecurse() {\n file -> println file.getAbsolutePath()\n }\n }\n} " } ]
How to set up and Run CUDA Operations in Pytorch ?
18 Jul, 2021 CUDA(or Computer Unified Device Architecture) is a proprietary parallel computing platform and programming model from NVIDIA. Using the CUDA SDK, developers can utilize their NVIDIA GPUs(Graphics Processing Units), thus enabling them to bring in the power of GPU-based parallel processing instead of the usual CPU-based sequential processing in their usual programming workflow. With deep learning on the rise in recent years, it’s seen that various operations involved in model training, like matrix multiplication, inversion, etc., can be parallelized to a great extent for better learning performance and faster training cycles. Thus, many deep learning libraries like Pytorch enable their users to take advantage of their GPUs using a set of interfaces and utility functions. This article will cover setting up a CUDA environment in any system containing CUDA-enabled GPU(s) and a brief introduction to the various CUDA operations available in the Pytorch library using Python. First, you should ensure that their GPU is CUDA enabled or not by checking their system’s GPU through the official Nvidia CUDA compatibility list. Pytorch makes the CUDA installation process very simple by providing a nice user-friendly interface that lets you choose your operating system and other requirements, as given in the figure below. According to our computing machine, we’ll be installing according to the specifications given in the figure below. Refer to Pytorch’s official link and choose the specifications according to their computer specifications. We also suggest a complete restart of the system after installation to ensure the proper working of the toolkit. Screenshot from Pytorch’s installation page pip3 install torch==1.9.0+cu102 torchvision==0.10.0+cu102 torchaudio===0.9.0 -f https://download.pytorch.org/whl/torch_stable.html Once installed, we can use the torch.cuda interface to interact with CUDA using Pytorch. We’ll use the following functions: Syntax: torch.version.cuda(): Returns CUDA version of the currently installed packagestorch.cuda.is_available(): Returns True if CUDA is supported by your system, else Falsetorch.cuda.current_device(): Returns ID of current devicetorch.cuda.get_device_name(device_ID): Returns name of the CUDA device with ID = ‘device_ID’ torch.version.cuda(): Returns CUDA version of the currently installed packages torch.cuda.is_available(): Returns True if CUDA is supported by your system, else False torch.cuda.current_device(): Returns ID of current device torch.cuda.get_device_name(device_ID): Returns name of the CUDA device with ID = ‘device_ID’ Code: Python3 import torch print(f"Is CUDA supported by this system? {torch.cuda.is_available()}")print(f"CUDA version: {torch.version.cuda}") # Storing ID of current CUDA devicecuda_id = torch.cuda.current_device()print(f"ID of current CUDA device: {torch.cuda.current_device()}") print(f"Name of current CUDA device: {torch.cuda.get_device_name(cuda_id)}") Output: CUDA version For interacting Pytorch tensors through CUDA, we can use the following utility functions: Syntax: Tensor.device: Returns the device name of ‘Tensor’ Tensor.to(device_name): Returns new instance of ‘Tensor’ on the device specified by ‘device_name’: ‘cpu’ for CPU and ‘cuda’ for CUDA enabled GPU Tensor.cpu(): Transfers ‘Tensor’ to CPU from it’s current device To demonstrate the above functions, we’ll be creating a test tensor and do the following operations: Checking the current device of the tensor and applying a tensor operation(squaring), transferring the tensor to GPU and applying the same tensor operation(squaring) and comparing the results of the 2 devices. Code: Python3 import torch # Creating a test tensorx = torch.randint(1, 100, (100, 100)) # Checking the device name:# Should return 'cpu' by defaultprint(x.device) # Applying tensor operationres_cpu = x ** 2 # Transferring tensor to GPUx = x.to(torch.device('cuda')) # Checking the device name:# Should return 'cuda:0'print(x.device) # Applying same tensor operationres_gpu = x ** 2 # Checking the equality# of the two resultsassert torch.equal(res_cpu, res_gpu.cpu()) Output: cpu cuda : 0 A good Pytorch practice is to produce device-agnostic code because some systems might not have access to a GPU and have to rely on the CPU only or vice versa. Once that’s done the following function can be used to transfer any machine learning model onto the selected device Syntax: Model.to(device_name): Returns: New instance of Machine Learning ‘Model’ on the device specified by ‘device_name’: ‘cpu’ for CPU and ‘cuda’ for CUDA enabled GPU In this example, we are importing the pre-trained Resnet-18 model from the torchvision.models utility, the reader can use the same steps for transferring models to their selected device. Code: Python3 import torchimport torchvision.models as models # Making the code device-agnosticdevice = 'cuda' if torch.cuda.is_available() else 'cpu' # Instantiating a pre-trained modelmodel = models.resnet18(pretrained=True) # Transferring the model to a CUDA enabled GPUmodel = model.to(device) # Now the reader can continue the rest of the workflow# including training, cross validation, etc! Output: ML with CUDA Picked Python-PyTorch Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Information Retrieval? Introduction to Recurrent Neural Network Support Vector Machine Algorithm Sequential Covering Algorithm ML | Expectation-Maximization Algorithm Iterate over a list in Python How to iterate through Excel rows in Python? Read JSON file using Python Python map() function Rotate axis tick labels in Seaborn and Matplotlib
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jul, 2021" }, { "code": null, "e": 434, "s": 54, "text": "CUDA(or Computer Unified Device Architecture) is a proprietary parallel computing platform and programming model from NVIDIA. Using the CUDA SDK, developers can utilize their NVIDIA GPUs(Graphics Processing Units), thus enabling them to bring in the power of GPU-based parallel processing instead of the usual CPU-based sequential processing in their usual programming workflow. " }, { "code": null, "e": 1038, "s": 434, "text": "With deep learning on the rise in recent years, it’s seen that various operations involved in model training, like matrix multiplication, inversion, etc., can be parallelized to a great extent for better learning performance and faster training cycles. Thus, many deep learning libraries like Pytorch enable their users to take advantage of their GPUs using a set of interfaces and utility functions. This article will cover setting up a CUDA environment in any system containing CUDA-enabled GPU(s) and a brief introduction to the various CUDA operations available in the Pytorch library using Python. " }, { "code": null, "e": 1498, "s": 1038, "text": "First, you should ensure that their GPU is CUDA enabled or not by checking their system’s GPU through the official Nvidia CUDA compatibility list. Pytorch makes the CUDA installation process very simple by providing a nice user-friendly interface that lets you choose your operating system and other requirements, as given in the figure below. According to our computing machine, we’ll be installing according to the specifications given in the figure below. " }, { "code": null, "e": 1718, "s": 1498, "text": "Refer to Pytorch’s official link and choose the specifications according to their computer specifications. We also suggest a complete restart of the system after installation to ensure the proper working of the toolkit." }, { "code": null, "e": 1762, "s": 1718, "text": "Screenshot from Pytorch’s installation page" }, { "code": null, "e": 1893, "s": 1762, "text": "pip3 install torch==1.9.0+cu102 torchvision==0.10.0+cu102 torchaudio===0.9.0 -f https://download.pytorch.org/whl/torch_stable.html" }, { "code": null, "e": 2017, "s": 1893, "text": "Once installed, we can use the torch.cuda interface to interact with CUDA using Pytorch. We’ll use the following functions:" }, { "code": null, "e": 2025, "s": 2017, "text": "Syntax:" }, { "code": null, "e": 2340, "s": 2025, "text": "torch.version.cuda(): Returns CUDA version of the currently installed packagestorch.cuda.is_available(): Returns True if CUDA is supported by your system, else Falsetorch.cuda.current_device(): Returns ID of current devicetorch.cuda.get_device_name(device_ID): Returns name of the CUDA device with ID = ‘device_ID’" }, { "code": null, "e": 2419, "s": 2340, "text": "torch.version.cuda(): Returns CUDA version of the currently installed packages" }, { "code": null, "e": 2507, "s": 2419, "text": "torch.cuda.is_available(): Returns True if CUDA is supported by your system, else False" }, { "code": null, "e": 2565, "s": 2507, "text": "torch.cuda.current_device(): Returns ID of current device" }, { "code": null, "e": 2658, "s": 2565, "text": "torch.cuda.get_device_name(device_ID): Returns name of the CUDA device with ID = ‘device_ID’" }, { "code": null, "e": 2664, "s": 2658, "text": "Code:" }, { "code": null, "e": 2672, "s": 2664, "text": "Python3" }, { "code": "import torch print(f\"Is CUDA supported by this system? {torch.cuda.is_available()}\")print(f\"CUDA version: {torch.version.cuda}\") # Storing ID of current CUDA devicecuda_id = torch.cuda.current_device()print(f\"ID of current CUDA device: {torch.cuda.current_device()}\") print(f\"Name of current CUDA device: {torch.cuda.get_device_name(cuda_id)}\")", "e": 3042, "s": 2672, "text": null }, { "code": null, "e": 3050, "s": 3042, "text": "Output:" }, { "code": null, "e": 3063, "s": 3050, "text": "CUDA version" }, { "code": null, "e": 3153, "s": 3063, "text": "For interacting Pytorch tensors through CUDA, we can use the following utility functions:" }, { "code": null, "e": 3161, "s": 3153, "text": "Syntax:" }, { "code": null, "e": 3212, "s": 3161, "text": "Tensor.device: Returns the device name of ‘Tensor’" }, { "code": null, "e": 3358, "s": 3212, "text": "Tensor.to(device_name): Returns new instance of ‘Tensor’ on the device specified by ‘device_name’: ‘cpu’ for CPU and ‘cuda’ for CUDA enabled GPU" }, { "code": null, "e": 3423, "s": 3358, "text": "Tensor.cpu(): Transfers ‘Tensor’ to CPU from it’s current device" }, { "code": null, "e": 3524, "s": 3423, "text": "To demonstrate the above functions, we’ll be creating a test tensor and do the following operations:" }, { "code": null, "e": 3733, "s": 3524, "text": "Checking the current device of the tensor and applying a tensor operation(squaring), transferring the tensor to GPU and applying the same tensor operation(squaring) and comparing the results of the 2 devices." }, { "code": null, "e": 3739, "s": 3733, "text": "Code:" }, { "code": null, "e": 3747, "s": 3739, "text": "Python3" }, { "code": "import torch # Creating a test tensorx = torch.randint(1, 100, (100, 100)) # Checking the device name:# Should return 'cpu' by defaultprint(x.device) # Applying tensor operationres_cpu = x ** 2 # Transferring tensor to GPUx = x.to(torch.device('cuda')) # Checking the device name:# Should return 'cuda:0'print(x.device) # Applying same tensor operationres_gpu = x ** 2 # Checking the equality# of the two resultsassert torch.equal(res_cpu, res_gpu.cpu())", "e": 4209, "s": 3747, "text": null }, { "code": null, "e": 4217, "s": 4209, "text": "Output:" }, { "code": null, "e": 4230, "s": 4217, "text": "cpu\ncuda : 0" }, { "code": null, "e": 4505, "s": 4230, "text": "A good Pytorch practice is to produce device-agnostic code because some systems might not have access to a GPU and have to rely on the CPU only or vice versa. Once that’s done the following function can be used to transfer any machine learning model onto the selected device" }, { "code": null, "e": 4536, "s": 4505, "text": "Syntax: Model.to(device_name):" }, { "code": null, "e": 4675, "s": 4536, "text": "Returns: New instance of Machine Learning ‘Model’ on the device specified by ‘device_name’: ‘cpu’ for CPU and ‘cuda’ for CUDA enabled GPU" }, { "code": null, "e": 4862, "s": 4675, "text": "In this example, we are importing the pre-trained Resnet-18 model from the torchvision.models utility, the reader can use the same steps for transferring models to their selected device." }, { "code": null, "e": 4868, "s": 4862, "text": "Code:" }, { "code": null, "e": 4876, "s": 4868, "text": "Python3" }, { "code": "import torchimport torchvision.models as models # Making the code device-agnosticdevice = 'cuda' if torch.cuda.is_available() else 'cpu' # Instantiating a pre-trained modelmodel = models.resnet18(pretrained=True) # Transferring the model to a CUDA enabled GPUmodel = model.to(device) # Now the reader can continue the rest of the workflow# including training, cross validation, etc!", "e": 5263, "s": 4876, "text": null }, { "code": null, "e": 5271, "s": 5263, "text": "Output:" }, { "code": null, "e": 5284, "s": 5271, "text": "ML with CUDA" }, { "code": null, "e": 5291, "s": 5284, "text": "Picked" }, { "code": null, "e": 5306, "s": 5291, "text": "Python-PyTorch" }, { "code": null, "e": 5323, "s": 5306, "text": "Machine Learning" }, { "code": null, "e": 5330, "s": 5323, "text": "Python" }, { "code": null, "e": 5347, "s": 5330, "text": "Machine Learning" }, { "code": null, "e": 5445, "s": 5347, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5476, "s": 5445, "text": "What is Information Retrieval?" }, { "code": null, "e": 5517, "s": 5476, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 5550, "s": 5517, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 5580, "s": 5550, "text": "Sequential Covering Algorithm" }, { "code": null, "e": 5620, "s": 5580, "text": "ML | Expectation-Maximization Algorithm" }, { "code": null, "e": 5650, "s": 5620, "text": "Iterate over a list in Python" }, { "code": null, "e": 5695, "s": 5650, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 5723, "s": 5695, "text": "Read JSON file using Python" }, { "code": null, "e": 5745, "s": 5723, "text": "Python map() function" } ]
Sign Convention for Spherical Mirrors
07 Feb, 2022 While studying the reflection of light by spherical mirrors and the formation of images by spherical mirrors, a set of sign conventions are needed to learn that is required to measure the focal length, a distance of object or image from the mirror, and the magnification of the mirror. Before, understanding the concept of sign conventions for spherical mirrors first discuss some commonly used terms in a spherical mirror. 1. Aperture – The part of a spherical mirror that is exposed to all the light rays that incident on it is called the aperture of the spherical mirror. In other words, the diameter (XY) of the aperture of the concave and the convex mirror are shown in figure 1, known as its aperture. Figure 1 2. Centre of curvature – The centre of a hollow sphere of which the curved or spherical mirror forms a part is called the centre of curvature. It is denoted by C (as shown in Figures 2 and 3). 3. Radius of curvature – The radius of a hollow sphere of which the spherical mirror forms a part is called the radius of curvature. It is denoted by R. 4. Pole – The centre of the spherical surface is called its pole. It is denoted by P. 5. Principal axis – The line joining the centre of curvature (C) and pole (P) of a spherical mirror and extended on either side is called the principal axis. 6. Principal focus – A point on the principal axis of a spherical mirror where the rays of light parallel to the principal axis meet or appear to meet after reflection from the spherical mirror is called the principal focus. It is denoted by F. In case of a concave mirror, the rays of light parallel to the principal axis after reflection actually meet the principal axis at F as shown in figure 2. So, the principal focus of a concave mirror is real. In case of a convex mirror, the rays of light parallel to the principal axis after reflection appear to meet or diverge from the principal axis at F as shown in figure 3. So, the principal focus of a convex mirror is virtual. 7. Focal plane – A plane normal or perpendicular to the principal axis and passing through the principal focus (F) of a spherical mirror is called the focal plane of the spherical mirror. 8. Focal length – The distance between the pole (P) and principal focus (F) of a spherical mirror is called the focal length of the mirror. It is denoted by f. In the figure 2 & 3 the focal length of the mirror is represented by PF. Figure 2 Figure 3 The set of guidelines to set signs for image distance, object distance, focal length, etc for mathematical calculation during an image formation is called the Sign Convention. The sign conventions in case of the spherical mirrors are made in taking consideration that the objects are always placed on the left side of the mirror, such that the direction of incident light is from left to right. The sign conventions followed for any spherical mirror are given as: 1) All distances are measured from the pole of a spherical error. 2) Distances measured in the direction of incident light are taken as positive, while distances measured in a direction opposite to the direction of the incident light are taken as negative. 3) The upward distances perpendicular to the principal axis are taken as positive, while the downward distances perpendicular to the principal axis are taken as negative. For convenience, the object is assumed to be placed on the left side of a mirror. Hence, the distance of an object from the pole of a spherical mirror is taken as negative. Since the incident light always goes from left to right, all the distances measured from the pole (P) of mirror to the right side will be considered positive (because they will be in the same directions the incident light). On the other hand, all the distances measured from pole (P) of mirror to the left will be negative (because they are measured against the direction of incident light) According to the sign convention, the distances towards the left of the mirror are negative. Since as object is always placed to the left side of a mirror, therefore, the object distance (u) is always negative. The images formed by a concave mirror can be either behind the mirror (virtual) or in front of the mirror (real). So, the image distance () for a concave mirror can be either positive or negative depending on the position of the image. If the image is formed behind a concave mirror, the image distance (v) is positive but if the image is formed in front of the mirror , then the image distance will be negative. In a convex mirror, the image is always formed on the right-hand side (behind the mirror), so the image distance (o) for a convex mirror will be always positive. The focus of concave mirror is in front of the mirror on the left side, so the focal length of a concave mirror will be negative (and written with a minus sign, say, -10 cm). On the other hand, the focus of the convex mirror is behind the mirror on the right side, so the focal length (and written with a plus sign, say +20 cm or just 20 cm), a convex mirror is positive. The Focal Length and radius of curvature of a concave mirror are taken negative. Figure 4 -Concave Mirror The Focal Length and radius of curvature of a convex mirror are taken positive. FigureConvex Mirror The distance of the position of an object on the principal axis from the pole of a spherical mirror is known as object distance. It is denoted by u. The distance of the position of the image of an object on the principal axis from the pole of a spherical mirror is known as image distance. It is denoted by v. The relation between v and f of a spherical mirror is known as mirror formula. It is given by 1/u + 1/v =1/f or 1/object distance + 1/image distance = 1/ focal length Linear Magnification produced by a mirror is defined as the ratio of the size (or height) of the image to the size (or height) of the object. It is denoted by m. If h’ = Size (or height) of the image produced by the mirror and h = Size (or height) of the object. Then, linear magnification, m = h‘ / h or m= height of image/ height of object Linear magnification has no unit. Example 1: A concave mirror produces two times magnified real image of an object placed at 10 cm in front of it. Find the position of the image. Solution: Here, -10 cm (Sign convention) m=- 2 ( Image is real). But m =-v/u -2=-v/u v=-20 cm Thus, image of the object is at 20 cm from the pole of the mirror and in front of the mirror. Example 2: An object of 5 cm in size is placed at a distance of 20 cm from it concave minor of focal length 15 cm At what distance from the mirror, should a screen be placed to get the sharp image? Also calculate the size of the image. Solution: Given that, h=+5 cm f=- 15.0 cm (Sign convention) u=- 20 cm (Sign convention) Determination of the position of image. Using, 1/u + 1/v =1/f We get , 1/v = 1/f-1/u v=-60cm So the screen must be placed at a distance of 60 cm in front of the concave mirror. Determination of size of the image and its nature. Using, m= h’/h =-v/u h‘=-(v/u)h hi=-15cm Thus, the size of image -15cm, negative sign with h’ shows that the image is real and inverted. Example 3: An object 4 cm high is placed at a distance of 6 cm in front of c concave mirror of focal length 12 cm Find the position, nature and size of the image formed. Solution: Sound: It is produced in a material medium by a vibrating source when a material median vibrates it pushes air near it this is called compression (region of high pressure) and when the particle moves backwards it creates a region of low pressure known as rarefaction. due to this compression and rarefaction, sound waves travel. Sound waves required a median to travel material that can be the solid-liquid or the sound speed of sound is highest in solid. Sound waves are longitudinal mechanical waves. Sound waves can be divided into 3 categories: 1) Audible sounds: The frequency of audible sound is between 20hz-20khz the human ear can hear this sound. 2.INFRASONIC SOUNDS: these sound have a frequency of less than 20kz. Elephants and whales can hear this sound 3. Ultrasonic waves these have a frequency greater than 20khz we cannot detect these sounds built the creatures like dogs, cats bats and mosquitos can hear it. When a sound wave reaches our ear it is characterised by 3 factors: 1 pitch and frequency 2 loudness and intensity 3 quality Pitch : Pitch : It is the characteristic of sound which distinguishes a shrilled soundwave from a dull or flat sound. The higher the frequency the higher is the pitch and the lower the frequency lower is their pitch. Frequency is defined as the number of cycles per unit of time. 2.Loudness: It relates with the amplitude of the sound higher the amplitude higher is the loudness and lower the amplitude lower is the loudness.] The intensity of sound at any point is defined as the amount of energy passing normally per unit area helped around that point per unit time si unit of intensity are watt/m2. The intensity of sound at any point: a ) Inversely proportional to the square of the distance of a point from the source.] b) directly proportional to the square of the amplitude, sq of frequency and density of the medium. I1/I2 = A21/A2 2 Unit of loudness is bel the practical unit of loudness is decibel. 1db = 1/10 bel 3. Quality: Quality in that characteristic of sound distinguishes between sound produced by two sources having the same intensity and pitch. the quality of sound wave depends on factors like frequency and relative intensity of over tunes.zStep 1. Here size of object, 4 cm u=-6 cm (sign convention) f=-12cm (sign convention) Using, 1/u + 1/v =1/f We get, Using, -1/6 + 1/v =-1/12 ] v=12cm Image is formed at a distance of 12 cm behind the concave mirror as v is positive. Therefore , image is virtual. Using, m= h’/h =-v/u h’=(-12/-6)4 hi=8 cm Example 4: A convex mirror used in a bus has radius of curvature 3.5 m. If the driver of the bus locates a car at 10 m behind the bus, find the position, nature and size of the image of the car. Solution: Here, R = 3-5 m f = R 2 3-5 2 = 1.75m, u = – 100 m. Determination of the position of the car. Using, Using, 1/u + 1/v =1/f 1/v =1/f -1/u 1/v= 1/1.75 -1/(-10) v=1.5m Thus, the car appears to be at 1.5 m from the convex mirror and behind the mirror. Determination of the size and nature of the image Using, m= h’/h =-v/u m=-1.5/-10 m=0.15 Thus, the size of the image of the car is 0.15 times the actual size of the car. Since m is positive, so image of the car is virtual and erect (i.e., upright). ysachin2314 varshagumber28 Class 10 School Learning School Physics Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Internet Mobile Technologies - Definition, Types, Uses, Advantages Metals and Non-Metals - Definition, Properties, Uses and Applications CBSE Notes for Class 10 Physics Rusting of Iron - Explanation, Chemical Reaction, Prevention How to Align Text in HTML? Libraries in Python What are Different Output Devices? Generations of Computers - Computer Fundamentals Reading Rows from a CSV File in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Feb, 2022" }, { "code": null, "e": 340, "s": 54, "text": "While studying the reflection of light by spherical mirrors and the formation of images by spherical mirrors, a set of sign conventions are needed to learn that is required to measure the focal length, a distance of object or image from the mirror, and the magnification of the mirror." }, { "code": null, "e": 478, "s": 340, "text": "Before, understanding the concept of sign conventions for spherical mirrors first discuss some commonly used terms in a spherical mirror." }, { "code": null, "e": 764, "s": 478, "text": "1. Aperture – The part of a spherical mirror that is exposed to all the light rays that incident on it is called the aperture of the spherical mirror. In other words, the diameter (XY) of the aperture of the concave and the convex mirror are shown in figure 1, known as its aperture. " }, { "code": null, "e": 773, "s": 764, "text": "Figure 1" }, { "code": null, "e": 968, "s": 773, "text": "2. Centre of curvature – The centre of a hollow sphere of which the curved or spherical mirror forms a part is called the centre of curvature. It is denoted by C (as shown in Figures 2 and 3). " }, { "code": null, "e": 1123, "s": 968, "text": "3. Radius of curvature – The radius of a hollow sphere of which the spherical mirror forms a part is called the radius of curvature. It is denoted by R. " }, { "code": null, "e": 1211, "s": 1123, "text": "4. Pole – The centre of the spherical surface is called its pole. It is denoted by P. " }, { "code": null, "e": 1371, "s": 1211, "text": "5. Principal axis – The line joining the centre of curvature (C) and pole (P) of a spherical mirror and extended on either side is called the principal axis. " }, { "code": null, "e": 1619, "s": 1371, "text": "6. Principal focus – A point on the principal axis of a spherical mirror where the rays of light parallel to the principal axis meet or appear to meet after reflection from the spherical mirror is called the principal focus. It is denoted by F. " }, { "code": null, "e": 1827, "s": 1619, "text": "In case of a concave mirror, the rays of light parallel to the principal axis after reflection actually meet the principal axis at F as shown in figure 2. So, the principal focus of a concave mirror is real." }, { "code": null, "e": 2053, "s": 1827, "text": "In case of a convex mirror, the rays of light parallel to the principal axis after reflection appear to meet or diverge from the principal axis at F as shown in figure 3. So, the principal focus of a convex mirror is virtual." }, { "code": null, "e": 2242, "s": 2053, "text": "7. Focal plane – A plane normal or perpendicular to the principal axis and passing through the principal focus (F) of a spherical mirror is called the focal plane of the spherical mirror." }, { "code": null, "e": 2476, "s": 2242, "text": "8. Focal length – The distance between the pole (P) and principal focus (F) of a spherical mirror is called the focal length of the mirror. It is denoted by f. In the figure 2 & 3 the focal length of the mirror is represented by PF." }, { "code": null, "e": 2485, "s": 2476, "text": "Figure 2" }, { "code": null, "e": 2494, "s": 2485, "text": "Figure 3" }, { "code": null, "e": 2958, "s": 2494, "text": "The set of guidelines to set signs for image distance, object distance, focal length, etc for mathematical calculation during an image formation is called the Sign Convention. The sign conventions in case of the spherical mirrors are made in taking consideration that the objects are always placed on the left side of the mirror, such that the direction of incident light is from left to right. The sign conventions followed for any spherical mirror are given as:" }, { "code": null, "e": 3025, "s": 2958, "text": "1) All distances are measured from the pole of a spherical error. " }, { "code": null, "e": 3216, "s": 3025, "text": "2) Distances measured in the direction of incident light are taken as positive, while distances measured in a direction opposite to the direction of the incident light are taken as negative." }, { "code": null, "e": 3388, "s": 3216, "text": "3) The upward distances perpendicular to the principal axis are taken as positive, while the downward distances perpendicular to the principal axis are taken as negative. " }, { "code": null, "e": 3561, "s": 3388, "text": "For convenience, the object is assumed to be placed on the left side of a mirror. Hence, the distance of an object from the pole of a spherical mirror is taken as negative." }, { "code": null, "e": 3953, "s": 3561, "text": "Since the incident light always goes from left to right, all the distances measured from the pole (P) of mirror to the right side will be considered positive (because they will be in the same directions the incident light). On the other hand, all the distances measured from pole (P) of mirror to the left will be negative (because they are measured against the direction of incident light)" }, { "code": null, "e": 4164, "s": 3953, "text": "According to the sign convention, the distances towards the left of the mirror are negative. Since as object is always placed to the left side of a mirror, therefore, the object distance (u) is always negative." }, { "code": null, "e": 4400, "s": 4164, "text": "The images formed by a concave mirror can be either behind the mirror (virtual) or in front of the mirror (real). So, the image distance () for a concave mirror can be either positive or negative depending on the position of the image." }, { "code": null, "e": 4577, "s": 4400, "text": "If the image is formed behind a concave mirror, the image distance (v) is positive but if the image is formed in front of the mirror , then the image distance will be negative." }, { "code": null, "e": 4739, "s": 4577, "text": "In a convex mirror, the image is always formed on the right-hand side (behind the mirror), so the image distance (o) for a convex mirror will be always positive." }, { "code": null, "e": 4914, "s": 4739, "text": "The focus of concave mirror is in front of the mirror on the left side, so the focal length of a concave mirror will be negative (and written with a minus sign, say, -10 cm)." }, { "code": null, "e": 5111, "s": 4914, "text": "On the other hand, the focus of the convex mirror is behind the mirror on the right side, so the focal length (and written with a plus sign, say +20 cm or just 20 cm), a convex mirror is positive." }, { "code": null, "e": 5192, "s": 5111, "text": "The Focal Length and radius of curvature of a concave mirror are taken negative." }, { "code": null, "e": 5217, "s": 5192, "text": "Figure 4 -Concave Mirror" }, { "code": null, "e": 5297, "s": 5217, "text": "The Focal Length and radius of curvature of a convex mirror are taken positive." }, { "code": null, "e": 5317, "s": 5297, "text": "FigureConvex Mirror" }, { "code": null, "e": 5467, "s": 5317, "text": "The distance of the position of an object on the principal axis from the pole of a spherical mirror is known as object distance. It is denoted by u. " }, { "code": null, "e": 5629, "s": 5467, "text": "The distance of the position of the image of an object on the principal axis from the pole of a spherical mirror is known as image distance. It is denoted by v. " }, { "code": null, "e": 5709, "s": 5629, "text": "The relation between v and f of a spherical mirror is known as mirror formula. " }, { "code": null, "e": 5725, "s": 5709, "text": "It is given by " }, { "code": null, "e": 5740, "s": 5725, "text": "1/u + 1/v =1/f" }, { "code": null, "e": 5798, "s": 5740, "text": "or 1/object distance + 1/image distance = 1/ focal length" }, { "code": null, "e": 5960, "s": 5798, "text": "Linear Magnification produced by a mirror is defined as the ratio of the size (or height) of the image to the size (or height) of the object. It is denoted by m." }, { "code": null, "e": 6062, "s": 5960, "text": "If h’ = Size (or height) of the image produced by the mirror and h = Size (or height) of the object. " }, { "code": null, "e": 6094, "s": 6062, "text": "Then, linear magnification, " }, { "code": null, "e": 6112, "s": 6094, "text": " m = h‘ / h" }, { "code": null, "e": 6155, "s": 6112, "text": "or m= height of image/ height of object" }, { "code": null, "e": 6189, "s": 6155, "text": "Linear magnification has no unit." }, { "code": null, "e": 6334, "s": 6189, "text": "Example 1: A concave mirror produces two times magnified real image of an object placed at 10 cm in front of it. Find the position of the image." }, { "code": null, "e": 6346, "s": 6334, "text": "Solution: " }, { "code": null, "e": 6378, "s": 6346, "text": "Here, -10 cm (Sign convention) " }, { "code": null, "e": 6425, "s": 6378, "text": " m=- 2 ( Image is real). " }, { "code": null, "e": 6462, "s": 6425, "text": " But m =-v/u " }, { "code": null, "e": 6499, "s": 6462, "text": " -2=-v/u" }, { "code": null, "e": 6539, "s": 6499, "text": " v=-20 cm" }, { "code": null, "e": 6634, "s": 6539, "text": "Thus, image of the object is at 20 cm from the pole of the mirror and in front of the mirror. " }, { "code": null, "e": 6873, "s": 6636, "text": "Example 2: An object of 5 cm in size is placed at a distance of 20 cm from it concave minor of focal length 15 cm At what distance from the mirror, should a screen be placed to get the sharp image? Also calculate the size of the image. " }, { "code": null, "e": 6884, "s": 6873, "text": "Solution: " }, { "code": null, "e": 6898, "s": 6886, "text": "Given that," }, { "code": null, "e": 6907, "s": 6898, "text": "h=+5 cm " }, { "code": null, "e": 6967, "s": 6907, "text": "f=- 15.0 cm (Sign convention) " }, { "code": null, "e": 7026, "s": 6967, "text": "u=- 20 cm (Sign convention) " }, { "code": null, "e": 7067, "s": 7026, "text": "Determination of the position of image. " }, { "code": null, "e": 7075, "s": 7067, "text": "Using, " }, { "code": null, "e": 7091, "s": 7075, "text": "1/u + 1/v =1/f " }, { "code": null, "e": 7101, "s": 7091, "text": "We get , " }, { "code": null, "e": 7115, "s": 7101, "text": "1/v = 1/f-1/u" }, { "code": null, "e": 7127, "s": 7115, "text": " v=-60cm" }, { "code": null, "e": 7212, "s": 7127, "text": "So the screen must be placed at a distance of 60 cm in front of the concave mirror. " }, { "code": null, "e": 7263, "s": 7212, "text": "Determination of size of the image and its nature." }, { "code": null, "e": 7271, "s": 7263, "text": "Using, " }, { "code": null, "e": 7285, "s": 7271, "text": "m= h’/h =-v/u" }, { "code": null, "e": 7297, "s": 7285, "text": " h‘=-(v/u)h" }, { "code": null, "e": 7307, "s": 7297, "text": " hi=-15cm" }, { "code": null, "e": 7404, "s": 7307, "text": "Thus, the size of image -15cm, negative sign with h’ shows that the image is real and inverted. " }, { "code": null, "e": 7576, "s": 7406, "text": "Example 3: An object 4 cm high is placed at a distance of 6 cm in front of c concave mirror of focal length 12 cm Find the position, nature and size of the image formed." }, { "code": null, "e": 7588, "s": 7578, "text": "Solution:" }, { "code": null, "e": 8046, "s": 7590, "text": "Sound: It is produced in a material medium by a vibrating source when a material median vibrates it pushes air near it this is called compression (region of high pressure) and when the particle moves backwards it creates a region of low pressure known as rarefaction. due to this compression and rarefaction, sound waves travel. Sound waves required a median to travel material that can be the solid-liquid or the sound speed of sound is highest in solid." }, { "code": null, "e": 8093, "s": 8046, "text": "Sound waves are longitudinal mechanical waves." }, { "code": null, "e": 8139, "s": 8093, "text": "Sound waves can be divided into 3 categories:" }, { "code": null, "e": 8158, "s": 8139, "text": "1) Audible sounds:" }, { "code": null, "e": 8246, "s": 8158, "text": "The frequency of audible sound is between 20hz-20khz the human ear can hear this sound." }, { "code": null, "e": 8267, "s": 8246, "text": "2.INFRASONIC SOUNDS:" }, { "code": null, "e": 8356, "s": 8267, "text": "these sound have a frequency of less than 20kz. Elephants and whales can hear this sound" }, { "code": null, "e": 8376, "s": 8356, "text": "3. Ultrasonic waves" }, { "code": null, "e": 8516, "s": 8376, "text": "these have a frequency greater than 20khz we cannot detect these sounds built the creatures like dogs, cats bats and mosquitos can hear it." }, { "code": null, "e": 8584, "s": 8516, "text": "When a sound wave reaches our ear it is characterised by 3 factors:" }, { "code": null, "e": 8606, "s": 8584, "text": "1 pitch and frequency" }, { "code": null, "e": 8631, "s": 8606, "text": "2 loudness and intensity" }, { "code": null, "e": 8642, "s": 8631, "text": "3 quality " }, { "code": null, "e": 8650, "s": 8642, "text": "Pitch :" }, { "code": null, "e": 8658, "s": 8650, "text": "Pitch :" }, { "code": null, "e": 8760, "s": 8658, "text": "It is the characteristic of sound which distinguishes a shrilled soundwave from a dull or flat sound." }, { "code": null, "e": 8859, "s": 8760, "text": "The higher the frequency the higher is the pitch and the lower the frequency lower is their pitch." }, { "code": null, "e": 8922, "s": 8859, "text": "Frequency is defined as the number of cycles per unit of time." }, { "code": null, "e": 8934, "s": 8922, "text": "2.Loudness:" }, { "code": null, "e": 9069, "s": 8934, "text": "It relates with the amplitude of the sound higher the amplitude higher is the loudness and lower the amplitude lower is the loudness.]" }, { "code": null, "e": 9244, "s": 9069, "text": "The intensity of sound at any point is defined as the amount of energy passing normally per unit area helped around that point per unit time si unit of intensity are watt/m2." }, { "code": null, "e": 9281, "s": 9244, "text": "The intensity of sound at any point:" }, { "code": null, "e": 9367, "s": 9281, "text": "a ) Inversely proportional to the square of the distance of a point from the source.]" }, { "code": null, "e": 9468, "s": 9367, "text": "b) directly proportional to the square of the amplitude, sq of frequency and density of the medium." }, { "code": null, "e": 9485, "s": 9468, "text": "I1/I2 = A21/A2 2" }, { "code": null, "e": 9509, "s": 9485, "text": "Unit of loudness is bel" }, { "code": null, "e": 9552, "s": 9509, "text": "the practical unit of loudness is decibel." }, { "code": null, "e": 9567, "s": 9552, "text": "1db = 1/10 bel" }, { "code": null, "e": 9708, "s": 9567, "text": "3. Quality: Quality in that characteristic of sound distinguishes between sound produced by two sources having the same intensity and pitch." }, { "code": null, "e": 9815, "s": 9708, "text": "the quality of sound wave depends on factors like frequency and relative intensity of over tunes.zStep 1. " }, { "code": null, "e": 9860, "s": 9815, "text": " Here size of object, 4 cm" }, { "code": null, "e": 9905, "s": 9860, "text": " u=-6 cm (sign convention)" }, { "code": null, "e": 9950, "s": 9905, "text": " f=-12cm (sign convention)" }, { "code": null, "e": 9973, "s": 9950, "text": "Using, 1/u + 1/v =1/f " }, { "code": null, "e": 9989, "s": 9973, "text": "We get, Using, " }, { "code": null, "e": 10017, "s": 9989, "text": " -1/6 + 1/v =-1/12 ]" }, { "code": null, "e": 10036, "s": 10017, "text": " v=12cm" }, { "code": null, "e": 10150, "s": 10036, "text": "Image is formed at a distance of 12 cm behind the concave mirror as v is positive. Therefore , image is virtual." }, { "code": null, "e": 10172, "s": 10150, "text": "Using, m= h’/h =-v/u" }, { "code": null, "e": 10199, "s": 10172, "text": " h’=(-12/-6)4" }, { "code": null, "e": 10221, "s": 10199, "text": " hi=8 cm" }, { "code": null, "e": 10419, "s": 10223, "text": "Example 4: A convex mirror used in a bus has radius of curvature 3.5 m. If the driver of the bus locates a car at 10 m behind the bus, find the position, nature and size of the image of the car." }, { "code": null, "e": 10431, "s": 10419, "text": "Solution: " }, { "code": null, "e": 10484, "s": 10431, "text": "Here, R = 3-5 m f = R 2 3-5 2 = 1.75m, u = – 100 m. " }, { "code": null, "e": 10527, "s": 10484, "text": "Determination of the position of the car. " }, { "code": null, "e": 10557, "s": 10527, "text": "Using, Using, 1/u + 1/v =1/f " }, { "code": null, "e": 10572, "s": 10557, "text": " 1/v =1/f -1/u" }, { "code": null, "e": 10596, "s": 10572, "text": " 1/v= 1/1.75 -1/(-10) " }, { "code": null, "e": 10609, "s": 10596, "text": " v=1.5m" }, { "code": null, "e": 10693, "s": 10609, "text": "Thus, the car appears to be at 1.5 m from the convex mirror and behind the mirror. " }, { "code": null, "e": 10744, "s": 10693, "text": "Determination of the size and nature of the image " }, { "code": null, "e": 10765, "s": 10744, "text": "Using, m= h’/h =-v/u" }, { "code": null, "e": 10779, "s": 10765, "text": " m=-1.5/-10" }, { "code": null, "e": 10789, "s": 10779, "text": " m=0.15" }, { "code": null, "e": 10871, "s": 10789, "text": "Thus, the size of the image of the car is 0.15 times the actual size of the car. " }, { "code": null, "e": 10950, "s": 10871, "text": "Since m is positive, so image of the car is virtual and erect (i.e., upright)." }, { "code": null, "e": 10964, "s": 10952, "text": "ysachin2314" }, { "code": null, "e": 10979, "s": 10964, "text": "varshagumber28" }, { "code": null, "e": 10988, "s": 10979, "text": "Class 10" }, { "code": null, "e": 11004, "s": 10988, "text": "School Learning" }, { "code": null, "e": 11019, "s": 11004, "text": "School Physics" }, { "code": null, "e": 11038, "s": 11019, "text": "Technical Scripter" }, { "code": null, "e": 11136, "s": 11038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11161, "s": 11136, "text": "Introduction to Internet" }, { "code": null, "e": 11219, "s": 11161, "text": "Mobile Technologies - Definition, Types, Uses, Advantages" }, { "code": null, "e": 11289, "s": 11219, "text": "Metals and Non-Metals - Definition, Properties, Uses and Applications" }, { "code": null, "e": 11321, "s": 11289, "text": "CBSE Notes for Class 10 Physics" }, { "code": null, "e": 11382, "s": 11321, "text": "Rusting of Iron - Explanation, Chemical Reaction, Prevention" }, { "code": null, "e": 11409, "s": 11382, "text": "How to Align Text in HTML?" }, { "code": null, "e": 11429, "s": 11409, "text": "Libraries in Python" }, { "code": null, "e": 11464, "s": 11429, "text": "What are Different Output Devices?" }, { "code": null, "e": 11513, "s": 11464, "text": "Generations of Computers - Computer Fundamentals" } ]
Matplotlib.axes.Axes.arrow() in Python
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.arrow() function in axes module of matplotlib library is also used to add an arrow to the axes. This function is used to draws an arrow from (x, y) to (x+dx, y+dy) Syntax: Axes.arrow(self, x, y, dx, dy, **kwargs) Parameters: This method accept the following parameters that are described below: x, y: These parameter are the x and y coordinates of the arrow base. dx, dy: These parameter are the length of the arrow along x and y direction. Returns: This method returns the arrow which is a created FancyArrow object. Below examples illustrate the matplotlib.axes.Axes.arrow() function in matplotlib.axes: Example-1: # Implementation of matplotlib functionimport matplotlib.pyplot as plt ax = plt.axes()ax.arrow(0, 0, 0.6, 0.7, head_width = 0.05, head_length = 0.1) ax.set_title('matplotlib.axes.Axes.arrow() Example', fontsize = 14, fontweight ='bold') plt.show() Output: Example-2: # Implementation of matplotlib functionimport matplotlib.pyplot as plt ax = plt.axes()ax.arrow(6, 7, -2.5, -2.5, head_width = 0.5, head_length = 0.5, fc ='g', ec ='g')ax.set_title('matplotlib.axes.Axes.arrow() Example', fontsize = 14, fontweight ='bold') ax.set(xlim =(1, 10), ylim =(1, 10))ax.set_xlabel("X-Axis")ax.set_ylabel("Y-Axis") plt.show() Output: Python-matplotlib 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 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 501, "s": 328, "text": "The Axes.arrow() function in axes module of matplotlib library is also used to add an arrow to the axes. This function is used to draws an arrow from (x, y) to (x+dx, y+dy)" }, { "code": null, "e": 509, "s": 501, "text": "Syntax:" }, { "code": null, "e": 551, "s": 509, "text": "Axes.arrow(self, x, y, dx, dy, **kwargs)\n" }, { "code": null, "e": 633, "s": 551, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 702, "s": 633, "text": "x, y: These parameter are the x and y coordinates of the arrow base." }, { "code": null, "e": 779, "s": 702, "text": "dx, dy: These parameter are the length of the arrow along x and y direction." }, { "code": null, "e": 856, "s": 779, "text": "Returns: This method returns the arrow which is a created FancyArrow object." }, { "code": null, "e": 944, "s": 856, "text": "Below examples illustrate the matplotlib.axes.Axes.arrow() function in matplotlib.axes:" }, { "code": null, "e": 955, "s": 944, "text": "Example-1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt ax = plt.axes()ax.arrow(0, 0, 0.6, 0.7, head_width = 0.05, head_length = 0.1) ax.set_title('matplotlib.axes.Axes.arrow() Example', fontsize = 14, fontweight ='bold') plt.show()", "e": 1228, "s": 955, "text": null }, { "code": null, "e": 1236, "s": 1228, "text": "Output:" }, { "code": null, "e": 1247, "s": 1236, "text": "Example-2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt ax = plt.axes()ax.arrow(6, 7, -2.5, -2.5, head_width = 0.5, head_length = 0.5, fc ='g', ec ='g')ax.set_title('matplotlib.axes.Axes.arrow() Example', fontsize = 14, fontweight ='bold') ax.set(xlim =(1, 10), ylim =(1, 10))ax.set_xlabel(\"X-Axis\")ax.set_ylabel(\"Y-Axis\") plt.show()", "e": 1621, "s": 1247, "text": null }, { "code": null, "e": 1629, "s": 1621, "text": "Output:" }, { "code": null, "e": 1647, "s": 1629, "text": "Python-matplotlib" }, { "code": null, "e": 1654, "s": 1647, "text": "Python" } ]
Groovy - Environment
There are a variety of ways to get the Groovy environment setup. Binary download and installation − Go to the link www.groovy-lang.org/download.html to get the Windows Installer section. Click on this option to start the download of the Groovy installer. Once you launch the installer, follow the steps given below to complete the installation. Step 1 − Select the language installer. Step 2 − Click the Next button in the next screen. Step 3 − Click the ‘I Agree’ button. Step 4 − Accept the default components and click the Next button. Step 5 − Choose the appropriate destination folder and then click the Next button. Step 6 − Click the Install button to start the installation. Step 7 − Once the installation is complete, click the Next button to start the configuration. Step 8 − Choose the default options and click the Next button. Step 9 − Accept the default file associations and click the Next button. Step 10 − Click the Finish button to complete the installation. Once the above steps are followed, you can then start the groovy shell which is part of the Groovy installation that helps in testing our different aspects of the Groovy language without the need of having a full-fledged integrated development environment for Groovy. This can be done by running the command groovysh from the command prompt. If you want to include the groovy binaries as part of you maven or gradle build, you can add the following lines
[ { "code": null, "e": 2437, "s": 2372, "text": "There are a variety of ways to get the Groovy environment setup." }, { "code": null, "e": 2628, "s": 2437, "text": "Binary download and installation − Go to the link www.groovy-lang.org/download.html to get the Windows Installer section. Click on this option to start the download of the Groovy installer." }, { "code": null, "e": 2718, "s": 2628, "text": "Once you launch the installer, follow the steps given below to complete the installation." }, { "code": null, "e": 2758, "s": 2718, "text": "Step 1 − Select the language installer." }, { "code": null, "e": 2809, "s": 2758, "text": "Step 2 − Click the Next button in the next screen." }, { "code": null, "e": 2846, "s": 2809, "text": "Step 3 − Click the ‘I Agree’ button." }, { "code": null, "e": 2912, "s": 2846, "text": "Step 4 − Accept the default components and click the Next button." }, { "code": null, "e": 2995, "s": 2912, "text": "Step 5 − Choose the appropriate destination folder and then click the Next button." }, { "code": null, "e": 3056, "s": 2995, "text": "Step 6 − Click the Install button to start the installation." }, { "code": null, "e": 3150, "s": 3056, "text": "Step 7 − Once the installation is complete, click the Next button to start the configuration." }, { "code": null, "e": 3213, "s": 3150, "text": "Step 8 − Choose the default options and click the Next button." }, { "code": null, "e": 3286, "s": 3213, "text": "Step 9 − Accept the default file associations and click the Next button." }, { "code": null, "e": 3350, "s": 3286, "text": "Step 10 − Click the Finish button to complete the installation." }, { "code": null, "e": 3692, "s": 3350, "text": "Once the above steps are followed, you can then start the groovy shell which is part of the Groovy installation that helps in testing our different aspects of the Groovy language without the need of having a full-fledged integrated development environment for Groovy. This can be done by running the command groovysh from the command prompt." } ]
Bootstrap 4 | Forms
12 May, 2022 Form Layout: Bootstrap provides two types of form layout which are listed below: Stacked form Inline form Stacked form: The stacked form creates input field and submit button in stacked format. Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <h2 class="text-center">Stacked form</h2> <div class="container"> <form action="#"> <div class="form-group"> <label for="fname">First Name:</label> <input type="text" class="form-control" id="fname" placeholder="Enter First Name" name="fname"> </div> <div class="form-group"> <label for="lname">Last Name:</label> <input type="text" class="form-control" id="lname" placeholder="Enter Last Name" name="lname"> </div> <div class="form-group"> <label for="email">Email Id:</label> <input type="email" class="form-control" id="email" placeholder="Enter Email Id" name="email"> </div> <div class="form-group"> <label for="contact">Contact No:</label> <input type="text" class="form-control" id="contact" placeholder="Enter Contact Number" name="contact"> </div> <div class="form-group form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="remember"> Remember me </label> </div> <button type="submit" class="btn bg-success"> Submit </button> </form> </div></body></html> Output: Inline Form: The .form-inline class is used with <form> element to create inline form. The inline form contains elements that are left-aligned and inline. The inline property applies when viewports are at least 576px wide. If screen size is smaller than 576px then the form element will be stacked vertically.Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <h2 class="text-center">Inline form</h2> <div class="container"> <form class="form-inline" action="#"> <label for="fname">First Name:</label> <input type="text" class="form-control" id="fname" placeholder="Enter First Name" name="fname"> <label for="lname">Last Name:</label> <input type="text" class="form-control" id="lname" placeholder="Enter Last Name" name="lname"> <label for="email">Email Id:</label> <input type="email" class="form-control" id="email" placeholder="Enter Email Id" name="email"> <label for="contact">Contact No:</label> <input type="text" class="form-control" id="contact" placeholder="Enter Contact Number" name="contact"> <div class="form-group form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="remember"> Remember me </label> </div> <button type="submit" class="btn bg-success"> Submit </button> </form> </div></body></html> Output: Inline Form with Utilities: The Bootstrap spacing utilities is used to add space to look better inline form. The .mr-sm-2 class is used to add the right margin to each input on all devices (small and up) and .mb-2 class adds a margin to the bottom.Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <h2 class="text-center">Inline form with Utilities</h2> <div class="container-fluit"> <form class="form-inline" action="#"> <label for="fname" class="mb-2 mr-sm-2"> First Name: </label> <input type="text" class="form-control mb-2 mr-sm-2" id="fname" placeholder="Enter First Name" name="fname"> <label for="lname" class="mb-2 mr-sm-2"> Last Name: </label> <input type="text" class="form-control mb-2 mr-sm-2" id="lname" placeholder="Enter Last Name" name="lname"> <label for="email" class="mb-2 mr-sm-2"> Email Id: </label> <input type="email" class="form-control mb-2 mr-sm-2" id="email" placeholder="Enter Email Id" name="email"> <label for="contact" class="mb-2 mr-sm-2"> Contact No: </label> <input type="text" class="form-control mb-2 mr-sm-2" id="contact" placeholder="Enter Contact Number" name="contact"> <div class="form-check mb-2 mr-sm-2"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="remember"> Remember me </label> </div> <button type="submit" class="btn bg-success mb-2"> Submit </button> </form> </div></body></html> Output: Form Validation: The .was-validated or .needs-validation class in <form> element is used to provide validation before or after submitting the form. The input field with green border indicate valid and red border indicate invalid form content. The .valid-feedback or .invalid-feedback is used to display a notification message to the user before submitting the form.Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 class="text-success text-center">GeeksforGeeks</h1> <h2 class="text-center">Form Validation</h2> <div class="container"> <form action="#" class="was-validated"> <div class="form-group"> <label for="fname">First Name:</label> <input type="text" class="form-control" id="fname" placeholder="Enter First Name" name="fname" required> <div class="valid-feedback">Valid</div> <div class="invalid-feedback"> Please fill this field </div> </div> <div class="form-group"> <label for="lname">Last Name:</label> <input type="text" class="form-control" id="lname" placeholder="Enter Last Name" name="lname" required> <div class="valid-feedback">Valid</div> <div class="invalid-feedback"> Please fill this field </div> </div> <div class="form-group"> <label for="email">Email Id:</label> <input type="email" class="form-control" id="email" placeholder="Enter Email Id" name="email" required> <div class="valid-feedback">Valid</div> <div class="invalid-feedback"> Please fill this field </div> </div> <div class="form-group"> <label for="contact">Contact No:</label> <input type="text" class="form-control" id="contact" placeholder="Enter Contact Number" name="contact" required> <div class="valid-feedback">Valid</div> <div class="invalid-feedback"> Please fill this field </div> </div> <div class="form-group form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="remember" required> I agree <div class="valid-feedback">Valid</div> <div class="invalid-feedback"> Please check the checkbox </div> </label> </div> <button type="submit" class="btn bg-success"> Submit </button> </form> </div></body></html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 sahilintern simmytarika5 Bootstrap-4 Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2022" }, { "code": null, "e": 110, "s": 28, "text": "Form Layout: Bootstrap provides two types of form layout which are listed below: " }, { "code": null, "e": 123, "s": 110, "text": "Stacked form" }, { "code": null, "e": 135, "s": 123, "text": "Inline form" }, { "code": null, "e": 233, "s": 135, "text": "Stacked form: The stacked form creates input field and submit button in stacked format. Example: " }, { "code": null, "e": 238, "s": 233, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Form</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <h2 class=\"text-center\">Stacked form</h2> <div class=\"container\"> <form action=\"#\"> <div class=\"form-group\"> <label for=\"fname\">First Name:</label> <input type=\"text\" class=\"form-control\" id=\"fname\" placeholder=\"Enter First Name\" name=\"fname\"> </div> <div class=\"form-group\"> <label for=\"lname\">Last Name:</label> <input type=\"text\" class=\"form-control\" id=\"lname\" placeholder=\"Enter Last Name\" name=\"lname\"> </div> <div class=\"form-group\"> <label for=\"email\">Email Id:</label> <input type=\"email\" class=\"form-control\" id=\"email\" placeholder=\"Enter Email Id\" name=\"email\"> </div> <div class=\"form-group\"> <label for=\"contact\">Contact No:</label> <input type=\"text\" class=\"form-control\" id=\"contact\" placeholder=\"Enter Contact Number\" name=\"contact\"> </div> <div class=\"form-group form-check\"> <label class=\"form-check-label\"> <input class=\"form-check-input\" type=\"checkbox\" name=\"remember\"> Remember me </label> </div> <button type=\"submit\" class=\"btn bg-success\"> Submit </button> </form> </div></body></html>", "e": 2374, "s": 238, "text": null }, { "code": null, "e": 2383, "s": 2374, "text": "Output: " }, { "code": null, "e": 2702, "s": 2383, "text": "Inline Form: The .form-inline class is used with <form> element to create inline form. The inline form contains elements that are left-aligned and inline. The inline property applies when viewports are at least 576px wide. If screen size is smaller than 576px then the form element will be stacked vertically.Example: " }, { "code": null, "e": 2707, "s": 2702, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Form</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <h2 class=\"text-center\">Inline form</h2> <div class=\"container\"> <form class=\"form-inline\" action=\"#\"> <label for=\"fname\">First Name:</label> <input type=\"text\" class=\"form-control\" id=\"fname\" placeholder=\"Enter First Name\" name=\"fname\"> <label for=\"lname\">Last Name:</label> <input type=\"text\" class=\"form-control\" id=\"lname\" placeholder=\"Enter Last Name\" name=\"lname\"> <label for=\"email\">Email Id:</label> <input type=\"email\" class=\"form-control\" id=\"email\" placeholder=\"Enter Email Id\" name=\"email\"> <label for=\"contact\">Contact No:</label> <input type=\"text\" class=\"form-control\" id=\"contact\" placeholder=\"Enter Contact Number\" name=\"contact\"> <div class=\"form-group form-check\"> <label class=\"form-check-label\"> <input class=\"form-check-input\" type=\"checkbox\" name=\"remember\"> Remember me </label> </div> <button type=\"submit\" class=\"btn bg-success\"> Submit </button> </form> </div></body></html>", "e": 4746, "s": 2707, "text": null }, { "code": null, "e": 4755, "s": 4746, "text": "Output: " }, { "code": null, "e": 5013, "s": 4755, "text": "Inline Form with Utilities: The Bootstrap spacing utilities is used to add space to look better inline form. The .mr-sm-2 class is used to add the right margin to each input on all devices (small and up) and .mb-2 class adds a margin to the bottom.Example: " }, { "code": null, "e": 5018, "s": 5013, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Form</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <h2 class=\"text-center\">Inline form with Utilities</h2> <div class=\"container-fluit\"> <form class=\"form-inline\" action=\"#\"> <label for=\"fname\" class=\"mb-2 mr-sm-2\"> First Name: </label> <input type=\"text\" class=\"form-control mb-2 mr-sm-2\" id=\"fname\" placeholder=\"Enter First Name\" name=\"fname\"> <label for=\"lname\" class=\"mb-2 mr-sm-2\"> Last Name: </label> <input type=\"text\" class=\"form-control mb-2 mr-sm-2\" id=\"lname\" placeholder=\"Enter Last Name\" name=\"lname\"> <label for=\"email\" class=\"mb-2 mr-sm-2\"> Email Id: </label> <input type=\"email\" class=\"form-control mb-2 mr-sm-2\" id=\"email\" placeholder=\"Enter Email Id\" name=\"email\"> <label for=\"contact\" class=\"mb-2 mr-sm-2\"> Contact No: </label> <input type=\"text\" class=\"form-control mb-2 mr-sm-2\" id=\"contact\" placeholder=\"Enter Contact Number\" name=\"contact\"> <div class=\"form-check mb-2 mr-sm-2\"> <label class=\"form-check-label\"> <input class=\"form-check-input\" type=\"checkbox\" name=\"remember\"> Remember me </label> </div> <button type=\"submit\" class=\"btn bg-success mb-2\"> Submit </button> </form> </div></body></html>", "e": 7293, "s": 5018, "text": null }, { "code": null, "e": 7302, "s": 7293, "text": "Output: " }, { "code": null, "e": 7677, "s": 7302, "text": "Form Validation: The .was-validated or .needs-validation class in <form> element is used to provide validation before or after submitting the form. The input field with green border indicate valid and red border indicate invalid form content. The .valid-feedback or .invalid-feedback is used to display a notification message to the user before submitting the form.Example: " }, { "code": null, "e": 7682, "s": 7677, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Form</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 class=\"text-success text-center\">GeeksforGeeks</h1> <h2 class=\"text-center\">Form Validation</h2> <div class=\"container\"> <form action=\"#\" class=\"was-validated\"> <div class=\"form-group\"> <label for=\"fname\">First Name:</label> <input type=\"text\" class=\"form-control\" id=\"fname\" placeholder=\"Enter First Name\" name=\"fname\" required> <div class=\"valid-feedback\">Valid</div> <div class=\"invalid-feedback\"> Please fill this field </div> </div> <div class=\"form-group\"> <label for=\"lname\">Last Name:</label> <input type=\"text\" class=\"form-control\" id=\"lname\" placeholder=\"Enter Last Name\" name=\"lname\" required> <div class=\"valid-feedback\">Valid</div> <div class=\"invalid-feedback\"> Please fill this field </div> </div> <div class=\"form-group\"> <label for=\"email\">Email Id:</label> <input type=\"email\" class=\"form-control\" id=\"email\" placeholder=\"Enter Email Id\" name=\"email\" required> <div class=\"valid-feedback\">Valid</div> <div class=\"invalid-feedback\"> Please fill this field </div> </div> <div class=\"form-group\"> <label for=\"contact\">Contact No:</label> <input type=\"text\" class=\"form-control\" id=\"contact\" placeholder=\"Enter Contact Number\" name=\"contact\" required> <div class=\"valid-feedback\">Valid</div> <div class=\"invalid-feedback\"> Please fill this field </div> </div> <div class=\"form-group form-check\"> <label class=\"form-check-label\"> <input class=\"form-check-input\" type=\"checkbox\" name=\"remember\" required> I agree <div class=\"valid-feedback\">Valid</div> <div class=\"invalid-feedback\"> Please check the checkbox </div> </label> </div> <button type=\"submit\" class=\"btn bg-success\"> Submit </button> </form> </div></body></html>", "e": 10705, "s": 7682, "text": null }, { "code": null, "e": 10714, "s": 10705, "text": "Output: " }, { "code": null, "e": 10733, "s": 10714, "text": "Supported Browser:" }, { "code": null, "e": 10747, "s": 10733, "text": "Google Chrome" }, { "code": null, "e": 10765, "s": 10747, "text": "Internet Explorer" }, { "code": null, "e": 10773, "s": 10765, "text": "Firefox" }, { "code": null, "e": 10779, "s": 10773, "text": "Opera" }, { "code": null, "e": 10786, "s": 10779, "text": "Safari" }, { "code": null, "e": 10798, "s": 10786, "text": "ysachin2314" }, { "code": null, "e": 10810, "s": 10798, "text": "sahilintern" }, { "code": null, "e": 10823, "s": 10810, "text": "simmytarika5" }, { "code": null, "e": 10835, "s": 10823, "text": "Bootstrap-4" }, { "code": null, "e": 10845, "s": 10835, "text": "Bootstrap" }, { "code": null, "e": 10862, "s": 10845, "text": "Web Technologies" } ]
matplotlib.pyplot.nipy_spectral() in Python
22 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The nipy_spectral() function in pyplot module of matplotlib library is used to set the colormap to “nipy_spectral”. Syntax: matplotlib.pyplot.nipy_spectral() Parameters: This method does not accepts any parameters. Return value: This method does not returns any value. Below examples illustrate the matplotlib.pyplot.nipy_spectral() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.nipy_spectral()plt.title('matplotlib.pyplot.nipy_spectral() function Example', fontweight ="bold")plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.nipy_spectral()plt.title('matplotlib.pyplot.nipy_spectral() function Example', fontweight ="bold")plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 339, "s": 223, "text": "The nipy_spectral() function in pyplot module of matplotlib library is used to set the colormap to “nipy_spectral”." }, { "code": null, "e": 347, "s": 339, "text": "Syntax:" }, { "code": null, "e": 382, "s": 347, "text": "matplotlib.pyplot.nipy_spectral()\n" }, { "code": null, "e": 439, "s": 382, "text": "Parameters: This method does not accepts any parameters." }, { "code": null, "e": 493, "s": 439, "text": "Return value: This method does not returns any value." }, { "code": null, "e": 588, "s": 493, "text": "Below examples illustrate the matplotlib.pyplot.nipy_spectral() function in matplotlib.pyplot:" }, { "code": null, "e": 600, "s": 588, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.nipy_spectral()plt.title('matplotlib.pyplot.nipy_spectral() function Example', fontweight =\"bold\")plt.show()", "e": 1417, "s": 600, "text": null }, { "code": null, "e": 1425, "s": 1417, "text": "Output:" }, { "code": null, "e": 1437, "s": 1425, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.nipy_spectral()plt.title('matplotlib.pyplot.nipy_spectral() function Example', fontweight =\"bold\")plt.show()", "e": 2215, "s": 1437, "text": null }, { "code": null, "e": 2223, "s": 2215, "text": "Output:" }, { "code": null, "e": 2241, "s": 2223, "text": "Python-matplotlib" }, { "code": null, "e": 2248, "s": 2241, "text": "Python" }, { "code": null, "e": 2346, "s": 2248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2378, "s": 2346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2405, "s": 2378, "text": "Python Classes and Objects" }, { "code": null, "e": 2426, "s": 2405, "text": "Python OOPs Concepts" }, { "code": null, "e": 2449, "s": 2426, "text": "Introduction To PYTHON" }, { "code": null, "e": 2505, "s": 2449, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2536, "s": 2505, "text": "Python | os.path.join() method" }, { "code": null, "e": 2578, "s": 2536, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2620, "s": 2578, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2659, "s": 2620, "text": "Python | Get unique values from a list" } ]
Program to find Simple Interest and Compound Interest in PL/SQL
02 Jul, 2018 Prerequisite – PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given principal(p), rate(r), time(t), the task is to calculate the simple interest and compound interest. Examples: Input: p = 1500 r = 5 t = 3 Output: SI = 225, CI = 1736.44 Input: p = 2700 r = 7 t = 8 Output: SI = 1512, CI = 4639.1 Formula for Simple Interest:Formula for Compound Interest:Where:P: Principal (original amount)R: Rate of Interest (in %)T: Time period Below is the required implementation:- DECLARE --declaration of principal variable p NUMBER(9, 2); ----declaration of rate variable r NUMBER(9, 2); --declaration of time period variable t NUMBER(9, 2); --declaration of simple interest variable si NUMBER(9, 2); ci NUMBER(9, 2);BEGIN --Code Block Start --assigning principal values p := 33000; --assigning rate values r := 7; --assigning time period values t := 6; --To calculate SI by simple --mathematical formula si := ( p * r * t ) / 100; ci := p * Power (1 + ( r / 100 ),t); --Print Result of SI......... dbms_output.Put_line('Simple Interest = ' ||si); dbms_output.Put_line('Compound interest = ' || ci);END;--End program Output Simple Interest = 13860 Compound interest = 49524.1 SQL-PL/SQL 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? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jul, 2018" }, { "code": null, "e": 63, "s": 28, "text": "Prerequisite – PL/SQL introduction" }, { "code": null, "e": 273, "s": 63, "text": "In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 379, "s": 273, "text": "Given principal(p), rate(r), time(t), the task is to calculate the simple interest and compound interest." }, { "code": null, "e": 389, "s": 379, "text": "Examples:" }, { "code": null, "e": 538, "s": 389, "text": "Input: p = 1500\n r = 5\n t = 3\nOutput: SI = 225, CI = 1736.44 \n\nInput: p = 2700\n r = 7\n t = 8\nOutput: SI = 1512, CI = 4639.1\n" }, { "code": null, "e": 673, "s": 538, "text": "Formula for Simple Interest:Formula for Compound Interest:Where:P: Principal (original amount)R: Rate of Interest (in %)T: Time period" }, { "code": null, "e": 712, "s": 673, "text": "Below is the required implementation:-" }, { "code": " DECLARE --declaration of principal variable p NUMBER(9, 2); ----declaration of rate variable r NUMBER(9, 2); --declaration of time period variable t NUMBER(9, 2); --declaration of simple interest variable si NUMBER(9, 2); ci NUMBER(9, 2);BEGIN --Code Block Start --assigning principal values p := 33000; --assigning rate values r := 7; --assigning time period values t := 6; --To calculate SI by simple --mathematical formula si := ( p * r * t ) / 100; ci := p * Power (1 + ( r / 100 ),t); --Print Result of SI......... dbms_output.Put_line('Simple Interest = ' ||si); dbms_output.Put_line('Compound interest = ' || ci);END;--End program ", "e": 1490, "s": 712, "text": null }, { "code": null, "e": 1497, "s": 1490, "text": "Output" }, { "code": null, "e": 1550, "s": 1497, "text": "Simple Interest = 13860\nCompound interest = 49524.1\n" }, { "code": null, "e": 1561, "s": 1550, "text": "SQL-PL/SQL" }, { "code": null, "e": 1565, "s": 1561, "text": "SQL" }, { "code": null, "e": 1569, "s": 1565, "text": "SQL" }, { "code": null, "e": 1667, "s": 1569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1733, "s": 1667, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1757, "s": 1733, "text": "Window functions in SQL" }, { "code": null, "e": 1789, "s": 1757, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1806, "s": 1789, "text": "SQL using Python" }, { "code": null, "e": 1839, "s": 1806, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1917, "s": 1839, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1947, "s": 1917, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1983, "s": 1947, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2014, "s": 1983, "text": "SQL Query to Compare Two Dates" } ]
Java Program to Check Whether Undirected Graph is Connected Using DFS
02 Feb, 2021 Given an undirected graph, the task is to check if the given graph is connected or not using DFS. A connected graph is a graph that is connected in the sense of a topological space, i.e., there is always a path from any node to any other node in the graph. A graph that is not connected is said to be disconnected. Examples: Input: Output: Graph is connected Input: Output: Graph is disconnected Approach: Take a boolean visited [] array.Start DFS(Depth First Search) from any of the vertexes and mark the visited vertices as True in the visited[] array.After completion of DFS check if all the vertices in the visited [] array is marked as True.If yes then the graph is connected, or else the graph is not connected or disconnected. Take a boolean visited [] array. Start DFS(Depth First Search) from any of the vertexes and mark the visited vertices as True in the visited[] array. After completion of DFS check if all the vertices in the visited [] array is marked as True. If yes then the graph is connected, or else the graph is not connected or disconnected. Code: Java // Java Program to check if // an undirected graph is connected or not// using DFS import java.util.*; public class checkConnectivity { // Graph class static class Graph{ int vertices; // Linked list for adjacency list of a vertex LinkedList<Integer> adjacencyList []; @SuppressWarnings("unchecked") public Graph(int vertices) { this.vertices = vertices; adjacencyList = new LinkedList[vertices]; for (int i = 0; i<vertices ; i++) { adjacencyList[i] = new LinkedList<>(); } } // Function for adding edges public void addEdge(int source, int dest) { adjacencyList.addFirst(dest); adjacencyList[dest].addFirst(source); } } // Function to check if the graph is connected or not public void isConnected(Graph graph){ int vertices = graph.vertices; LinkedList<Integer> adjacencyList [] = graph.adjacencyList; // Take a boolean visited array boolean[] visited = new boolean[vertices]; // Start the DFS from vertex 0 DFS(0, adjacencyList, visited); // Check if all the vertices are visited // Set connected to False if one node is unvisited boolean connected = true; for (int i = 0; i <visited.length ; i++) { if(!visited[i]){ connected = false; break; } } if(connected){ System.out.println("Graph is connected"); }else{ System.out.println("Graph is disconnected"); } } public void DFS(int source, LinkedList<Integer> adjacencyList [], boolean[] visited){ // Mark the vertex visited as True visited = true; // Travel the adjacent neighbours for (int i = 0; i <adjacencyList.size() ; i++) { int neighbour = adjacencyList.get(i); if(visited[neighbour]==false){ // Call DFS from neighbour DFS(neighbour, adjacencyList, visited); } } } // Driver code public static void main(String[] args) { // Given graph 1 Graph graph = new Graph(5); graph.addEdge(0,1); graph.addEdge(0,4); graph.addEdge(1,4); graph.addEdge(1,3); graph.addEdge(3,4); graph.addEdge(2,1); graph.addEdge(2,3); // Check if it's connected System.out.print("Graph 1:- "); checkConnectivity c = new checkConnectivity(); c.isConnected(graph); // Given graph 2 graph = new Graph(5); graph.addEdge(0,1); graph.addEdge(0,4); graph.addEdge(1,4); graph.addEdge(1,3); graph.addEdge(3,4); // Check if it's connected System.out.print("Graph 2:- "); c = new checkConnectivity(); c.isConnected(graph); }} Graph 1:- Graph is connected Graph 2:- Graph is disconnected Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Feb, 2021" }, { "code": null, "e": 152, "s": 54, "text": "Given an undirected graph, the task is to check if the given graph is connected or not using DFS." }, { "code": null, "e": 369, "s": 152, "text": "A connected graph is a graph that is connected in the sense of a topological space, i.e., there is always a path from any node to any other node in the graph. A graph that is not connected is said to be disconnected." }, { "code": null, "e": 379, "s": 369, "text": "Examples:" }, { "code": null, "e": 386, "s": 379, "text": "Input:" }, { "code": null, "e": 413, "s": 386, "text": "Output: Graph is connected" }, { "code": null, "e": 420, "s": 413, "text": "Input:" }, { "code": null, "e": 450, "s": 420, "text": "Output: Graph is disconnected" }, { "code": null, "e": 460, "s": 450, "text": "Approach:" }, { "code": null, "e": 788, "s": 460, "text": "Take a boolean visited [] array.Start DFS(Depth First Search) from any of the vertexes and mark the visited vertices as True in the visited[] array.After completion of DFS check if all the vertices in the visited [] array is marked as True.If yes then the graph is connected, or else the graph is not connected or disconnected." }, { "code": null, "e": 821, "s": 788, "text": "Take a boolean visited [] array." }, { "code": null, "e": 938, "s": 821, "text": "Start DFS(Depth First Search) from any of the vertexes and mark the visited vertices as True in the visited[] array." }, { "code": null, "e": 1031, "s": 938, "text": "After completion of DFS check if all the vertices in the visited [] array is marked as True." }, { "code": null, "e": 1119, "s": 1031, "text": "If yes then the graph is connected, or else the graph is not connected or disconnected." }, { "code": null, "e": 1125, "s": 1119, "text": "Code:" }, { "code": null, "e": 1130, "s": 1125, "text": "Java" }, { "code": "// Java Program to check if // an undirected graph is connected or not// using DFS import java.util.*; public class checkConnectivity { // Graph class static class Graph{ int vertices; // Linked list for adjacency list of a vertex LinkedList<Integer> adjacencyList []; @SuppressWarnings(\"unchecked\") public Graph(int vertices) { this.vertices = vertices; adjacencyList = new LinkedList[vertices]; for (int i = 0; i<vertices ; i++) { adjacencyList[i] = new LinkedList<>(); } } // Function for adding edges public void addEdge(int source, int dest) { adjacencyList.addFirst(dest); adjacencyList[dest].addFirst(source); } } // Function to check if the graph is connected or not public void isConnected(Graph graph){ int vertices = graph.vertices; LinkedList<Integer> adjacencyList [] = graph.adjacencyList; // Take a boolean visited array boolean[] visited = new boolean[vertices]; // Start the DFS from vertex 0 DFS(0, adjacencyList, visited); // Check if all the vertices are visited // Set connected to False if one node is unvisited boolean connected = true; for (int i = 0; i <visited.length ; i++) { if(!visited[i]){ connected = false; break; } } if(connected){ System.out.println(\"Graph is connected\"); }else{ System.out.println(\"Graph is disconnected\"); } } public void DFS(int source, LinkedList<Integer> adjacencyList [], boolean[] visited){ // Mark the vertex visited as True visited = true; // Travel the adjacent neighbours for (int i = 0; i <adjacencyList.size() ; i++) { int neighbour = adjacencyList.get(i); if(visited[neighbour]==false){ // Call DFS from neighbour DFS(neighbour, adjacencyList, visited); } } } // Driver code public static void main(String[] args) { // Given graph 1 Graph graph = new Graph(5); graph.addEdge(0,1); graph.addEdge(0,4); graph.addEdge(1,4); graph.addEdge(1,3); graph.addEdge(3,4); graph.addEdge(2,1); graph.addEdge(2,3); // Check if it's connected System.out.print(\"Graph 1:- \"); checkConnectivity c = new checkConnectivity(); c.isConnected(graph); // Given graph 2 graph = new Graph(5); graph.addEdge(0,1); graph.addEdge(0,4); graph.addEdge(1,4); graph.addEdge(1,3); graph.addEdge(3,4); // Check if it's connected System.out.print(\"Graph 2:- \"); c = new checkConnectivity(); c.isConnected(graph); }}", "e": 4182, "s": 1130, "text": null }, { "code": null, "e": 4244, "s": 4182, "text": "Graph 1:- Graph is connected\nGraph 2:- Graph is disconnected\n" }, { "code": null, "e": 4251, "s": 4244, "text": "Picked" }, { "code": null, "e": 4275, "s": 4251, "text": "Technical Scripter 2020" }, { "code": null, "e": 4280, "s": 4275, "text": "Java" }, { "code": null, "e": 4294, "s": 4280, "text": "Java Programs" }, { "code": null, "e": 4313, "s": 4294, "text": "Technical Scripter" }, { "code": null, "e": 4318, "s": 4313, "text": "Java" }, { "code": null, "e": 4416, "s": 4318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4431, "s": 4416, "text": "Stream In Java" }, { "code": null, "e": 4452, "s": 4431, "text": "Introduction to Java" }, { "code": null, "e": 4473, "s": 4452, "text": "Constructors in Java" }, { "code": null, "e": 4492, "s": 4473, "text": "Exceptions in Java" }, { "code": null, "e": 4509, "s": 4492, "text": "Generics in Java" }, { "code": null, "e": 4535, "s": 4509, "text": "Java Programming Examples" }, { "code": null, "e": 4569, "s": 4535, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4616, "s": 4569, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4654, "s": 4616, "text": "Factory method design pattern in Java" } ]
HTML | DOM Location hash Property
05 Jul, 2022 The Location Hash property in HTML is used to return the anchor part of a URL. It can also be used to set the anchor part of the URL. It returns the string which represents the anchor part of a URL including the hash ‘#’ sign.Syntax: It returns the hash property. location.hash It is used to set the hash property. location.hash = anchorname Property Value anchorname: It contains a string value which specify the anchor part of an URL’S. Return Value: It returns a string value which represents the anchor part of a URL. Below program illustrates the Location hash property in HTML:Example: html <!DOCTYPE html><html> <head> <title>DOM Location hash property</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM Location hash Property</h2> <p> For setting the anchor part to 'newlocationhash', double click the "Set Anchor" button: </p> <button ondblclick="mylocation()"> Set Anchor </button> <p id="hash"></p> <script> function mylocation() { location.hash = "newlocationhash"; var h = "The anchor part is now: " + location.hash; document.getElementById("hash").innerHTML = h; } </script></body> </html> Output: After click on the button: Supported Browsers: The browsers supported by Location hash property are listed below: Google Chrome 1 Edge 12 Internet Explorer 3 Firefox 1 Opera 12.1 Safari 1 ManasChhabra2 geeksr3ap HTML-DOM CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Jul, 2022" }, { "code": null, "e": 289, "s": 53, "text": "The Location Hash property in HTML is used to return the anchor part of a URL. It can also be used to set the anchor part of the URL. It returns the string which represents the anchor part of a URL including the hash ‘#’ sign.Syntax: " }, { "code": null, "e": 321, "s": 289, "text": "It returns the hash property. " }, { "code": null, "e": 335, "s": 321, "text": "location.hash" }, { "code": null, "e": 374, "s": 335, "text": "It is used to set the hash property. " }, { "code": null, "e": 401, "s": 374, "text": "location.hash = anchorname" }, { "code": null, "e": 416, "s": 401, "text": "Property Value" }, { "code": null, "e": 498, "s": 416, "text": "anchorname: It contains a string value which specify the anchor part of an URL’S." }, { "code": null, "e": 582, "s": 498, "text": "Return Value: It returns a string value which represents the anchor part of a URL. " }, { "code": null, "e": 654, "s": 582, "text": "Below program illustrates the Location hash property in HTML:Example: " }, { "code": null, "e": 659, "s": 654, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM Location hash property</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM Location hash Property</h2> <p> For setting the anchor part to 'newlocationhash', double click the \"Set Anchor\" button: </p> <button ondblclick=\"mylocation()\"> Set Anchor </button> <p id=\"hash\"></p> <script> function mylocation() { location.hash = \"newlocationhash\"; var h = \"The anchor part is now: \" + location.hash; document.getElementById(\"hash\").innerHTML = h; } </script></body> </html> ", "e": 1482, "s": 659, "text": null }, { "code": null, "e": 1492, "s": 1482, "text": "Output: " }, { "code": null, "e": 1521, "s": 1492, "text": "After click on the button: " }, { "code": null, "e": 1610, "s": 1521, "text": "Supported Browsers: The browsers supported by Location hash property are listed below: " }, { "code": null, "e": 1626, "s": 1610, "text": "Google Chrome 1" }, { "code": null, "e": 1634, "s": 1626, "text": "Edge 12" }, { "code": null, "e": 1654, "s": 1634, "text": "Internet Explorer 3" }, { "code": null, "e": 1664, "s": 1654, "text": "Firefox 1" }, { "code": null, "e": 1675, "s": 1664, "text": "Opera 12.1" }, { "code": null, "e": 1684, "s": 1675, "text": "Safari 1" }, { "code": null, "e": 1700, "s": 1686, "text": "ManasChhabra2" }, { "code": null, "e": 1710, "s": 1700, "text": "geeksr3ap" }, { "code": null, "e": 1719, "s": 1710, "text": "HTML-DOM" }, { "code": null, "e": 1723, "s": 1719, "text": "CSS" }, { "code": null, "e": 1728, "s": 1723, "text": "HTML" }, { "code": null, "e": 1745, "s": 1728, "text": "Web Technologies" }, { "code": null, "e": 1750, "s": 1745, "text": "HTML" }, { "code": null, "e": 1848, "s": 1750, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1896, "s": 1848, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1958, "s": 1896, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2008, "s": 1958, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2066, "s": 2008, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2116, "s": 2066, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2164, "s": 2116, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2226, "s": 2164, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2276, "s": 2226, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2300, "s": 2276, "text": "REST API (Introduction)" } ]
Implementing Web Scraping in Python with Scrapy
08 Nov, 2019 Nowadays data is everything and if someone wants to get data from webpages then one way to use an API or implement Web Scraping techniques. In Python, Web scraping can be done easily by using scraping tools like BeautifulSoup. But what if the user is concerned about performance of scraper or need to scrape data efficiently. To overcome this problem, one can make use of MultiThreading/Multiprocessing with BeautifulSoup module and he/she can create spider, which can help to crawl over a website and extract data. In order to save the time one use Scrapy. With the help of Scrapy one can : 1. Fetch millions of data efficiently 2. Run it on server 3. Fetching data 4. Run spider in multiple processes Scrapy comes with whole new features of creating spider, running it and then saving data easily by scraping it. At first it looks quite confusing but it’s for the best. Let’s talk about the installation, creating a spider and then testing it. Step 1 : Creating virtual environment It is good to create one virtual environment as it isolates the program and doesn’t affect any other programs present in the machine. To create virtual environment first install it by using : sudo apt-get install python3-venv Create one folder and then activate it : mkdir scrapy-project && cd scrapy-project python3 -m venv myvenv If above command gives Error then try this : python3.5 -m venv myvenv After creating virtual environment activate it by using : source myvenv/bin/activate Step 2 : Installing Scrapy module Install Scrapy by using : pip install scrapy To install scrapy for any specific version of python : python3.5 -m pip install scrapy Replace 3.5 version with some other version like 3.6. Step 3 : Creating Scrapy project While working with Scrapy, one needs to create scrapy project. scrapy startproject gfg In Scrapy, always try to create one spider which helps to fetch data, so to create one, move to spider folder and create one python file over there. Create one spider with name gfgfetch.py python file. Step 4 : Creating Spider Move to the spider folder and create gfgfetch.py. While creating spider, always create one class with unique name and define requirements. First thing is to name the spider by assigning it with name variable and then provide the starting URL through which spider will start crawling. Define some methods which helps to crawl much deeper into that website. For now, let’s scrap all the URL present and store all those URL. import scrapy class ExtractUrls(scrapy.Spider): # This name must be unique always name = "extract" # Function which will be invoked def start_requests(self): # enter the URL here urls = ['https://www.geeksforgeeks.org/', ] for url in urls: yield scrapy.Request(url = url, callback = self.parse) Main motive is to get each url and then request it. Fetch all the urls or anchor tags from it. To do this, we need to create one more method parse ,to fetch data from the given url. Step 5 : Fetching data from given pageBefore writing parse function, test few things like how to fetch any data from given page. To do this make use of scrapy shell. It is just like python interpreter but with the ability to scrape data from the given url. In short, its a python interpreter with Scrapy functionality. scrapy shell URL Note: Make sure to in the same directory where scrapy.cfg is present, else it will not work. scrapy shell https://www.geeksforgeeks.org/ Now for fetching data from the given page, use selectors. These selectors can be either from CSS or from Xpath. For now, let’s try to fetch all url by using CSS Selector. To get anchor tag :response.css('a') response.css('a') To extract the data :links = response.css('a').extract() links = response.css('a').extract() For example, links[0] will show something like this :'<a href="https://www.geeksforgeeks.org/" title="GeeksforGeeks" rel="home">GeeksforGeeks</a>' '<a href="https://www.geeksforgeeks.org/" title="GeeksforGeeks" rel="home">GeeksforGeeks</a>' To get href attribute, use attributes tag.links = response.css('a::attr(href)').extract() links = response.css('a::attr(href)').extract() This will get all the href data which is very useful. Make use of this link and start requesting it. Now, let’s create parse method and fetch all the urls and then yield it. Follow that particular URL and fetch more links from that page and this will keep on happening again and again. In short, we are fetching all url present on that page. Scrapy, by default, filters those url which has already been visited. So it will not crawl the same url path again. But it’s possible that in two different pages there are two or more than two similar links. For example, in each page, the header link will be available which means that this header link will come in each page request. So try to exclude it by checking it. # Parse functiondef parse(self, response): # Extra feature to get title title = response.css('title::text').extract_first() # Get anchor tags links = response.css('a::attr(href)').extract() for link in links: yield { 'title': title, 'links': link } if 'geeksforgeeks' in link: yield scrapy.Request(url = link, callback = self.parse) Below is the implementation of scraper : # importing the scrapy moduleimport scrapy class ExtractUrls(scrapy.Spider): name = "extract" # request function def start_requests(self): urls = [ 'https://www.geeksforgeeks.org', ] for url in urls: yield scrapy.Request(url = url, callback = self.parse) # Parse function def parse(self, response): # Extra feature to get title title = response.css('title::text').extract_first() # Get anchor tags links = response.css('a::attr(href)').extract() for link in links: yield { 'title': title, 'links': link } if 'geeksforgeeks' in link: yield scrapy.Request(url = link, callback = self.parse) Step 6 : In last step, Run the spider and get output in simple json file scrapy crawl NAME_OF_SPIDER -o links.json Here, name of spider is “extract” for given example. It will fetch loads of data within few seconds. Output : Note : Scraping any web page is not a legal activity. Don’t perform any scraping operation without permission. Reference : https://doc.scrapy.org/en/. shubham_singh python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Nov, 2019" }, { "code": null, "e": 354, "s": 28, "text": "Nowadays data is everything and if someone wants to get data from webpages then one way to use an API or implement Web Scraping techniques. In Python, Web scraping can be done easily by using scraping tools like BeautifulSoup. But what if the user is concerned about performance of scraper or need to scrape data efficiently." }, { "code": null, "e": 586, "s": 354, "text": "To overcome this problem, one can make use of MultiThreading/Multiprocessing with BeautifulSoup module and he/she can create spider, which can help to crawl over a website and extract data. In order to save the time one use Scrapy." }, { "code": null, "e": 733, "s": 586, "text": "With the help of Scrapy one can :\n\n1. Fetch millions of data efficiently\n2. Run it on server\n3. Fetching data \n4. Run spider in multiple processes" }, { "code": null, "e": 902, "s": 733, "text": "Scrapy comes with whole new features of creating spider, running it and then saving data easily by scraping it. At first it looks quite confusing but it’s for the best." }, { "code": null, "e": 976, "s": 902, "text": "Let’s talk about the installation, creating a spider and then testing it." }, { "code": null, "e": 1014, "s": 976, "text": "Step 1 : Creating virtual environment" }, { "code": null, "e": 1206, "s": 1014, "text": "It is good to create one virtual environment as it isolates the program and doesn’t affect any other programs present in the machine. To create virtual environment first install it by using :" }, { "code": null, "e": 1240, "s": 1206, "text": "sudo apt-get install python3-venv" }, { "code": null, "e": 1281, "s": 1240, "text": "Create one folder and then activate it :" }, { "code": null, "e": 1348, "s": 1281, "text": "mkdir scrapy-project && cd scrapy-project\npython3 -m venv myvenv \n" }, { "code": null, "e": 1393, "s": 1348, "text": "If above command gives Error then try this :" }, { "code": null, "e": 1418, "s": 1393, "text": "python3.5 -m venv myvenv" }, { "code": null, "e": 1476, "s": 1418, "text": "After creating virtual environment activate it by using :" }, { "code": null, "e": 1503, "s": 1476, "text": "source myvenv/bin/activate" }, { "code": null, "e": 1538, "s": 1503, "text": " Step 2 : Installing Scrapy module" }, { "code": null, "e": 1564, "s": 1538, "text": "Install Scrapy by using :" }, { "code": null, "e": 1583, "s": 1564, "text": "pip install scrapy" }, { "code": null, "e": 1638, "s": 1583, "text": "To install scrapy for any specific version of python :" }, { "code": null, "e": 1670, "s": 1638, "text": "python3.5 -m pip install scrapy" }, { "code": null, "e": 1757, "s": 1670, "text": "Replace 3.5 version with some other version like 3.6. Step 3 : Creating Scrapy project" }, { "code": null, "e": 1820, "s": 1757, "text": "While working with Scrapy, one needs to create scrapy project." }, { "code": null, "e": 1844, "s": 1820, "text": "scrapy startproject gfg" }, { "code": null, "e": 2071, "s": 1844, "text": "In Scrapy, always try to create one spider which helps to fetch data, so to create one, move to spider folder and create one python file over there. Create one spider with name gfgfetch.py python file. Step 4 : Creating Spider" }, { "code": null, "e": 2493, "s": 2071, "text": "Move to the spider folder and create gfgfetch.py. While creating spider, always create one class with unique name and define requirements. First thing is to name the spider by assigning it with name variable and then provide the starting URL through which spider will start crawling. Define some methods which helps to crawl much deeper into that website. For now, let’s scrap all the URL present and store all those URL." }, { "code": "import scrapy class ExtractUrls(scrapy.Spider): # This name must be unique always name = \"extract\" # Function which will be invoked def start_requests(self): # enter the URL here urls = ['https://www.geeksforgeeks.org/', ] for url in urls: yield scrapy.Request(url = url, callback = self.parse)", "e": 2878, "s": 2493, "text": null }, { "code": null, "e": 3379, "s": 2878, "text": "Main motive is to get each url and then request it. Fetch all the urls or anchor tags from it. To do this, we need to create one more method parse ,to fetch data from the given url. Step 5 : Fetching data from given pageBefore writing parse function, test few things like how to fetch any data from given page. To do this make use of scrapy shell. It is just like python interpreter but with the ability to scrape data from the given url. In short, its a python interpreter with Scrapy functionality." }, { "code": null, "e": 3396, "s": 3379, "text": "scrapy shell URL" }, { "code": null, "e": 3489, "s": 3396, "text": "Note: Make sure to in the same directory where scrapy.cfg is present, else it will not work." }, { "code": null, "e": 3533, "s": 3489, "text": "scrapy shell https://www.geeksforgeeks.org/" }, { "code": null, "e": 3704, "s": 3533, "text": "Now for fetching data from the given page, use selectors. These selectors can be either from CSS or from Xpath. For now, let’s try to fetch all url by using CSS Selector." }, { "code": null, "e": 3741, "s": 3704, "text": "To get anchor tag :response.css('a')" }, { "code": null, "e": 3759, "s": 3741, "text": "response.css('a')" }, { "code": null, "e": 3816, "s": 3759, "text": "To extract the data :links = response.css('a').extract()" }, { "code": null, "e": 3852, "s": 3816, "text": "links = response.css('a').extract()" }, { "code": null, "e": 3999, "s": 3852, "text": "For example, links[0] will show something like this :'<a href=\"https://www.geeksforgeeks.org/\" title=\"GeeksforGeeks\" rel=\"home\">GeeksforGeeks</a>'" }, { "code": null, "e": 4093, "s": 3999, "text": "'<a href=\"https://www.geeksforgeeks.org/\" title=\"GeeksforGeeks\" rel=\"home\">GeeksforGeeks</a>'" }, { "code": null, "e": 4183, "s": 4093, "text": "To get href attribute, use attributes tag.links = response.css('a::attr(href)').extract()" }, { "code": null, "e": 4231, "s": 4183, "text": "links = response.css('a::attr(href)').extract()" }, { "code": null, "e": 4332, "s": 4231, "text": "This will get all the href data which is very useful. Make use of this link and start requesting it." }, { "code": null, "e": 4573, "s": 4332, "text": "Now, let’s create parse method and fetch all the urls and then yield it. Follow that particular URL and fetch more links from that page and this will keep on happening again and again. In short, we are fetching all url present on that page." }, { "code": null, "e": 4945, "s": 4573, "text": "Scrapy, by default, filters those url which has already been visited. So it will not crawl the same url path again. But it’s possible that in two different pages there are two or more than two similar links. For example, in each page, the header link will be available which means that this header link will come in each page request. So try to exclude it by checking it." }, { "code": "# Parse functiondef parse(self, response): # Extra feature to get title title = response.css('title::text').extract_first() # Get anchor tags links = response.css('a::attr(href)').extract() for link in links: yield { 'title': title, 'links': link } if 'geeksforgeeks' in link: yield scrapy.Request(url = link, callback = self.parse)", "e": 5398, "s": 4945, "text": null }, { "code": null, "e": 5440, "s": 5398, "text": " Below is the implementation of scraper :" }, { "code": "# importing the scrapy moduleimport scrapy class ExtractUrls(scrapy.Spider): name = \"extract\" # request function def start_requests(self): urls = [ 'https://www.geeksforgeeks.org', ] for url in urls: yield scrapy.Request(url = url, callback = self.parse) # Parse function def parse(self, response): # Extra feature to get title title = response.css('title::text').extract_first() # Get anchor tags links = response.css('a::attr(href)').extract() for link in links: yield { 'title': title, 'links': link } if 'geeksforgeeks' in link: yield scrapy.Request(url = link, callback = self.parse)", "e": 6268, "s": 5440, "text": null }, { "code": null, "e": 6342, "s": 6268, "text": " Step 6 : In last step, Run the spider and get output in simple json file" }, { "code": null, "e": 6384, "s": 6342, "text": "scrapy crawl NAME_OF_SPIDER -o links.json" }, { "code": null, "e": 6485, "s": 6384, "text": "Here, name of spider is “extract” for given example. It will fetch loads of data within few seconds." }, { "code": null, "e": 6495, "s": 6485, "text": "Output : " }, { "code": null, "e": 6606, "s": 6495, "text": "Note : Scraping any web page is not a legal activity. Don’t perform any scraping operation without permission." }, { "code": null, "e": 6646, "s": 6606, "text": "Reference : https://doc.scrapy.org/en/." }, { "code": null, "e": 6660, "s": 6646, "text": "shubham_singh" }, { "code": null, "e": 6675, "s": 6660, "text": "python-utility" }, { "code": null, "e": 6682, "s": 6675, "text": "Python" }, { "code": null, "e": 6698, "s": 6682, "text": "Python Programs" } ]
C Sharp with Selenium - How to Switch one tab to another tab in Csharp Selenium?
We can switch one tab to another tab with Selenium webdriver in C#. Sometimes on clicking a link or a button, we can have multiple tabs opened in the same browser. By default, the webdriver can access only the parent tab. To access the second tab, we have to switch the driver focus with the help of the SwitchTo().Window() method. The window handle id of the tab where we want to switch to is passed as a parameter.. The method CurrentWindowHandle yields the window handle id of the tab which is in focus. The WindowHandles method returns all the window handle ids of the opened tabs in the browser. Let us try to switch the tabs opened in browser as shown in below image − driver.SwitchTo().Window(driver.WindowHandles[1]); using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using System; using OpenQA.Selenium; namespace NUnitTestProject2{ public class Tests{ String url =" https://www.tutorialspoint.com/index.htm"; IWebDriver driver; [SetUp] public void Setup(){ //creating object of FirefoxDriver driver = new FirefoxDriver(""); } [Test] public void Test2(){ //implicit wait driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); //URL launch driver.Navigate().GoToUrl(url); //identify element then click IWebElement l = driver.FindElement(By.XPath("//*[text()='Jobs']")); l.Click(); //switch to second tab driver.SwitchTo().Window(driver.WindowHandles[1]); //get current window handle id Console.WriteLine ("Current window id: " + driver.CurrentWindowHandle); Console.WriteLine("Page title in second tab is: " + driver.Title); //close second tab driver.Close(); //switch to first tab driver.SwitchTo().Window(driver.WindowHandles[0]); IWebElement m = driver.FindElement(By.TagName("h4")); Console.WriteLine("Element in first tab is: " + m.Text); } [TearDown] public void close_Browser(){ driver.Quit(); } } }
[ { "code": null, "e": 1255, "s": 1187, "text": "We can switch one tab to another tab with Selenium webdriver in C#." }, { "code": null, "e": 1351, "s": 1255, "text": "Sometimes on clicking a link or a button, we can have multiple tabs opened in the same browser." }, { "code": null, "e": 1605, "s": 1351, "text": "By default, the webdriver can access only the parent tab. To access the second tab, we have to switch the driver focus with the help of the SwitchTo().Window() method. The window handle id of the tab where we want to switch to is passed as a parameter.." }, { "code": null, "e": 1788, "s": 1605, "text": "The method CurrentWindowHandle yields the window handle id of the tab which is in focus. The WindowHandles method returns all the window handle ids of the opened tabs in the browser." }, { "code": null, "e": 1862, "s": 1788, "text": "Let us try to switch the tabs opened in browser as shown in below image −" }, { "code": null, "e": 1913, "s": 1862, "text": "driver.SwitchTo().Window(driver.WindowHandles[1]);" }, { "code": null, "e": 3312, "s": 1913, "text": "using NUnit.Framework;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Firefox;\nusing System;\nusing OpenQA.Selenium;\nnamespace NUnitTestProject2{\n public class Tests{\n String url =\" https://www.tutorialspoint.com/index.htm\";\n IWebDriver driver;\n [SetUp]\n public void Setup(){\n //creating object of FirefoxDriver\n driver = new FirefoxDriver(\"\");\n }\n [Test]\n public void Test2(){\n //implicit wait\n driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);\n //URL launch\n driver.Navigate().GoToUrl(url);\n //identify element then click\n IWebElement l = driver.FindElement(By.XPath(\"//*[text()='Jobs']\"));\n l.Click();\n //switch to second tab\n driver.SwitchTo().Window(driver.WindowHandles[1]);\n //get current window handle id\n Console.WriteLine\n (\"Current window id: \" + driver.CurrentWindowHandle);\n Console.WriteLine(\"Page title in second tab is: \" + driver.Title);\n //close second tab\n driver.Close();\n //switch to first tab\n driver.SwitchTo().Window(driver.WindowHandles[0]);\n IWebElement m = driver.FindElement(By.TagName(\"h4\"));\n Console.WriteLine(\"Element in first tab is: \" + m.Text);\n }\n [TearDown]\n public void close_Browser(){\n driver.Quit();\n }\n }\n}" } ]
DateTime.ToShortDateString() Method in C#
30 Jan, 2019 This method is used to convert the value of the current DateTime object to its equivalent short date string representation. Syntax: public string ToShortDateString (); Return Value: This method returns a string that contains the short date string representation of the current DateTime object. Below programs illustrate the use of DateTime.ToShortDateString() Method: Example 1: // C# program to demonstrate the// DateTime.ToShortDateString()// Methodusing System; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting ShortTime from DateTime // using ToShortDateString() method; string value = date.ToShortDateString(); // Display the ShortTime Console.WriteLine("date is {0}", value); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} date is 01/01/2010 Example 2: // C# program to demonstrate the// DateTime.ToShortDateString()// Methodusing System; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date) { // getting ShortTime from DateTime // using ToShortDateString() method; string value = date.ToShortDateString(); // Display the date Console.WriteLine("date of {0} is "+ "{1}", date, value); }} date of 01/03/2010 04:00:15 is 01/03/2010 date of 01/05/2010 04:00:15 is 01/05/2010 date of 01/05/2010 04:00:15 is 01/05/2010 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | Constructors C# | Class and Object C# | Replace() Method Extension Method in C# Difference between Ref and Out keywords in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2019" }, { "code": null, "e": 152, "s": 28, "text": "This method is used to convert the value of the current DateTime object to its equivalent short date string representation." }, { "code": null, "e": 196, "s": 152, "text": "Syntax: public string ToShortDateString ();" }, { "code": null, "e": 322, "s": 196, "text": "Return Value: This method returns a string that contains the short date string representation of the current DateTime object." }, { "code": null, "e": 396, "s": 322, "text": "Below programs illustrate the use of DateTime.ToShortDateString() Method:" }, { "code": null, "e": 407, "s": 396, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.ToShortDateString()// Methodusing System; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting ShortTime from DateTime // using ToShortDateString() method; string value = date.ToShortDateString(); // Display the ShortTime Console.WriteLine(\"date is {0}\", value); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 1127, "s": 407, "text": null }, { "code": null, "e": 1147, "s": 1127, "text": "date is 01/01/2010\n" }, { "code": null, "e": 1158, "s": 1147, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// DateTime.ToShortDateString()// Methodusing System; class GFG { // Main Method public static void Main() { // calling check() method check(new DateTime(2010, 1, 3, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); check(new DateTime(2010, 1, 5, 4, 0, 15)); } public static void check(DateTime date) { // getting ShortTime from DateTime // using ToShortDateString() method; string value = date.ToShortDateString(); // Display the date Console.WriteLine(\"date of {0} is \"+ \"{1}\", date, value); }}", "e": 1814, "s": 1158, "text": null }, { "code": null, "e": 1941, "s": 1814, "text": "date of 01/03/2010 04:00:15 is 01/03/2010\ndate of 01/05/2010 04:00:15 is 01/05/2010\ndate of 01/05/2010 04:00:15 is 01/05/2010\n" }, { "code": null, "e": 1952, "s": 1941, "text": "Reference:" }, { "code": null, "e": 2054, "s": 1952, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.7.2" }, { "code": null, "e": 2077, "s": 2054, "text": "CSharp DateTime Struct" }, { "code": null, "e": 2091, "s": 2077, "text": "CSharp-method" }, { "code": null, "e": 2094, "s": 2091, "text": "C#" }, { "code": null, "e": 2192, "s": 2094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2235, "s": 2192, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2266, "s": 2235, "text": "Introduction to .NET Framework" }, { "code": null, "e": 2281, "s": 2266, "text": "C# | Delegates" }, { "code": null, "e": 2330, "s": 2281, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2346, "s": 2330, "text": "C# | Data Types" }, { "code": null, "e": 2364, "s": 2346, "text": "C# | Constructors" }, { "code": null, "e": 2386, "s": 2364, "text": "C# | Class and Object" }, { "code": null, "e": 2408, "s": 2386, "text": "C# | Replace() Method" }, { "code": null, "e": 2431, "s": 2408, "text": "Extension Method in C#" } ]
Python | Pandas isnull() and notnull()
08 Jun, 2022 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.While making a Data Frame from a csv file, many blank columns are imported as null value into the Data Frame which later creates problems while operating that data frame. Pandas isnull() and notnull() methods are used to check and manage NULL values in a data frame. Syntax: Pandas.isnull(“DataFrame Name”) or DataFrame.isnull()Parameters: Object to check null values forReturn Type: Dataframe of Boolean values which are True for NaN values To download the CSV file used, Click Here.Example #1: Using isnull() In the following example, Team column is checked for NULL values and a boolean series is returned by the isnull() method which stores True for ever NaN value and False for a Not null value. Python # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # creating bool series True for NaN valuesbool_series = pd.isnull(data["Team"]) # filtering data# displaying data only with team = NaNdata[bool_series] Output: As shown in output image, only the rows having Team=NULL are displayed. Syntax: Pandas.notnull(“DataFrame Name”) or DataFrame.notnull()Parameters: Object to check null values forReturn Type: Dataframe of Boolean values which are False for NaN values Example #1: Using notnull() In the following example, Gender column is checked for NULL values and a boolean series is returned by the notnull() method which stores True for ever NON-NULL value and False for a null value. Python # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # creating bool series False for NaN valuesbool_series = pd.notnull(data["Gender"]) # displayed data only with team = NaNdata[bool_series] Output: As shown in output image, only the rows having some value in Gender are displayed. swapnil159 user_ocpa simmytarika5 Python pandas-dataFrame Python pandas-dataFrame-methods python-modules Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 509, "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.While making a Data Frame from a csv file, many blank columns are imported as null value into the Data Frame which later creates problems while operating that data frame. Pandas isnull() and notnull() methods are used to check and manage NULL values in a data frame. " }, { "code": null, "e": 688, "s": 511, "text": "Syntax: Pandas.isnull(“DataFrame Name”) or DataFrame.isnull()Parameters: Object to check null values forReturn Type: Dataframe of Boolean values which are True for NaN values " }, { "code": null, "e": 949, "s": 688, "text": "To download the CSV file used, Click Here.Example #1: Using isnull() In the following example, Team column is checked for NULL values and a boolean series is returned by the isnull() method which stores True for ever NaN value and False for a Not null value. " }, { "code": null, "e": 956, "s": 949, "text": "Python" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # creating bool series True for NaN valuesbool_series = pd.isnull(data[\"Team\"]) # filtering data# displaying data only with team = NaNdata[bool_series]", "e": 1223, "s": 956, "text": null }, { "code": null, "e": 1305, "s": 1223, "text": "Output: As shown in output image, only the rows having Team=NULL are displayed. " }, { "code": null, "e": 1489, "s": 1309, "text": "Syntax: Pandas.notnull(“DataFrame Name”) or DataFrame.notnull()Parameters: Object to check null values forReturn Type: Dataframe of Boolean values which are False for NaN values " }, { "code": null, "e": 1712, "s": 1489, "text": "Example #1: Using notnull() In the following example, Gender column is checked for NULL values and a boolean series is returned by the notnull() method which stores True for ever NON-NULL value and False for a null value. " }, { "code": null, "e": 1719, "s": 1712, "text": "Python" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # creating bool series False for NaN valuesbool_series = pd.notnull(data[\"Gender\"]) # displayed data only with team = NaNdata[bool_series]", "e": 1973, "s": 1719, "text": null }, { "code": null, "e": 2066, "s": 1973, "text": "Output: As shown in output image, only the rows having some value in Gender are displayed. " }, { "code": null, "e": 2079, "s": 2068, "text": "swapnil159" }, { "code": null, "e": 2089, "s": 2079, "text": "user_ocpa" }, { "code": null, "e": 2102, "s": 2089, "text": "simmytarika5" }, { "code": null, "e": 2126, "s": 2102, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2158, "s": 2126, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2173, "s": 2158, "text": "python-modules" }, { "code": null, "e": 2187, "s": 2173, "text": "Python-pandas" }, { "code": null, "e": 2194, "s": 2187, "text": "Python" } ]
Shell Script to Join a String
25 Mar, 2021 There are different ways to concatenate strings in the shell. Some of them are listed below. String concatenation is used in shell scripting to make it much easier for the user to understand and use the program. Appending strings also allow the programmer to learn the working of concatenation on the shell. These are the ways for joining the string: Using String VariablesUsing String SeparatorUsing direct String Variable in echo commandUsing += Operator to Join Strings Using String Variables Using String Separator Using direct String Variable in echo command Using += Operator to Join Strings Open a file named “strAppend.sh” in gedit. # gedit strAppend.sh Close the editor and Give permission to execute # chmod 777 strAppend.sh Open a file “strAppend.sh” again and write the below code: #!/bin/bash #Using String Variables echo "********Using String Variables**************" First_string="Hello" echo -e "First String is \n ${First_string}" Second_string="World!" echo -e "Second String is \n ${Second_string}" # now concatenate both strings by assigning them to third string concate_string="$First_string$Second_string" echo -e "Joined String is \n ${concate_string}" echo -e "\n\n\n\n\n" Save the file by “Ctrl + s” and close the file, Now run the file by the below command: # ./strAppend.sh Hence, the strings are joined. Open a new and empty file named strAppend.sh and write below code # gedit strAppend.sh #!/bin/bash #using String Separator echo "********Using String Separator**************" Name="Hemant" echo -e "First String is \n ${Name}" roll_no="48" echo -e "Second String is \n ${roll_no}" # now concatenate both strings by separator concate_string=$Name:$roll_no echo -e "Joined String is \n ${concate_string}" echo -e "\n\n\n\n\n" Save the file by “Ctrl + s” and close the file, now run the file by the below command: # ./strAppend.sh Hence, the strings are joined. Open a new and empty file named strAppend.sh and write below code # gedit strAppend.sh #!/bin/bash # Using Direct Variable in echo command echo "********Using Direct Variable in echo command**************" First_string="Hey" echo -e "First String is \n ${First_string}" Second_string="You!" echo -e "Second String is \n ${Second_string}" # no need of third string echo "In this no need of third String" echo -e "Joined String is \n ${First_string}${Second_string}" echo -e "\n\n\n\n\n" Save the file by “Ctrl + s” and close the file, now run the file by the below command: # ./strAppend.sh Hence, the strings are joined. Open a new and empty file named strAppend.sh and write below code # gedit strAppend.sh #!/bin/bash # Using += Operator to Join Strings echo "********Using += Operator to Join Strings**************" # First declaring an empty string Combine="" #for loop for different strings for names in 'name1' 'name2' 'name3'; do # now append using += Combine+="$names " done echo -e "Joined String is \n ${Combine}" Save the file by “Ctrl + s” and close the file, now run the file by the below command: # ./strAppend.sh Hence, the strings are joined. Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Mar, 2021" }, { "code": null, "e": 337, "s": 28, "text": "There are different ways to concatenate strings in the shell. Some of them are listed below. String concatenation is used in shell scripting to make it much easier for the user to understand and use the program. Appending strings also allow the programmer to learn the working of concatenation on the shell. " }, { "code": null, "e": 380, "s": 337, "text": "These are the ways for joining the string:" }, { "code": null, "e": 502, "s": 380, "text": "Using String VariablesUsing String SeparatorUsing direct String Variable in echo commandUsing += Operator to Join Strings" }, { "code": null, "e": 525, "s": 502, "text": "Using String Variables" }, { "code": null, "e": 548, "s": 525, "text": "Using String Separator" }, { "code": null, "e": 593, "s": 548, "text": "Using direct String Variable in echo command" }, { "code": null, "e": 627, "s": 593, "text": "Using += Operator to Join Strings" }, { "code": null, "e": 670, "s": 627, "text": "Open a file named “strAppend.sh” in gedit." }, { "code": null, "e": 691, "s": 670, "text": "# gedit strAppend.sh" }, { "code": null, "e": 739, "s": 691, "text": "Close the editor and Give permission to execute" }, { "code": null, "e": 764, "s": 739, "text": "# chmod 777 strAppend.sh" }, { "code": null, "e": 823, "s": 764, "text": "Open a file “strAppend.sh” again and write the below code:" }, { "code": null, "e": 1231, "s": 823, "text": "#!/bin/bash\n\n#Using String Variables\necho \"********Using String Variables**************\"\n\nFirst_string=\"Hello\"\necho -e \"First String is \\n ${First_string}\"\n\nSecond_string=\"World!\"\necho -e \"Second String is \\n ${Second_string}\"\n\n# now concatenate both strings by assigning them to third string\nconcate_string=\"$First_string$Second_string\"\n\necho -e \"Joined String is \\n ${concate_string}\"\necho -e \"\\n\\n\\n\\n\\n\"" }, { "code": null, "e": 1318, "s": 1231, "text": "Save the file by “Ctrl + s” and close the file, Now run the file by the below command:" }, { "code": null, "e": 1335, "s": 1318, "text": "# ./strAppend.sh" }, { "code": null, "e": 1366, "s": 1335, "text": "Hence, the strings are joined." }, { "code": null, "e": 1432, "s": 1366, "text": "Open a new and empty file named strAppend.sh and write below code" }, { "code": null, "e": 1453, "s": 1432, "text": "# gedit strAppend.sh" }, { "code": null, "e": 1792, "s": 1453, "text": "#!/bin/bash\n\n#using String Separator\necho \"********Using String Separator**************\"\nName=\"Hemant\"\necho -e \"First String is \\n ${Name}\"\nroll_no=\"48\"\n\necho -e \"Second String is \\n ${roll_no}\"\n\n# now concatenate both strings by separator\nconcate_string=$Name:$roll_no\necho -e \"Joined String is \\n ${concate_string}\"\necho -e \"\\n\\n\\n\\n\\n\"" }, { "code": null, "e": 1879, "s": 1792, "text": "Save the file by “Ctrl + s” and close the file, now run the file by the below command:" }, { "code": null, "e": 1896, "s": 1879, "text": "# ./strAppend.sh" }, { "code": null, "e": 1927, "s": 1896, "text": "Hence, the strings are joined." }, { "code": null, "e": 1993, "s": 1927, "text": "Open a new and empty file named strAppend.sh and write below code" }, { "code": null, "e": 2014, "s": 1993, "text": "# gedit strAppend.sh" }, { "code": null, "e": 2416, "s": 2014, "text": "#!/bin/bash\n\n# Using Direct Variable in echo command\necho \"********Using Direct Variable in echo command**************\"\nFirst_string=\"Hey\"\necho -e \"First String is \\n ${First_string}\"\nSecond_string=\"You!\"\n\necho -e \"Second String is \\n ${Second_string}\"\n\n# no need of third string\necho \"In this no need of third String\"\necho -e \"Joined String is \\n ${First_string}${Second_string}\"\necho -e \"\\n\\n\\n\\n\\n\"" }, { "code": null, "e": 2503, "s": 2416, "text": "Save the file by “Ctrl + s” and close the file, now run the file by the below command:" }, { "code": null, "e": 2520, "s": 2503, "text": "# ./strAppend.sh" }, { "code": null, "e": 2551, "s": 2520, "text": "Hence, the strings are joined." }, { "code": null, "e": 2617, "s": 2551, "text": "Open a new and empty file named strAppend.sh and write below code" }, { "code": null, "e": 2638, "s": 2617, "text": "# gedit strAppend.sh" }, { "code": null, "e": 2957, "s": 2638, "text": "#!/bin/bash\n\n# Using += Operator to Join Strings\necho \"********Using += Operator to Join Strings**************\"\n\n# First declaring an empty string\nCombine=\"\"\n#for loop for different strings\nfor names in 'name1' 'name2' 'name3'; do\n\n# now append using +=\nCombine+=\"$names \"\ndone\necho -e \"Joined String is \\n ${Combine}\"" }, { "code": null, "e": 3044, "s": 2957, "text": "Save the file by “Ctrl + s” and close the file, now run the file by the below command:" }, { "code": null, "e": 3061, "s": 3044, "text": "# ./strAppend.sh" }, { "code": null, "e": 3092, "s": 3061, "text": "Hence, the strings are joined." }, { "code": null, "e": 3099, "s": 3092, "text": "Picked" }, { "code": null, "e": 3112, "s": 3099, "text": "Shell Script" }, { "code": null, "e": 3123, "s": 3112, "text": "Linux-Unix" }, { "code": null, "e": 3221, "s": 3123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3247, "s": 3221, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3282, "s": 3247, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3319, "s": 3282, "text": "chown command in Linux with Examples" }, { "code": null, "e": 3348, "s": 3319, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 3382, "s": 3348, "text": "mv command in Linux with examples" }, { "code": null, "e": 3419, "s": 3382, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 3456, "s": 3419, "text": "chmod command in Linux with examples" }, { "code": null, "e": 3495, "s": 3456, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 3535, "s": 3495, "text": "Array Basics in Shell Scripting | Set 1" } ]
Python | Remove duplicates from nested list
15 Apr, 2019 The task of removing duplicates many times in recent past, but sometimes when we deal with the complex data structure, in those cases we need different techniques to handle this type of problem. Let’s discuss certain ways in which this task can be achieved. Method #1 : Using sorted() + set()This particular problem can be solved using the above functions. The idea here is to sort the sublist and then removing the like elements using the set operations which removes duplicates. # Python3 code to demonstrate# removing duplicate sublist # using set() + sorted() # initializing listtest_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]] # printing original listprint("The original list : " + str(test_list)) # using set() + sorted()# removing duplicate sublistres = list(set(tuple(sorted(sub)) for sub in test_list)) # print resultprint("The list after duplicate removal : " + str(res)) The original list : [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]] The list after duplicate removal : [(-1, 0, 1), (1, 3, 4), (1, 2, 3)] Method #2 : Using set() + map() + sorted()The task performed by the list comprehension in the above method can be modified using the map function using lambda functions to extend the logic to each and every sublist. # Python3 code to demonstrate# removing duplicate sublist # using set() + map() + sorted() # initializing listtest_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]] # printing original listprint("The original list : " + str(test_list)) # using set() + map() + sorted()# removing duplicate sublistres = list(set(map(lambda i: tuple(sorted(i)), test_list))) # print resultprint("The list after duplicate removal : " + str(res)) The original list : [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]] The list after duplicate removal : [(-1, 0, 1), (1, 3, 4), (1, 2, 3)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2019" }, { "code": null, "e": 286, "s": 28, "text": "The task of removing duplicates many times in recent past, but sometimes when we deal with the complex data structure, in those cases we need different techniques to handle this type of problem. Let’s discuss certain ways in which this task can be achieved." }, { "code": null, "e": 509, "s": 286, "text": "Method #1 : Using sorted() + set()This particular problem can be solved using the above functions. The idea here is to sort the sublist and then removing the like elements using the set operations which removes duplicates." }, { "code": "# Python3 code to demonstrate# removing duplicate sublist # using set() + sorted() # initializing listtest_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]] # printing original listprint(\"The original list : \" + str(test_list)) # using set() + sorted()# removing duplicate sublistres = list(set(tuple(sorted(sub)) for sub in test_list)) # print resultprint(\"The list after duplicate removal : \" + str(res)) ", "e": 964, "s": 509, "text": null }, { "code": null, "e": 1114, "s": 964, "text": "The original list : [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]]\nThe list after duplicate removal : [(-1, 0, 1), (1, 3, 4), (1, 2, 3)]\n" }, { "code": null, "e": 1332, "s": 1116, "text": "Method #2 : Using set() + map() + sorted()The task performed by the list comprehension in the above method can be modified using the map function using lambda functions to extend the logic to each and every sublist." }, { "code": "# Python3 code to demonstrate# removing duplicate sublist # using set() + map() + sorted() # initializing listtest_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]] # printing original listprint(\"The original list : \" + str(test_list)) # using set() + map() + sorted()# removing duplicate sublistres = list(set(map(lambda i: tuple(sorted(i)), test_list))) # print resultprint(\"The list after duplicate removal : \" + str(res))", "e": 1804, "s": 1332, "text": null }, { "code": null, "e": 1954, "s": 1804, "text": "The original list : [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]]\nThe list after duplicate removal : [(-1, 0, 1), (1, 3, 4), (1, 2, 3)]\n" }, { "code": null, "e": 1975, "s": 1954, "text": "Python list-programs" }, { "code": null, "e": 1982, "s": 1975, "text": "Python" }, { "code": null, "e": 1998, "s": 1982, "text": "Python Programs" }, { "code": null, "e": 2096, "s": 1998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2114, "s": 2096, "text": "Python Dictionary" }, { "code": null, "e": 2156, "s": 2114, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2178, "s": 2156, "text": "Enumerate() in Python" }, { "code": null, "e": 2213, "s": 2178, "text": "Read a file line by line in Python" }, { "code": null, "e": 2239, "s": 2213, "text": "Python String | replace()" }, { "code": null, "e": 2282, "s": 2239, "text": "Python program to convert a list to string" }, { "code": null, "e": 2304, "s": 2282, "text": "Defaultdict in Python" }, { "code": null, "e": 2343, "s": 2304, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2381, "s": 2343, "text": "Python | Convert a list to dictionary" } ]
fgrep command in Linux with examples
11 Oct, 2021 The fgrep filter is used to search for the fixed-character strings in a file. There can be multiple files also to be searched. This command is useful when you need to search for strings which contain lots of regular expression metacharacters, such as “^”, “$”, etc. Syntax: fgrep [options] [ -e pattern_list] [pattern] [file] Options with Description: -c : It is used to print only a count of the lines which contain the pattern. -h : Used to display the matched lines. -i : During comparisons, it will ignore upper/lower case distinction. -l : Used to print the names of files with matching lines once, separated by new-lines. It will not repeat the names of files when the pattern is found more than once. -n : It is used precede each line by its line number in the file (first line is 1). -s : It will only display the error messages. -v : Print all lines except those contain the pattern. -x : Print only lines matched entirely. -e pattern_list : Search for a string in pattern-list (useful when the string begins with a “-“). -f pattern-file : Take the list of patterns from pattern-file. pattern : Specify a pattern to be used during the search for input. file : A path name of a file to be searched for the patterns. If no file operands are specified, the standard input will be used. Below are the examples with options to illustrate the fgrep command: Consider below file as input. Here it is create using cat command and “name of the file is para”. Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.Geeks*forgeeks is best for learni\ng. -c option: Displaying the count of number of matches. We can find the number of lines that match the given string. Example: $fgrep -c "usin.g" para Output: 1 -h option: To display the matched lines. Example: fgrep -h "usin.g" para Output: Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts. -i option: Used in case insensitive search. It ignore upper/lower case distinction during comparisons. It matches words like : “geeks*forgeeks”, “Geeks*forgeeks”. Example: fgrep -i "geeks*forgeeks" para Output: Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts. Geeks*forgeeks is best for learni\ng. -l option: It will display the file names that match the pattern. We can just display the files that contains the given string/pattern. Example: fgrep -l "geeks*forgeeks" para para2 Output: para -n option: Precede each line by its line number in the file. It shows line number of file with the line matched. Example: $ fgrep -n "learni\ng" para Output: 1:Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts. 2:Geeks*forgeeks is best for learni\ng. -v option: It is used to display all lines except those that contain the pattern. It will print all lines except those that contain the pattern. Example: fgrep -v "@re" para Output: Geeks*forgeeks is best for learni\ng. -x option: It will display only lines matched entirely. Example 1: fgrep -x "@re" para Output: Example 2: fgrep -x "Geeks*forgeeks is best for learni\ng." para Output: Geeks*forgeeks is best for learni\ng. anikaseth98 linux-command Linux-text-processing-commands Picked Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 chmod command in Linux with examples mv command in Linux with examples Basic Operators in Shell Scripting
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Oct, 2021" }, { "code": null, "e": 319, "s": 53, "text": "The fgrep filter is used to search for the fixed-character strings in a file. There can be multiple files also to be searched. This command is useful when you need to search for strings which contain lots of regular expression metacharacters, such as “^”, “$”, etc." }, { "code": null, "e": 327, "s": 319, "text": "Syntax:" }, { "code": null, "e": 380, "s": 327, "text": "fgrep [options] [ -e pattern_list] [pattern] [file]\n" }, { "code": null, "e": 406, "s": 380, "text": "Options with Description:" }, { "code": null, "e": 484, "s": 406, "text": "-c : It is used to print only a count of the lines which contain the pattern." }, { "code": null, "e": 524, "s": 484, "text": "-h : Used to display the matched lines." }, { "code": null, "e": 594, "s": 524, "text": "-i : During comparisons, it will ignore upper/lower case distinction." }, { "code": null, "e": 762, "s": 594, "text": "-l : Used to print the names of files with matching lines once, separated by new-lines. It will not repeat the names of files when the pattern is found more than once." }, { "code": null, "e": 846, "s": 762, "text": "-n : It is used precede each line by its line number in the file (first line is 1)." }, { "code": null, "e": 892, "s": 846, "text": "-s : It will only display the error messages." }, { "code": null, "e": 947, "s": 892, "text": "-v : Print all lines except those contain the pattern." }, { "code": null, "e": 987, "s": 947, "text": "-x : Print only lines matched entirely." }, { "code": null, "e": 1085, "s": 987, "text": "-e pattern_list : Search for a string in pattern-list (useful when the string begins with a “-“)." }, { "code": null, "e": 1148, "s": 1085, "text": "-f pattern-file : Take the list of patterns from pattern-file." }, { "code": null, "e": 1216, "s": 1148, "text": "pattern : Specify a pattern to be used during the search for input." }, { "code": null, "e": 1346, "s": 1216, "text": "file : A path name of a file to be searched for the patterns. If no file operands are specified, the standard input will be used." }, { "code": null, "e": 1415, "s": 1346, "text": "Below are the examples with options to illustrate the fgrep command:" }, { "code": null, "e": 1513, "s": 1415, "text": "Consider below file as input. Here it is create using cat command and “name of the file is para”." }, { "code": null, "e": 1626, "s": 1513, "text": "Hi, @re you usin.g geeks*forgeeks for learni\\ng computer science con/cepts.Geeks*forgeeks is best for learni\\ng." }, { "code": null, "e": 1741, "s": 1626, "text": "-c option: Displaying the count of number of matches. We can find the number of lines that match the given string." }, { "code": null, "e": 1750, "s": 1741, "text": "Example:" }, { "code": null, "e": 1774, "s": 1750, "text": "$fgrep -c \"usin.g\" para" }, { "code": null, "e": 1782, "s": 1774, "text": "Output:" }, { "code": null, "e": 1784, "s": 1782, "text": "1" }, { "code": null, "e": 1825, "s": 1784, "text": "-h option: To display the matched lines." }, { "code": null, "e": 1834, "s": 1825, "text": "Example:" }, { "code": null, "e": 1858, "s": 1834, "text": " fgrep -h \"usin.g\" para" }, { "code": null, "e": 1866, "s": 1858, "text": "Output:" }, { "code": null, "e": 1943, "s": 1866, "text": "Hi, @re you usin.g geeks*forgeeks for learni\\ng computer science con/cepts.\n" }, { "code": null, "e": 2106, "s": 1943, "text": "-i option: Used in case insensitive search. It ignore upper/lower case distinction during comparisons. It matches words like : “geeks*forgeeks”, “Geeks*forgeeks”." }, { "code": null, "e": 2115, "s": 2106, "text": "Example:" }, { "code": null, "e": 2147, "s": 2115, "text": " fgrep -i \"geeks*forgeeks\" para" }, { "code": null, "e": 2155, "s": 2147, "text": "Output:" }, { "code": null, "e": 2270, "s": 2155, "text": "Hi, @re you usin.g geeks*forgeeks for learni\\ng computer science con/cepts.\nGeeks*forgeeks is best for learni\\ng.\n" }, { "code": null, "e": 2406, "s": 2270, "text": "-l option: It will display the file names that match the pattern. We can just display the files that contains the given string/pattern." }, { "code": null, "e": 2415, "s": 2406, "text": "Example:" }, { "code": null, "e": 2452, "s": 2415, "text": "fgrep -l \"geeks*forgeeks\" para para2" }, { "code": null, "e": 2460, "s": 2452, "text": "Output:" }, { "code": null, "e": 2465, "s": 2460, "text": "para" }, { "code": null, "e": 2578, "s": 2465, "text": "-n option: Precede each line by its line number in the file. It shows line number of file with the line matched." }, { "code": null, "e": 2587, "s": 2578, "text": "Example:" }, { "code": null, "e": 2615, "s": 2587, "text": "$ fgrep -n \"learni\\ng\" para" }, { "code": null, "e": 2623, "s": 2615, "text": "Output:" }, { "code": null, "e": 2742, "s": 2623, "text": "1:Hi, @re you usin.g geeks*forgeeks for learni\\ng computer science con/cepts.\n2:Geeks*forgeeks is best for learni\\ng.\n" }, { "code": null, "e": 2887, "s": 2742, "text": "-v option: It is used to display all lines except those that contain the pattern. It will print all lines except those that contain the pattern." }, { "code": null, "e": 2896, "s": 2887, "text": "Example:" }, { "code": null, "e": 2916, "s": 2896, "text": "fgrep -v \"@re\" para" }, { "code": null, "e": 2924, "s": 2916, "text": "Output:" }, { "code": null, "e": 2963, "s": 2924, "text": "Geeks*forgeeks is best for learni\\ng.\n" }, { "code": null, "e": 3019, "s": 2963, "text": "-x option: It will display only lines matched entirely." }, { "code": null, "e": 3030, "s": 3019, "text": "Example 1:" }, { "code": null, "e": 3050, "s": 3030, "text": "fgrep -x \"@re\" para" }, { "code": null, "e": 3058, "s": 3050, "text": "Output:" }, { "code": null, "e": 3071, "s": 3060, "text": "Example 2:" }, { "code": null, "e": 3125, "s": 3071, "text": "fgrep -x \"Geeks*forgeeks is best for learni\\ng.\" para" }, { "code": null, "e": 3133, "s": 3125, "text": "Output:" }, { "code": null, "e": 3172, "s": 3133, "text": "Geeks*forgeeks is best for learni\\ng.\n" }, { "code": null, "e": 3184, "s": 3172, "text": "anikaseth98" }, { "code": null, "e": 3198, "s": 3184, "text": "linux-command" }, { "code": null, "e": 3229, "s": 3198, "text": "Linux-text-processing-commands" }, { "code": null, "e": 3236, "s": 3229, "text": "Picked" }, { "code": null, "e": 3260, "s": 3236, "text": "Technical Scripter 2018" }, { "code": null, "e": 3271, "s": 3260, "text": "Linux-Unix" }, { "code": null, "e": 3290, "s": 3271, "text": "Technical Scripter" }, { "code": null, "e": 3388, "s": 3290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3414, "s": 3388, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3449, "s": 3414, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3486, "s": 3449, "text": "chown command in Linux with Examples" }, { "code": null, "e": 3515, "s": 3486, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 3552, "s": 3515, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 3591, "s": 3552, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 3631, "s": 3591, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 3668, "s": 3631, "text": "chmod command in Linux with examples" }, { "code": null, "e": 3702, "s": 3668, "text": "mv command in Linux with examples" } ]
How to Easily Set Up Python on Any M1 Mac | by Frank Andrade | Towards Data Science
After buying an M1 Mac, I realized how confusing is to properly set up Python with all data science packages (and non-data science packages) on the new Mac models. According to this long Anaconda guide to the Apple Silicon, there are 3 options for running Python on the M1 — pyenv, anaconda, and miniforge. In this guide, I will show you how to easily set up Python on any M1 Mac using anaconda and miniforge. Anaconda brings all the tools (including Python and Jupyter Notebook) and packages used in data science with one install, while miniforge gives you the freedom to set up the conda environment as you want, so you need to install any package on your own. Note: The approaches mentioned in this guide won’t help you run Python natively on the M1 Macs but through Rosetta2. Python will work fine, just keep in mind that people see a 20–30% performance penalty when running x86–64 programs with Rosetta2 compared to native ARM64 Table of Contents1. Setting up Python and Data Science Packages with Anaconda - Step 1: Download and Install Anaconda - Step 2: Launch Jupyter Notebook/Lab - Step 3: Install any additional library2. Setting up Python with Miniforge - Step 1: Install Homebrew - Step 2: Install miniforge - Step 3: Setup and activate a virtual environment - Step 4: Install any Python library The steps below will help you download the Anaconda installer with all the packages used for data science. With this option, we will be able to manage Anaconda using the graphical installer. Go to Anaconda and click on the “Get started” button. A list will show up, choose the option “Download Anaconda installers.” Here you will see the Anaconda installers for all operating systems. Download any 64-bit installer for macOS (both work fine with M1 models thanks to Rosetta2). In my case, I chose the “64-Bit Graphical Installer” to have that nice GUI Anaconda offers. Once the file is downloaded, open it up to install Anaconda. A window will pop up, press “Continue” to start the installation. Once Anaconda is installed, you’ll see a green circular icon that represents the Anaconda logo. Click on it to run anaconda. If you downloaded the graphical installer like me, you will see the Anaconda navigator shown below. The main applications for data science are Jupyter Notebook and Jupyter Lab. Let’s launch any of them and import a couple of data science libraries to check everything was set up correctly import pandas as pdimport numpy as np The first time you import the libraries it might take more than usual. Anaconda brings the most common packages for data science, but there might be a couple of extra libraries you will need to install eventually. To do so, go to the “Environments” section located on the left. Then choose the environment you’re using (the default it’s called “base”), click on the dropdown, and select “Not installed.” After this, all the packages available through the conda-forge channel will be displayed. On the search box, you can write any library you want and then check the box to install the library. That’s it! You’re ready to use Python for data science. If something is unclear, check the video below for more details. Miniforge allows you to install the conda package manager. This option gives you the freedom to set up the conda environment as you want, so you need to install any package on your own. To easily install miniforge, first, we need to install Homebrew. Homebrew is an open-source package management system that simplifies the installation of software on macOS. To install Homebrew, go to this website. There you will find the code below that you need to run in the terminal. /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" The terminal will request your user’s password. Introduce it and then press return/enter to continue. Note: To install Homebrew, you need to have XCode build tools installed. If you’re not sure whether you already have it, don’t worry; the terminal will let you know if XCode build tools is missing and ask to install it. Once Homebrew is installed, restart the terminal and install miniforge running the following command. brew install miniforge In case you get the error zsh: command not found: brew, probably homebrew was saved in /opt/homebrew/ instead of /user/local/... If that’s the case, you have to modify your PATH with the command below (more details on StackOverflow). export PATH=/opt/homebrew/bin:$PATH After this, you can use brew and install miniforge. Now it’s time to create and activate a virtual environment. To install a virtual environment run the command below on the terminal. In this example, I’m going to create a new environment named test_env with Python 3.8 conda create --name test_env python=3.8 After this, you have to activate the environment running the following command. conda activate test_env Finally, you can install a Python package running the command below. conda install PACKAGENAME Let’s install the most popular Python libraries used in data science. conda install numpyconda install pandasconda install matplotlibconda install plotlyconda install scikit-learn You should also install Jupyter Notebook and/or Jupyter Lab. conda install jupyterconda install jupyterlab To run jupyter notebooks run the following command on the terminal. jupyter notebook That’s it! You’re ready to use Python for data science. Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF) If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to thousands of Python guides and Data science articles. If you sign up using my link, I’ll earn a small commission with no extra cost to you.
[ { "code": null, "e": 336, "s": 172, "text": "After buying an M1 Mac, I realized how confusing is to properly set up Python with all data science packages (and non-data science packages) on the new Mac models." }, { "code": null, "e": 479, "s": 336, "text": "According to this long Anaconda guide to the Apple Silicon, there are 3 options for running Python on the M1 — pyenv, anaconda, and miniforge." }, { "code": null, "e": 835, "s": 479, "text": "In this guide, I will show you how to easily set up Python on any M1 Mac using anaconda and miniforge. Anaconda brings all the tools (including Python and Jupyter Notebook) and packages used in data science with one install, while miniforge gives you the freedom to set up the conda environment as you want, so you need to install any package on your own." }, { "code": null, "e": 1106, "s": 835, "text": "Note: The approaches mentioned in this guide won’t help you run Python natively on the M1 Macs but through Rosetta2. Python will work fine, just keep in mind that people see a 20–30% performance penalty when running x86–64 programs with Rosetta2 compared to native ARM64" }, { "code": null, "e": 1481, "s": 1106, "text": "Table of Contents1. Setting up Python and Data Science Packages with Anaconda - Step 1: Download and Install Anaconda - Step 2: Launch Jupyter Notebook/Lab - Step 3: Install any additional library2. Setting up Python with Miniforge - Step 1: Install Homebrew - Step 2: Install miniforge - Step 3: Setup and activate a virtual environment - Step 4: Install any Python library" }, { "code": null, "e": 1672, "s": 1481, "text": "The steps below will help you download the Anaconda installer with all the packages used for data science. With this option, we will be able to manage Anaconda using the graphical installer." }, { "code": null, "e": 1866, "s": 1672, "text": "Go to Anaconda and click on the “Get started” button. A list will show up, choose the option “Download Anaconda installers.” Here you will see the Anaconda installers for all operating systems." }, { "code": null, "e": 2050, "s": 1866, "text": "Download any 64-bit installer for macOS (both work fine with M1 models thanks to Rosetta2). In my case, I chose the “64-Bit Graphical Installer” to have that nice GUI Anaconda offers." }, { "code": null, "e": 2177, "s": 2050, "text": "Once the file is downloaded, open it up to install Anaconda. A window will pop up, press “Continue” to start the installation." }, { "code": null, "e": 2402, "s": 2177, "text": "Once Anaconda is installed, you’ll see a green circular icon that represents the Anaconda logo. Click on it to run anaconda. If you downloaded the graphical installer like me, you will see the Anaconda navigator shown below." }, { "code": null, "e": 2591, "s": 2402, "text": "The main applications for data science are Jupyter Notebook and Jupyter Lab. Let’s launch any of them and import a couple of data science libraries to check everything was set up correctly" }, { "code": null, "e": 2629, "s": 2591, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 2700, "s": 2629, "text": "The first time you import the libraries it might take more than usual." }, { "code": null, "e": 2843, "s": 2700, "text": "Anaconda brings the most common packages for data science, but there might be a couple of extra libraries you will need to install eventually." }, { "code": null, "e": 3224, "s": 2843, "text": "To do so, go to the “Environments” section located on the left. Then choose the environment you’re using (the default it’s called “base”), click on the dropdown, and select “Not installed.” After this, all the packages available through the conda-forge channel will be displayed. On the search box, you can write any library you want and then check the box to install the library." }, { "code": null, "e": 3345, "s": 3224, "text": "That’s it! You’re ready to use Python for data science. If something is unclear, check the video below for more details." }, { "code": null, "e": 3531, "s": 3345, "text": "Miniforge allows you to install the conda package manager. This option gives you the freedom to set up the conda environment as you want, so you need to install any package on your own." }, { "code": null, "e": 3704, "s": 3531, "text": "To easily install miniforge, first, we need to install Homebrew. Homebrew is an open-source package management system that simplifies the installation of software on macOS." }, { "code": null, "e": 3818, "s": 3704, "text": "To install Homebrew, go to this website. There you will find the code below that you need to run in the terminal." }, { "code": null, "e": 3914, "s": 3818, "text": "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"" }, { "code": null, "e": 4016, "s": 3914, "text": "The terminal will request your user’s password. Introduce it and then press return/enter to continue." }, { "code": null, "e": 4236, "s": 4016, "text": "Note: To install Homebrew, you need to have XCode build tools installed. If you’re not sure whether you already have it, don’t worry; the terminal will let you know if XCode build tools is missing and ask to install it." }, { "code": null, "e": 4338, "s": 4236, "text": "Once Homebrew is installed, restart the terminal and install miniforge running the following command." }, { "code": null, "e": 4361, "s": 4338, "text": "brew install miniforge" }, { "code": null, "e": 4595, "s": 4361, "text": "In case you get the error zsh: command not found: brew, probably homebrew was saved in /opt/homebrew/ instead of /user/local/... If that’s the case, you have to modify your PATH with the command below (more details on StackOverflow)." }, { "code": null, "e": 4631, "s": 4595, "text": "export PATH=/opt/homebrew/bin:$PATH" }, { "code": null, "e": 4743, "s": 4631, "text": "After this, you can use brew and install miniforge. Now it’s time to create and activate a virtual environment." }, { "code": null, "e": 4901, "s": 4743, "text": "To install a virtual environment run the command below on the terminal. In this example, I’m going to create a new environment named test_env with Python 3.8" }, { "code": null, "e": 4941, "s": 4901, "text": "conda create --name test_env python=3.8" }, { "code": null, "e": 5021, "s": 4941, "text": "After this, you have to activate the environment running the following command." }, { "code": null, "e": 5045, "s": 5021, "text": "conda activate test_env" }, { "code": null, "e": 5114, "s": 5045, "text": "Finally, you can install a Python package running the command below." }, { "code": null, "e": 5140, "s": 5114, "text": "conda install PACKAGENAME" }, { "code": null, "e": 5210, "s": 5140, "text": "Let’s install the most popular Python libraries used in data science." }, { "code": null, "e": 5320, "s": 5210, "text": "conda install numpyconda install pandasconda install matplotlibconda install plotlyconda install scikit-learn" }, { "code": null, "e": 5381, "s": 5320, "text": "You should also install Jupyter Notebook and/or Jupyter Lab." }, { "code": null, "e": 5427, "s": 5381, "text": "conda install jupyterconda install jupyterlab" }, { "code": null, "e": 5495, "s": 5427, "text": "To run jupyter notebooks run the following command on the terminal." }, { "code": null, "e": 5512, "s": 5495, "text": "jupyter notebook" }, { "code": null, "e": 5568, "s": 5512, "text": "That’s it! You’re ready to use Python for data science." }, { "code": null, "e": 5686, "s": 5568, "text": "Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)" } ]
How to set ringtone in Android from Android activity?
This example demonstrates how do I set ringtone in android from android activity. 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"> <Button android:id="@+id/btnSelRingtone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Select Ringtone"/> <TextView android:id="@+id/tvRingtone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textStyle="bold|italic" android:layout_below="@id/btnSelRingtone" android:text="Ringtone Path"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.annotation.SuppressLint; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button btn; TextView txtView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = findViewById(R.id.btnSelRingtone); txtView = findViewById(R.id.tvRingtone); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Intent to select Ringtone. final Uri currentTone= RingtoneManager.getActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_ALARM); Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone"); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentTone); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true); startActivityForResult(intent, 999); } }); } @SuppressLint("SetTextI18n") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 999 && resultCode == RESULT_OK){ Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); txtView.setText("From :" + uri.getPath()); } } } 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" xmlns:tools="http://schemas.android.com/tools" package="app.com.sample"> <uses-permission android:name="android.permission.WRITE_SETTINGS" tools:ignore="ProtectedPermissions" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrates how do I set ringtone in android from android activity." }, { "code": null, "e": 1273, "s": 1144, "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": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2152, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnSelRingtone\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Select Ringtone\"/>\n <TextView\n android:id=\"@+id/tvRingtone\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textStyle=\"bold|italic\"\n android:layout_below=\"@id/btnSelRingtone\"\n android:text=\"Ringtone Path\"/>\n</RelativeLayout>" }, { "code": null, "e": 2209, "s": 2152, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4083, "s": 2209, "text": "import android.annotation.SuppressLint;\nimport android.content.Intent;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n Button btn;\n TextView txtView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btn = findViewById(R.id.btnSelRingtone);\n txtView = findViewById(R.id.tvRingtone);\n btn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n //Intent to select Ringtone.\n final Uri currentTone=\n RingtoneManager.getActualDefaultRingtoneUri(MainActivity.this,\n RingtoneManager.TYPE_ALARM);\n Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);\n intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);\n intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, \"Select Tone\");\n intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentTone);\n intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);\n intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);\n startActivityForResult(intent, 999);\n }\n });\n }\n @SuppressLint(\"SetTextI18n\")\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n if(requestCode == 999 && resultCode == RESULT_OK){\n Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);\n txtView.setText(\"From :\" + uri.getPath());\n }\n }\n}" }, { "code": null, "e": 4138, "s": 4083, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5014, "s": 4138, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n package=\"app.com.sample\">\n <uses-permission\n android:name=\"android.permission.WRITE_SETTINGS\"\n tools:ignore=\"ProtectedPermissions\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5361, "s": 5014, "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 −" } ]
Get the fully-qualified name of an inner class in Java
A fully-qualified class name in Java contains the package that the class originated from. Also, an inner class is a class that is another class member. So, the fully-qualified name of an inner class can be obtained using the getName() method. A program that demonstrates this is given as follows − Live Demo public class Main { public static void main(String[] argv) throws Exception { Class c = java.lang.Character.Subset.class; String innerClassName = c.getName(); System.out.println("The fully qualified name of the inner class is: " + innerClassName); } } The fully qualified name of the inner class is: java.lang.Character$Subset Now let us understand the above program. The getName() method is used to get the fully-qualified name of the inner class i.e. the Subset class and this is stored in className. Then this is displayed. A code snippet which demonstrates this is as follows − Class c = java.lang.Character.Subset.class; String innerClassName = c.getName(); System.out.println("The fully qualified name of the inner class is: " + innerClassName);
[ { "code": null, "e": 1305, "s": 1062, "text": "A fully-qualified class name in Java contains the package that the class originated from. Also, an inner class is a class that is another class member. So, the fully-qualified name of an inner class can be obtained using the getName() method." }, { "code": null, "e": 1360, "s": 1305, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1371, "s": 1360, "text": " Live Demo" }, { "code": null, "e": 1647, "s": 1371, "text": "public class Main {\n public static void main(String[] argv) throws Exception {\n Class c = java.lang.Character.Subset.class;\n String innerClassName = c.getName();\n System.out.println(\"The fully qualified name of the inner class is: \" + innerClassName);\n }\n}" }, { "code": null, "e": 1722, "s": 1647, "text": "The fully qualified name of the inner class is: java.lang.Character$Subset" }, { "code": null, "e": 1763, "s": 1722, "text": "Now let us understand the above program." }, { "code": null, "e": 1977, "s": 1763, "text": "The getName() method is used to get the fully-qualified name of the inner class i.e. the Subset class and this is stored in className. Then this is displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2147, "s": 1977, "text": "Class c = java.lang.Character.Subset.class;\nString innerClassName = c.getName();\nSystem.out.println(\"The fully qualified name of the inner class is: \" + innerClassName);" } ]
HTML DOM Style backgroundColor Property
The backgroundColor property is used for setting or returning background color for an element. We can specify values by standard names, rgb(), rgba(), hsl() or hsla(). Following is the syntax for − Setting the backgroundColor property − object.style.backgroundColor = "color|transparent The above property values are explained as follows − Let us look at the example for the backgroundColor property − Live Demo <!DOCTYPE html> <html> <head> <style> #DIV1{ background-color: rgba(10,122,102,0.1); } </style> <script> function changeBackColor(){ document.getElementById("DIV1").style.backgroundColor="rgba(1,200,55,0.5)"; document.getElementById("Sample").innerHTML="The background color is now changed"; } </script> </head> <body> <div id="DIV1">Duis tincidunt urna a interdum consectetur. Pellentesque nec pretium ante. In nisl magna, vestibulum non vulputate vel, feugiat ac tellus. Sed tincidunt id leo at mollis. Praesent pellentesque purus vitae scelerisque gravida. Pellentesque pulvinar scelerisque sem, at euismod sapien tristique et.</div> <p>Change the above div background color by clicking the below button</p> <button onclick="changeBackColor()">CHANGE COLOR</button> <p id="Sample"></p> </body> </html> This will produce the following output − On clicking the CHANGE CLIP button −
[ { "code": null, "e": 1230, "s": 1062, "text": "The backgroundColor property is used for setting or returning background color for an element. We can specify values by standard names, rgb(), rgba(), hsl() or hsla()." }, { "code": null, "e": 1260, "s": 1230, "text": "Following is the syntax for −" }, { "code": null, "e": 1299, "s": 1260, "text": "Setting the backgroundColor property −" }, { "code": null, "e": 1349, "s": 1299, "text": "object.style.backgroundColor = \"color|transparent" }, { "code": null, "e": 1402, "s": 1349, "text": "The above property values are explained as follows −" }, { "code": null, "e": 1464, "s": 1402, "text": "Let us look at the example for the backgroundColor property −" }, { "code": null, "e": 1474, "s": 1464, "text": "Live Demo" }, { "code": null, "e": 2309, "s": 1474, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n #DIV1{\n background-color: rgba(10,122,102,0.1);\n }\n</style>\n<script>\n function changeBackColor(){\n document.getElementById(\"DIV1\").style.backgroundColor=\"rgba(1,200,55,0.5)\";\n document.getElementById(\"Sample\").innerHTML=\"The background color is now changed\";\n }\n</script>\n</head>\n<body>\n<div id=\"DIV1\">Duis tincidunt urna a interdum consectetur. Pellentesque nec pretium ante.\nIn nisl magna, vestibulum non vulputate vel, feugiat ac tellus. Sed tincidunt id leo at mollis.\nPraesent pellentesque purus vitae scelerisque gravida. Pellentesque pulvinar scelerisque sem,\nat euismod sapien tristique et.</div>\n<p>Change the above div background color by clicking the below button</p>\n<button onclick=\"changeBackColor()\">CHANGE COLOR</button>\n<p id=\"Sample\"></p>\n</body>\n</html>" }, { "code": null, "e": 2350, "s": 2309, "text": "This will produce the following output −" }, { "code": null, "e": 2387, "s": 2350, "text": "On clicking the CHANGE CLIP button −" } ]
Prediction Intervals in Linear Regression | by Nathan Maton | Towards Data Science
This post covers how to calculate prediction intervals for Linear Regression. Normally when modeling, we get a single value from a regression model. But what if that value is used to plan or make important decisions? Then a single value may overstate our confidence when we’d like to know our uncertainty or error margin. Sure, you can look at a general error score for all of your predictions like RMSE, but what about for a single prediction? Prediction intervals give you a range for the prediction that accounts for any threshold of modeling error that matters to you. Similar to confidence intervals you can pick a threshold like 95%, where you want the actual value to fall into a range 95% of the time. This is extremely nice when planning, as you can use the upper and lower bounds in your estimation process. I’ve created a small method (with some input from here) to predict a range for a certain confidence threshold that matters to you or your project. I’ll illustrate a prediction interval with the Boston Housing dataset, predicting the median value of homes in different regions. Here’s the whole notebook if you prefer to read the code on GitHub. Otherwise, here’s a description of the dataset: from sklearn import datasetsprint(datasets.load_boston()['DESCR'])Boston house prices dataset---------------------------**Data Set Characteristics:** :Number of Instances: 506 :Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target. :Attribute Information (in order): - CRIM per capita crime rate by town - ZN proportion of residential land zoned for lots over 25,000 sq.ft. - INDUS proportion of non-retail business acres per town - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX nitric oxides concentration (parts per 10 million) - RM average number of rooms per dwelling - AGE proportion of owner-occupied units built prior to 1940 - DIS weighted distances to five Boston employment centres - RAD index of accessibility to radial highways - TAX full-value property-tax rate per $10,000 - PTRATIO pupil-teacher ratio by town - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town - LSTAT % lower status of the population - MEDV Median value of owner-occupied homes in $1000's We’ll preprocess the data, model it using the Linear Regression package from sklearn. #preprocess datadf = pd.DataFrame(datasets.load_boston()['data'])df.columns = datasets.load_boston()['feature_names']df['target'] = datasets.load_boston()['target'] #split dataX_train, X_test, y_train, y_test = train_test_split( df.drop('target',axis=1), df.target, test_size=0.2, random_state=42)#do modelingmodel = LinearRegression()fit_model = model.fit(X_train, y_train)predictions = fit_model.predict(X_test) What if you want to understand the model error on a single prediction level? Here’s where I built a simple method to get this interval. def get_prediction_interval(prediction, y_test, test_predictions, pi=.95): ''' Get a prediction interval for a linear regression. INPUTS: - Single prediction, - y_test - All test set predictions, - Prediction interval threshold (default = .95) OUTPUT: - Prediction interval for single prediction ''' #get standard deviation of y_test sum_errs = np.sum((y_test - test_predictions)**2) stdev = np.sqrt(1 / (len(y_test) - 2) * sum_errs)#get interval from standard deviation one_minus_pi = 1 - pi ppf_lookup = 1 - (one_minus_pi / 2) z_score = stats.norm.ppf(ppf_lookup) interval = z_score * stdev#generate prediction interval lower and upper bound lower, upper = prediction - interval, prediction + interval return lower, prediction, upperget_prediction_interval(predictions[0], y_test, predictions)OUTPUT: (19.24072024369257, 28.996723619824934, 38.752726995957296) So what should you take away from this post? There are tools you can use to calculate uncertainty called a prediction interval and for Linear Regression you can use the code above in your project. This has helped me calculate uncertainty for very critical business processes and is a useful technique in your tool belt. As you continue to progress in your data science career you’ll want more ways to quantify risk and uncertainty as that will help inform key decisions. Hope you enjoyed this short tutorial!
[ { "code": null, "e": 389, "s": 172, "text": "This post covers how to calculate prediction intervals for Linear Regression. Normally when modeling, we get a single value from a regression model. But what if that value is used to plan or make important decisions?" }, { "code": null, "e": 990, "s": 389, "text": "Then a single value may overstate our confidence when we’d like to know our uncertainty or error margin. Sure, you can look at a general error score for all of your predictions like RMSE, but what about for a single prediction? Prediction intervals give you a range for the prediction that accounts for any threshold of modeling error that matters to you. Similar to confidence intervals you can pick a threshold like 95%, where you want the actual value to fall into a range 95% of the time. This is extremely nice when planning, as you can use the upper and lower bounds in your estimation process." }, { "code": null, "e": 1335, "s": 990, "text": "I’ve created a small method (with some input from here) to predict a range for a certain confidence threshold that matters to you or your project. I’ll illustrate a prediction interval with the Boston Housing dataset, predicting the median value of homes in different regions. Here’s the whole notebook if you prefer to read the code on GitHub." }, { "code": null, "e": 1383, "s": 1335, "text": "Otherwise, here’s a description of the dataset:" }, { "code": null, "e": 2632, "s": 1383, "text": "from sklearn import datasetsprint(datasets.load_boston()['DESCR'])Boston house prices dataset---------------------------**Data Set Characteristics:** :Number of Instances: 506 :Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target. :Attribute Information (in order): - CRIM per capita crime rate by town - ZN proportion of residential land zoned for lots over 25,000 sq.ft. - INDUS proportion of non-retail business acres per town - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX nitric oxides concentration (parts per 10 million) - RM average number of rooms per dwelling - AGE proportion of owner-occupied units built prior to 1940 - DIS weighted distances to five Boston employment centres - RAD index of accessibility to radial highways - TAX full-value property-tax rate per $10,000 - PTRATIO pupil-teacher ratio by town - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town - LSTAT % lower status of the population - MEDV Median value of owner-occupied homes in $1000's" }, { "code": null, "e": 2718, "s": 2632, "text": "We’ll preprocess the data, model it using the Linear Regression package from sklearn." }, { "code": null, "e": 3135, "s": 2718, "text": "#preprocess datadf = pd.DataFrame(datasets.load_boston()['data'])df.columns = datasets.load_boston()['feature_names']df['target'] = datasets.load_boston()['target'] #split dataX_train, X_test, y_train, y_test = train_test_split( df.drop('target',axis=1), df.target, test_size=0.2, random_state=42)#do modelingmodel = LinearRegression()fit_model = model.fit(X_train, y_train)predictions = fit_model.predict(X_test)" }, { "code": null, "e": 3271, "s": 3135, "text": "What if you want to understand the model error on a single prediction level? Here’s where I built a simple method to get this interval." }, { "code": null, "e": 4223, "s": 3271, "text": "def get_prediction_interval(prediction, y_test, test_predictions, pi=.95): ''' Get a prediction interval for a linear regression. INPUTS: - Single prediction, - y_test - All test set predictions, - Prediction interval threshold (default = .95) OUTPUT: - Prediction interval for single prediction ''' #get standard deviation of y_test sum_errs = np.sum((y_test - test_predictions)**2) stdev = np.sqrt(1 / (len(y_test) - 2) * sum_errs)#get interval from standard deviation one_minus_pi = 1 - pi ppf_lookup = 1 - (one_minus_pi / 2) z_score = stats.norm.ppf(ppf_lookup) interval = z_score * stdev#generate prediction interval lower and upper bound lower, upper = prediction - interval, prediction + interval return lower, prediction, upperget_prediction_interval(predictions[0], y_test, predictions)OUTPUT: (19.24072024369257, 28.996723619824934, 38.752726995957296)" }, { "code": null, "e": 4543, "s": 4223, "text": "So what should you take away from this post? There are tools you can use to calculate uncertainty called a prediction interval and for Linear Regression you can use the code above in your project. This has helped me calculate uncertainty for very critical business processes and is a useful technique in your tool belt." } ]
JSON Formatting in Python
The JSON (Java Script Object Notation) is light weight, well accepted data interchange format. Using JSON formatting techniques in Python, we can convert JSON strings to Python objects, and also convert Python Objects to JSON strings. To use these functionalities, we need to use the json module of Python. The json module comes with the Python standard library. So at first we have to import it first. import json In the json module, there are some methods like dump(), and dumps() to convert Python objects to JSON strings. The dump() method takes two arguments, the first one is the object, and second one is file object. This method serialize the object as JSON formatted stream to file objects. Similarly the dumps() method takes only one argument. The argument is object. It converts the objects to JSON string. import json from io import StringIO str_io_obj = StringIO() #Use JSON Dump to make StringIO json.dump(["India", "Australia", "Brazil"], str_io_obj) print('StringIO Object value: ' + str(str_io_obj.getvalue())) my_json = { "name" : "Kalyan", "age" : 25, "city" : 'Delhi' } print(json.dumps(my_json, indent=4)) StringIO Object value: ["India", "Australia", "Brazil"] { "name": "Kalyan", "age": 25, "city": "Delhi" } In this case we are De-serializing the JSON strings. There are two different methods. These are load() and loads(). Both of these methods takes the JSON file as argument. load() converts to python objects from file objects data, and loads() converts from string type data. import json from io import StringIO str_io_obj = StringIO('["xyz", "abc", "xyz", "pqr"]') #load from StringIO print('Load: ' + str(json.load(str_io_obj))) print('String to Json: ' + str(json.loads('{"xyz" : 1, "abc" : 2, "xyz" : 3, "pqr" : 4}'))) Load: ['xyz', 'abc', 'xyz', 'pqr'] String to Json: {'xyz': 3, 'abc': 2, 'pqr': 4} The JSONEncoder class is used to convert Python Objects to JSON format. Here in this example we will see how a complex number object can be converted as JSON type object using the JSONEncoder. import json class Comp_Encoder(json.JSONEncoder): def default(self, comp_obj): if isinstance(comp_obj, complex): return [comp_obj.real, comp_obj.imag] return json.JSONEncoder.default(self, comp_obj) print(json.dumps(5+8j, cls=Comp_Encoder)) [5.0, 8.0] The JSONDecoder class performs the reverse action. import json my_str = '{"Asim" : 25, "Priyesh" : 23, "Asim" : "28"}' #Decode JSON using the JSONDecoder print(json.JSONDecoder().decode(my_str)) print(json.JSONDecoder().raw_decode(my_str)) {'Asim': '28', 'Priyesh': 23} ({'Asim': '28', 'Priyesh': 23}, 44)
[ { "code": null, "e": 1297, "s": 1062, "text": "The JSON (Java Script Object Notation) is light weight, well accepted data interchange format. Using JSON formatting techniques in Python, we can convert JSON strings to Python objects, and also convert Python Objects to JSON strings." }, { "code": null, "e": 1465, "s": 1297, "text": "To use these functionalities, we need to use the json module of Python. The json module comes with the Python standard library. So at first we have to import it first." }, { "code": null, "e": 1477, "s": 1465, "text": "import json" }, { "code": null, "e": 1880, "s": 1477, "text": "In the json module, there are some methods like dump(), and dumps() to convert Python objects to JSON strings. The dump() method takes two arguments, the first one is the object, and second one is file object. This method serialize the object as JSON formatted stream to file objects. Similarly the dumps() method takes only one argument. The argument is object. It converts the objects to JSON string." }, { "code": null, "e": 2198, "s": 1880, "text": "import json\nfrom io import StringIO\nstr_io_obj = StringIO()\n#Use JSON Dump to make StringIO\njson.dump([\"India\", \"Australia\", \"Brazil\"], str_io_obj)\nprint('StringIO Object value: ' + str(str_io_obj.getvalue()))\nmy_json = {\n \"name\" : \"Kalyan\",\n \"age\" : 25,\n \"city\" : 'Delhi'\n}\nprint(json.dumps(my_json, indent=4))" }, { "code": null, "e": 2312, "s": 2198, "text": "StringIO Object value: [\"India\", \"Australia\", \"Brazil\"] {\n \"name\": \"Kalyan\",\n \"age\": 25,\n \"city\": \"Delhi\"\n}" }, { "code": null, "e": 2585, "s": 2312, "text": "In this case we are De-serializing the JSON strings. There are two different methods. These are load() and loads(). Both of these methods takes the JSON file as argument. load() converts to python objects from file objects data, and loads() converts from string type data." }, { "code": null, "e": 2832, "s": 2585, "text": "import json\nfrom io import StringIO\nstr_io_obj = StringIO('[\"xyz\", \"abc\", \"xyz\", \"pqr\"]')\n#load from StringIO\nprint('Load: ' + str(json.load(str_io_obj)))\nprint('String to Json: ' + str(json.loads('{\"xyz\" : 1, \"abc\" : 2, \"xyz\" : 3, \"pqr\" : 4}')))" }, { "code": null, "e": 2914, "s": 2832, "text": "Load: ['xyz', 'abc', 'xyz', 'pqr']\nString to Json: {'xyz': 3, 'abc': 2, 'pqr': 4}" }, { "code": null, "e": 3107, "s": 2914, "text": "The JSONEncoder class is used to convert Python Objects to JSON format. Here in this example we will see how a complex number object can be converted as JSON type object using the JSONEncoder." }, { "code": null, "e": 3375, "s": 3107, "text": "import json\nclass Comp_Encoder(json.JSONEncoder):\n def default(self, comp_obj):\n if isinstance(comp_obj, complex):\n return [comp_obj.real, comp_obj.imag]\n return json.JSONEncoder.default(self, comp_obj)\n print(json.dumps(5+8j, cls=Comp_Encoder))" }, { "code": null, "e": 3386, "s": 3375, "text": "[5.0, 8.0]" }, { "code": null, "e": 3437, "s": 3386, "text": "The JSONDecoder class performs the reverse action." }, { "code": null, "e": 3626, "s": 3437, "text": "import json\nmy_str = '{\"Asim\" : 25, \"Priyesh\" : 23, \"Asim\" : \"28\"}'\n#Decode JSON using the JSONDecoder\nprint(json.JSONDecoder().decode(my_str))\nprint(json.JSONDecoder().raw_decode(my_str))" }, { "code": null, "e": 3692, "s": 3626, "text": "{'Asim': '28', 'Priyesh': 23}\n({'Asim': '28', 'Priyesh': 23}, 44)" } ]
ER and Relational Models - GeeksforGeeks
09 Oct, 2019 Students(rollno: integer, sname: string) Courses(courseno: integer, cname: string) Registration(rollno: integer, courseno: integer, percent: real) "Find the distinct names of all students who score more than 90% in the course numbered 107" Option A: This is a SQL query expression. It first perform a cross product of Students and Registration, then WHERE clause only keeps those rows in the cross product set where the student is registered for course no 107, and percentage is > 90. Then select distinct statement gives the distinct names of those students as the result set. Option B: This is a relational algebra expression. It first perform a NATURAL JOIN of Students and Registration (NATURAL JOIN implicitly joins on the basis of common attribute, which here is rollno ), then the select operation( sigma) keeps only those rows where the student is registered for courseno 107, and percentage is > 90. And then the projection operation (pi) projects only distinct student names from the set. Note: Projection operation (pi) always gives the distinct result. Option C: This is a Tuple Relational Calculus (TRC) language expression, It is not a procedural language (i.e. it only tells “what to do”, not “how to do”). It just represents a declarative mathematical expression. Here T is a Tuple variable. From left to right, it can be read like this, “It is a set of tuples T, where, there exists a tuple S in Relation Students, and there exist a tuple R in relation Registration, such that S.rollno = R.rollno AND R.couseno = 107 AND R.percent > 90 AND T.sname = S.sname”. And the schema of this result is (sname), i.e. each tuple T will contain only student name, because only T.sname has been defined in the expression. As TRC is a mathematical expression, hence it is expected to give only distinct result set. Option D: This is a Domain Relational Calculus (DRC) language expression. This is also not procedural. Here SN is a Domain Variable. It can be read from left to right like this “The set of domain variable SN, where, there exist a domain variable SR , and a domain variable Rp, such that, SN and SR domain variables is in relation Students and SR,107,RP is a domain variables set in relation Registration, AND RP > 90 “ Above, SN represents sname domain attribute in Students relation, SR represents rollno domain attribute in Students relation, and RP represents percentage domain attribute in Registration relation. The schema for the result set is (SN), i.e. only student name. As DRC is a mathematical expression, hence it is expected to give only distinct result set. Students(rollno: integer, sname: string) Courses(courseno: integer, cname: string) Registration(rollno: integer, courseno: integer, percent: real) "Find the distinct names of all students who score more than 90% in the course numbered 107" Option A: This is a SQL query expression. It first perform a cross product of Students and Registration, then WHERE clause only keeps those rows in the cross product set where the student is registered for course no 107, and percentage is > 90. Then select distinct statement gives the distinct names of those students as the result set. Option B: This is a relational algebra expression. It first perform a NATURAL JOIN of Students and Registration (NATURAL JOIN implicitly joins on the basis of common attribute, which here is rollno ), then the select operation( sigma) keeps only those rows where the student is registered for courseno 107, and percentage is > 90. And then the projection operation (pi) projects only distinct student names from the set. Note: Projection operation (pi) always gives the distinct result. Option C: This is a Tuple Relational Calculus (TRC) language expression, It is not a procedural language (i.e. it only tells “what to do”, not “how to do”). It just represents a declarative mathematical expression. Here T is a Tuple variable. From left to right, it can be read like this, “It is a set of tuples T, where, there exists a tuple S in Relation Students, and there exist a tuple R in relation Registration, such that S.rollno = R.rollno AND R.couseno = 107 AND R.percent > 90 AND T.sname = S.sname”. And the schema of this result is (sname), i.e. each tuple T will contain only student name, because only T.sname has been defined in the expression. As TRC is a mathematical expression, hence it is expected to give only distinct result set. Option D: This is a Domain Relational Calculus (DRC) language expression. This is also not procedural. Here SN is a Domain Variable. It can be read from left to right like this “The set of domain variable SN, where, there exist a domain variable SR , and a domain variable Rp, such that, SN and SR domain variables is in relation Students and SR,107,RP is a domain variables set in relation Registration, AND RP > 90 “ Above, SN represents sname domain attribute in Students relation, SR represents rollno domain attribute in Students relation, and RP represents percentage domain attribute in Registration relation. The schema for the result set is (SN), i.e. only student name. As DRC is a mathematical expression, hence it is expected to give only distinct result set. Table A Id Name Age ---------------- 12 Arun 60 15 Shreya 24 99 Rohit 11 Table B Id Name Age ---------------- 15 Shreya 24 25 Hari 40 98 Rohit 20 99 Rohit 11 Table C Id Phone Area ----------------- 10 2200 02 99 2100 01 M ( M1, M2, M3, P1) P ( P1, P2 ) N ( P1, N1, N2 ) Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies Axios in React: A Guide for Beginners Implementation of Bit Stuffing and Bit Destuffing How to set background images in ReactJS ? BigInt (BIG INTEGERS) in C++ with Example How to Install Flutter on Visual Studio Code? How to calculate MOVING AVERAGE in a Pandas DataFrame? How to Show Images on Click using HTML ? How to install bootstrap in React.js ? Microsoft Interview Experience for Internship (Via Engage)
[ { "code": null, "e": 29600, "s": 29572, "text": "\n09 Oct, 2019" }, { "code": null, "e": 29759, "s": 29600, "text": " Students(rollno: integer, sname: string)\n Courses(courseno: integer, cname: string)\n Registration(rollno: integer, courseno: integer, percent: real)" }, { "code": null, "e": 29866, "s": 29759, "text": " \"Find the distinct names of all students who score \n more than 90% in the course numbered 107\"" }, { "code": null, "e": 30211, "s": 29866, "text": "Option A:\n\nThis is a SQL query expression. It first perform a cross product of Students \nand Registration, then WHERE clause only keeps those rows in the cross product \nset where the student is registered for course no 107, and percentage is > 90. \nThen select distinct statement gives the distinct names of those students as the \nresult set.\n\n" }, { "code": null, "e": 30705, "s": 30211, "text": "Option B:\n\nThis is a relational algebra expression. It first perform a NATURAL JOIN \nof Students and Registration (NATURAL JOIN implicitly joins on the basis \nof common attribute, which here is rollno ), then the select operation( sigma) \nkeeps only those rows where the student is registered for courseno 107,\nand percentage is > 90. And then the projection operation (pi) projects only \ndistinct student names from the set.\n\nNote: Projection operation (pi) always gives the distinct result.\n" }, { "code": null, "e": 31470, "s": 30705, "text": "Option C:\n\nThis is a Tuple Relational Calculus (TRC) language expression,\nIt is not a procedural language (i.e. it only tells “what to do”, \nnot “how to do”). It just represents a declarative mathematical \nexpression.\n\nHere T is a Tuple variable.\n\nFrom left to right, it can be read like this, “It is a set of\ntuples T, where, there exists a tuple S in Relation Students, and \nthere exist a tuple R in relation Registration, such that \nS.rollno = R.rollno AND R.couseno = 107 AND R.percent > 90 AND \nT.sname = S.sname”. And the schema of this result is (sname), i.e. each \ntuple T will contain only student name, because only T.sname has been defined \nin the expression.\n\nAs TRC is a mathematical expression, hence it is expected to give only distinct result set.\n" }, { "code": null, "e": 32253, "s": 31470, "text": "Option D:\n\nThis is a Domain Relational Calculus (DRC) language expression. \nThis is also not procedural. Here SN is a Domain Variable. It can be read \nfrom left to right like this “The set of domain variable SN, where, \nthere exist a domain variable SR , and a domain variable Rp, such that, \nSN and SR domain variables is in relation Students and SR,107,RP is a domain\nvariables set in relation Registration, AND RP > 90 “\n\nAbove, SN represents sname domain attribute in Students relation, SR \nrepresents rollno domain attribute in Students relation, and RP represents \npercentage domain attribute in Registration relation.\nThe schema for the result set is (SN), i.e. only student name.\n\nAs DRC is a mathematical expression, hence it is expected to\ngive only distinct result set.\n\n" }, { "code": null, "e": 32412, "s": 32253, "text": " Students(rollno: integer, sname: string)\n Courses(courseno: integer, cname: string)\n Registration(rollno: integer, courseno: integer, percent: real)" }, { "code": null, "e": 32519, "s": 32412, "text": " \"Find the distinct names of all students who score \n more than 90% in the course numbered 107\"" }, { "code": null, "e": 32864, "s": 32519, "text": "Option A:\n\nThis is a SQL query expression. It first perform a cross product of Students \nand Registration, then WHERE clause only keeps those rows in the cross product \nset where the student is registered for course no 107, and percentage is > 90. \nThen select distinct statement gives the distinct names of those students as the \nresult set.\n\n" }, { "code": null, "e": 33358, "s": 32864, "text": "Option B:\n\nThis is a relational algebra expression. It first perform a NATURAL JOIN \nof Students and Registration (NATURAL JOIN implicitly joins on the basis \nof common attribute, which here is rollno ), then the select operation( sigma) \nkeeps only those rows where the student is registered for courseno 107,\nand percentage is > 90. And then the projection operation (pi) projects only \ndistinct student names from the set.\n\nNote: Projection operation (pi) always gives the distinct result.\n" }, { "code": null, "e": 34123, "s": 33358, "text": "Option C:\n\nThis is a Tuple Relational Calculus (TRC) language expression,\nIt is not a procedural language (i.e. it only tells “what to do”, \nnot “how to do”). It just represents a declarative mathematical \nexpression.\n\nHere T is a Tuple variable.\n\nFrom left to right, it can be read like this, “It is a set of\ntuples T, where, there exists a tuple S in Relation Students, and \nthere exist a tuple R in relation Registration, such that \nS.rollno = R.rollno AND R.couseno = 107 AND R.percent > 90 AND \nT.sname = S.sname”. And the schema of this result is (sname), i.e. each \ntuple T will contain only student name, because only T.sname has been defined \nin the expression.\n\nAs TRC is a mathematical expression, hence it is expected to give only distinct result set.\n" }, { "code": null, "e": 34906, "s": 34123, "text": "Option D:\n\nThis is a Domain Relational Calculus (DRC) language expression. \nThis is also not procedural. Here SN is a Domain Variable. It can be read \nfrom left to right like this “The set of domain variable SN, where, \nthere exist a domain variable SR , and a domain variable Rp, such that, \nSN and SR domain variables is in relation Students and SR,107,RP is a domain\nvariables set in relation Registration, AND RP > 90 “\n\nAbove, SN represents sname domain attribute in Students relation, SR \nrepresents rollno domain attribute in Students relation, and RP represents \npercentage domain attribute in Registration relation.\nThe schema for the result set is (SN), i.e. only student name.\n\nAs DRC is a mathematical expression, hence it is expected to\ngive only distinct result set.\n\n" }, { "code": null, "e": 35181, "s": 34906, "text": "Table A\nId Name Age\n----------------\n12 Arun 60\n15 Shreya 24\n99 Rohit 11\n\n\nTable B\nId Name Age\n----------------\n15 Shreya 24\n25 Hari 40\n98 Rohit 20\n99 Rohit 11\n\n\nTable C\nId Phone Area\n-----------------\n10 2200 02 \n99 2100 01\n" }, { "code": null, "e": 35231, "s": 35181, "text": "M ( M1, M2, M3, P1)\nP ( P1, P2 )\nN ( P1, N1, N2 )" }, { "code": null, "e": 35329, "s": 35231, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 35338, "s": 35329, "text": "Comments" }, { "code": null, "e": 35351, "s": 35338, "text": "Old Comments" }, { "code": null, "e": 35404, "s": 35351, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 35442, "s": 35404, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 35492, "s": 35442, "text": "Implementation of Bit Stuffing and Bit Destuffing" }, { "code": null, "e": 35534, "s": 35492, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 35576, "s": 35534, "text": "BigInt (BIG INTEGERS) in C++ with Example" }, { "code": null, "e": 35622, "s": 35576, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 35677, "s": 35622, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 35718, "s": 35677, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 35757, "s": 35718, "text": "How to install bootstrap in React.js ?" } ]
How to Test your Broadband Speed from Linux Terminal
To install speed test CLI command line, it should require Python ppi. Use the following command to install Python ppi . $ sudo apt-get install python-pip The sample output should be like this – Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libbs2b0 libopusfile0 libqmmp-misc libqmmpui0 libsidplayfp linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic linux-signed-image-4.2.0-27-generic php7.0-opcache Use 'apt-get autoremove' to remove them. The following extra packages will be installed: python-chardet-whl python-colorama python-colorama-whl python-distlib python-distlib-whl python-html5lib python-html5lib-whl python-pip-whl python-requests-whl python-setuptools python-setuptools-whl python-six-whl python-urllib3-whl python-wheel Suggested packages: python-genshi Recommended packages: python-dev-all The following NEW packages will be installed: python-chardet-whl python-colorama python-colorama-whl python-distlib ............................................................................. To instal speedtest-cli, use the following command – $ sudo pip install speedtest-cli The sample output should be like this – Downloading/unpacking speedtest-cli Downloading speedtest_cli-0.3.4-py2.py3-none-any.whl Installing collected packages: speedtest-cli Successfully installed speedtest-cli Cleaning up... To run Speedtest-cli, use the following command – $ speedtest-cli The sample output should be like this – Retrieving speedtest.net configuration... Retrieving speedtest.net server list... Testing from Beam Telecom (183.82.104.71)... Selecting best server based on latency... Hosted by ACT Fibernet (Hyderabad) [10.33 km]: 2.75 ms Testing download speed........................................ Download: 23.32 Mbit/s Testing upload speed.................................................. Upload: 14.30 Mbit/s To get more information about speedtest-cli, use the following command – $ speedtest-cli --help The sample output should be like this – usage: speedtest-cli [-h] [--bytes] [--share] [--simple] [--list] [--server SERVER] [--mini MINI] [--source SOURCE] [--timeout TIMEOUT] [--secure] [--version] Command line interface for testing internet bandwidth using speedtest.net. -------------------------------------------------------------------------- https://github.com/sivel/speedtest-cli optional arguments: -h, --help show this help message and exit --bytes Display values in bytes instead of bits. Does not affect the image generated by --share --share Generate and provide a URL to the speedtest.net share results image --simple Suppress verbose output, only show basic information --list Display a list of speedtest.net servers sorted by distance --server SERVER Specify a server ID to test against --mini MINI URL of the Speedtest Mini server --source SOURCE Source IP address to bind to --timeout TIMEOUT HTTP timeout in seconds. Default 10 --secure Use HTTPS instead of HTTP when communicating with speedtest.net operated servers --version Show the version number and exit Congratulations! Now, you know “How to test your Broadband Speed from Linux Terminal ”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1182, "s": 1062, "text": "To install speed test CLI command line, it should require Python ppi. Use the following command to install Python ppi ." }, { "code": null, "e": 1216, "s": 1182, "text": "$ sudo apt-get install python-pip" }, { "code": null, "e": 1256, "s": 1216, "text": "The sample output should be like this –" }, { "code": null, "e": 2257, "s": 1256, "text": "Building dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n libbs2b0 libopusfile0 libqmmp-misc libqmmpui0 libsidplayfp\n linux-headers-4.2.0-27 linux-headers-4.2.0-27-generic\n linux-image-4.2.0-27-generic linux-image-extra-4.2.0-27-generic\n linux-signed-image-4.2.0-27-generic php7.0-opcache\nUse 'apt-get autoremove' to remove them.\nThe following extra packages will be installed:\n python-chardet-whl python-colorama python-colorama-whl python-distlib\n python-distlib-whl python-html5lib python-html5lib-whl python-pip-whl\n python-requests-whl python-setuptools python-setuptools-whl python-six-whl\n python-urllib3-whl python-wheel\nSuggested packages:\n python-genshi\nRecommended packages:\n python-dev-all\nThe following NEW packages will be installed:\n python-chardet-whl python-colorama python-colorama-whl python-distlib\n............................................................................." }, { "code": null, "e": 2310, "s": 2257, "text": "To instal speedtest-cli, use the following command –" }, { "code": null, "e": 2343, "s": 2310, "text": "$ sudo pip install speedtest-cli" }, { "code": null, "e": 2383, "s": 2343, "text": "The sample output should be like this –" }, { "code": null, "e": 2572, "s": 2383, "text": "Downloading/unpacking speedtest-cli\n Downloading speedtest_cli-0.3.4-py2.py3-none-any.whl\nInstalling collected packages: speedtest-cli\nSuccessfully installed speedtest-cli\nCleaning up..." }, { "code": null, "e": 2622, "s": 2572, "text": "To run Speedtest-cli, use the following command –" }, { "code": null, "e": 2638, "s": 2622, "text": "$ speedtest-cli" }, { "code": null, "e": 2678, "s": 2638, "text": "The sample output should be like this –" }, { "code": null, "e": 3080, "s": 2678, "text": "Retrieving speedtest.net configuration...\nRetrieving speedtest.net server list...\nTesting from Beam Telecom (183.82.104.71)...\nSelecting best server based on latency...\nHosted by ACT Fibernet (Hyderabad) [10.33 km]: 2.75 ms\nTesting download speed........................................\nDownload: 23.32 Mbit/s\nTesting upload speed..................................................\nUpload: 14.30 Mbit/s" }, { "code": null, "e": 3153, "s": 3080, "text": "To get more information about speedtest-cli, use the following command –" }, { "code": null, "e": 3176, "s": 3153, "text": "$ speedtest-cli --help" }, { "code": null, "e": 3216, "s": 3176, "text": "The sample output should be like this –" }, { "code": null, "e": 4381, "s": 3216, "text": "usage: speedtest-cli [-h] [--bytes] [--share] [--simple] [--list]\n[--server SERVER] [--mini MINI] [--source SOURCE]\n[--timeout TIMEOUT] [--secure] [--version]\n\nCommand line interface for testing internet bandwidth using speedtest.net.\n--------------------------------------------------------------------------\nhttps://github.com/sivel/speedtest-cli\n\noptional arguments:\n-h, --help show this help message and exit\n--bytes Display values in bytes instead of bits. Does not affect the image generated by --share\n--share Generate and provide a URL to the speedtest.net share results image\n--simple Suppress verbose output, only show basic information\n--list Display a list of speedtest.net servers sorted by distance\n--server SERVER Specify a server ID to test against\n--mini MINI URL of the Speedtest Mini server\n--source SOURCE Source IP address to bind to\n--timeout TIMEOUT HTTP timeout in seconds. Default 10\n--secure Use HTTPS instead of HTTP when communicating with speedtest.net operated servers\n--version Show the version number and exit" }, { "code": null, "e": 4554, "s": 4381, "text": "Congratulations! Now, you know “How to test your Broadband Speed from Linux Terminal ”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
JSP - Environment Setup
A development environment is where you would develop your JSP programs, test them and finally run them. This tutorial will guide you to setup your JSP development environment which involves the following steps − This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up the PATH environment variable appropriately. You can download SDK from Oracle's Java site − Java SE Downloads. Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and install the SDK in C:\jdk1.5.0_20, you need to add the following line in your C:\autoexec.bat file. set PATH = C:\jdk1.5.0_20\bin;%PATH% set JAVA_HOME = C:\jdk1.5.0_20 Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select Properties, then Advanced, followed by Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you will put the following into your .cshrc file. setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.5.0_20 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. A number of Web Servers that support JavaServer Pages and Servlets development are available in the market. Some web servers can be downloaded for free and Tomcat is one of them. Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine − Download the latest version of Tomcat from https://tomcat.apache.org/. Download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on the Windows machine − %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.sh After a successful startup, the default web-applications included with Tomcat will be available by visiting http://localhost:8080/. Upon execution, you will receive the following output − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/. Tomcat can be stopped by executing the following commands on the Windows machine − %CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-5.5.29\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler. If you are running Windows, you need to put the following lines in your C:\autoexec.bat file. set CATALINA = C:\apache-tomcat-5.5.29 set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH% Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press the OK button. On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file. setenv CATALINA = /usr/local/apache-tomcat-5.5.29 setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH NOTE − Assuming that your development directory is C:\JSPDev (Windows) or /usr/JSPDev (Unix), then you would need to add these directories as well in CLASSPATH. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2343, "s": 2239, "text": "A development environment is where you would develop your JSP programs, test them and finally run them." }, { "code": null, "e": 2451, "s": 2343, "text": "This tutorial will guide you to setup your JSP development environment which involves the following steps −" }, { "code": null, "e": 2603, "s": 2451, "text": "This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up the PATH environment variable appropriately." }, { "code": null, "e": 2669, "s": 2603, "text": "You can download SDK from Oracle's Java site − Java SE Downloads." }, { "code": null, "e": 2958, "s": 2669, "text": "Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 3089, "s": 2958, "text": "If you are running Windows and install the SDK in C:\\jdk1.5.0_20, you need to add the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 3158, "s": 3089, "text": "set PATH = C:\\jdk1.5.0_20\\bin;%PATH%\nset JAVA_HOME = C:\\jdk1.5.0_20\n" }, { "code": null, "e": 3369, "s": 3158, "text": "Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select Properties, then Advanced, followed by Environment Variables. Then, you would update the PATH value and press the OK button." }, { "code": null, "e": 3526, "s": 3369, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you will put the following into your .cshrc file." }, { "code": null, "e": 3612, "s": 3526, "text": "setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH\nsetenv JAVA_HOME /usr/local/jdk1.5.0_20\n" }, { "code": null, "e": 3837, "s": 3612, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java." }, { "code": null, "e": 4016, "s": 3837, "text": "A number of Web Servers that support JavaServer Pages and Servlets development are available in the market. Some web servers can be downloaded for free and Tomcat is one of them." }, { "code": null, "e": 4290, "s": 4016, "text": "Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine −" }, { "code": null, "e": 4361, "s": 4290, "text": "Download the latest version of Tomcat from https://tomcat.apache.org/." }, { "code": null, "e": 4432, "s": 4361, "text": "Download the latest version of Tomcat from https://tomcat.apache.org/." }, { "code": null, "e": 4705, "s": 4432, "text": "Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations." }, { "code": null, "e": 4978, "s": 4705, "text": "Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations." }, { "code": null, "e": 5061, "s": 4978, "text": "Tomcat can be started by executing the following commands on the Windows machine −" }, { "code": null, "e": 5140, "s": 5061, "text": "%CATALINA_HOME%\\bin\\startup.bat\n \nor\n \nC:\\apache-tomcat-5.5.29\\bin\\startup.bat" }, { "code": null, "e": 5243, "s": 5140, "text": "Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 5327, "s": 5243, "text": "$CATALINA_HOME/bin/startup.sh\n \nor\n \n/usr/local/apache-tomcat-5.5.29/bin/startup.sh" }, { "code": null, "e": 5459, "s": 5327, "text": "After a successful startup, the default web-applications included with Tomcat will be available by visiting http://localhost:8080/." }, { "code": null, "e": 5515, "s": 5459, "text": "Upon execution, you will receive the following output −" }, { "code": null, "e": 5685, "s": 5515, "text": "Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/." }, { "code": null, "e": 5768, "s": 5685, "text": "Tomcat can be stopped by executing the following commands on the Windows machine −" }, { "code": null, "e": 5838, "s": 5768, "text": "%CATALINA_HOME%\\bin\\shutdown\nor\n\nC:\\apache-tomcat-5.5.29\\bin\\shutdown" }, { "code": null, "e": 5937, "s": 5838, "text": "Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 6021, "s": 5937, "text": "$CATALINA_HOME/bin/shutdown.sh\n\nor\n\n/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh" }, { "code": null, "e": 6144, "s": 6021, "text": "Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler." }, { "code": null, "e": 6238, "s": 6144, "text": "If you are running Windows, you need to put the following lines in your C:\\autoexec.bat file." }, { "code": null, "e": 6340, "s": 6238, "text": "set CATALINA = C:\\apache-tomcat-5.5.29\nset CLASSPATH = %CATALINA%\\common\\lib\\jsp-api.jar;%CLASSPATH%\n" }, { "code": null, "e": 6549, "s": 6340, "text": "Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press the OK button." }, { "code": null, "e": 6668, "s": 6549, "text": "On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file." }, { "code": null, "e": 6780, "s": 6668, "text": "setenv CATALINA = /usr/local/apache-tomcat-5.5.29\nsetenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH\n" }, { "code": null, "e": 6942, "s": 6780, "text": "NOTE − Assuming that your development directory is C:\\JSPDev (Windows) or /usr/JSPDev (Unix), then you would need to add these directories as well in CLASSPATH." }, { "code": null, "e": 6977, "s": 6942, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 6992, "s": 6977, "text": " Chaand Sheikh" }, { "code": null, "e": 7027, "s": 6992, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 7042, "s": 7027, "text": " Chaand Sheikh" }, { "code": null, "e": 7077, "s": 7042, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7091, "s": 7077, "text": " Karthikeya T" }, { "code": null, "e": 7126, "s": 7091, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7142, "s": 7126, "text": " TELCOMA Global" }, { "code": null, "e": 7175, "s": 7142, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 7191, "s": 7175, "text": " TELCOMA Global" }, { "code": null, "e": 7225, "s": 7191, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 7233, "s": 7225, "text": " Uplatz" }, { "code": null, "e": 7240, "s": 7233, "text": " Print" }, { "code": null, "e": 7251, "s": 7240, "text": " Add Notes" } ]
C# Object Creation of Inherited Class
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces. The derived class inherits the base class member variables and member methods. Therefore, the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list. Here you can see object is created for the inherited class. Live Demo using System; namespace Demo { class Rectangle { protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class Tabletop : Rectangle { private double cost; public Tabletop(double l, double w) : base(l, w) { } public double GetCost() { double cost; cost = GetArea() * 70; return cost; } public void Display() { base.Display(); Console.WriteLine("Cost: {0}", GetCost()); } } class ExecuteRectangle { static void Main(string[] args) { Tabletop t = new Tabletop(3, 8); t.Display(); Console.ReadLine(); } } } Length: 3 Width: 8 Area: 24 Cost: 1680
[ { "code": null, "e": 1217, "s": 1062, "text": "A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces." }, { "code": null, "e": 1471, "s": 1217, "text": "The derived class inherits the base class member variables and member methods. Therefore, the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list." }, { "code": null, "e": 1531, "s": 1471, "text": "Here you can see object is created for the inherited class." }, { "code": null, "e": 1542, "s": 1531, "text": " Live Demo" }, { "code": null, "e": 2546, "s": 1542, "text": "using System;\nnamespace Demo {\n class Rectangle {\n protected double length;\n protected double width;\n public Rectangle(double l, double w) {\n length = l;\n width = w;\n }\n public double GetArea() {\n return length * width;\n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }\n class Tabletop : Rectangle {\n private double cost;\n public Tabletop(double l, double w) : base(l, w) { }\n public double GetCost() {\n double cost;\n cost = GetArea() * 70;\n return cost;\n }\n public void Display() {\n base.Display();\n Console.WriteLine(\"Cost: {0}\", GetCost());\n }\n }\n class ExecuteRectangle {\n static void Main(string[] args) {\n Tabletop t = new Tabletop(3, 8);\n t.Display();\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2585, "s": 2546, "text": "Length: 3\nWidth: 8\nArea: 24\nCost: 1680" } ]
HTTP headers | Access-Control-Allow-Headers. - GeeksforGeeks
19 Nov, 2019 The HTTP Access-Control-Allow-Headers header is a response-type header that is used to indicate the HTTP headers. It can be used during a request and is used in response to a CORS preflight request, that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers, which includes the Access-Control-Request-Headers HTTP header. Syntax: Access-Control-Allow-Headers: <header-name> Note:Multiple headers can be used. Directives: This header accepts two directives described below: <header-name>: It specifies the supported request header. If there are multiple headers in use we separate them using commas. *(wildcard): It is used for requests without HTTP cookies or HTTP authentication information. It should be noted that the Authorization header cannot be wild-carded and needs explicit mentioning. Examples: When there is just one headerAccess-Control-Allow-Headers: Proxy-Authorization Access-Control-Allow-Headers: Proxy-Authorization When there are multiple headersAccess-Control-Allow-Headers: Proxy-Authorization, Max-ForwardsTo check the Access-Control-Allow-Headers header, go to Inspect Element -> Network. Check the response header like below Access-Control-Allow-Headers is highlightedSupported Browsers: The browsers are compatible with HTTP Access-Control-Allow-Headers header are listed below:Google Chrome 4.0Internet Explorer 12.0Firefox 3.5Opera 12.0Safari 4.0Note: *(wildcard) directive may not supported on Safari and Internet Explorer.My Personal Notes arrow_drop_upSave Access-Control-Allow-Headers: Proxy-Authorization, Max-Forwards To check the Access-Control-Allow-Headers header, go to Inspect Element -> Network. Check the response header like below Access-Control-Allow-Headers is highlighted Supported Browsers: The browsers are compatible with HTTP Access-Control-Allow-Headers header are listed below: Google Chrome 4.0 Internet Explorer 12.0 Firefox 3.5 Opera 12.0 Safari 4.0 Note: *(wildcard) directive may not supported on Safari and Internet Explorer. HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function Top 10 Angular Libraries For Web Developers Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Set the value of an input field in JavaScript How to Insert Form Data into Database using PHP ? Client-Server Model How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24191, "s": 24163, "text": "\n19 Nov, 2019" }, { "code": null, "e": 24565, "s": 24191, "text": "The HTTP Access-Control-Allow-Headers header is a response-type header that is used to indicate the HTTP headers. It can be used during a request and is used in response to a CORS preflight request, that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers, which includes the Access-Control-Request-Headers HTTP header." }, { "code": null, "e": 24573, "s": 24565, "text": "Syntax:" }, { "code": null, "e": 24617, "s": 24573, "text": "Access-Control-Allow-Headers: <header-name>" }, { "code": null, "e": 24652, "s": 24617, "text": "Note:Multiple headers can be used." }, { "code": null, "e": 24716, "s": 24652, "text": "Directives: This header accepts two directives described below:" }, { "code": null, "e": 24842, "s": 24716, "text": "<header-name>: It specifies the supported request header. If there are multiple headers in use we separate them using commas." }, { "code": null, "e": 25038, "s": 24842, "text": "*(wildcard): It is used for requests without HTTP cookies or HTTP authentication information. It should be noted that the Authorization header cannot be wild-carded and needs explicit mentioning." }, { "code": null, "e": 25048, "s": 25038, "text": "Examples:" }, { "code": null, "e": 25127, "s": 25048, "text": "When there is just one headerAccess-Control-Allow-Headers: Proxy-Authorization" }, { "code": null, "e": 25177, "s": 25127, "text": "Access-Control-Allow-Headers: Proxy-Authorization" }, { "code": null, "e": 25730, "s": 25177, "text": "When there are multiple headersAccess-Control-Allow-Headers: Proxy-Authorization, Max-ForwardsTo check the Access-Control-Allow-Headers header, go to Inspect Element -> Network. Check the response header like below Access-Control-Allow-Headers is highlightedSupported Browsers: The browsers are compatible with HTTP Access-Control-Allow-Headers header are listed below:Google Chrome 4.0Internet Explorer 12.0Firefox 3.5Opera 12.0Safari 4.0Note: *(wildcard) directive may not supported on Safari and Internet Explorer.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 25794, "s": 25730, "text": "Access-Control-Allow-Headers: Proxy-Authorization, Max-Forwards" }, { "code": null, "e": 25959, "s": 25794, "text": "To check the Access-Control-Allow-Headers header, go to Inspect Element -> Network. Check the response header like below Access-Control-Allow-Headers is highlighted" }, { "code": null, "e": 26071, "s": 25959, "text": "Supported Browsers: The browsers are compatible with HTTP Access-Control-Allow-Headers header are listed below:" }, { "code": null, "e": 26089, "s": 26071, "text": "Google Chrome 4.0" }, { "code": null, "e": 26112, "s": 26089, "text": "Internet Explorer 12.0" }, { "code": null, "e": 26124, "s": 26112, "text": "Firefox 3.5" }, { "code": null, "e": 26135, "s": 26124, "text": "Opera 12.0" }, { "code": null, "e": 26146, "s": 26135, "text": "Safari 4.0" }, { "code": null, "e": 26225, "s": 26146, "text": "Note: *(wildcard) directive may not supported on Safari and Internet Explorer." }, { "code": null, "e": 26238, "s": 26225, "text": "HTTP-headers" }, { "code": null, "e": 26245, "s": 26238, "text": "Picked" }, { "code": null, "e": 26262, "s": 26245, "text": "Web Technologies" }, { "code": null, "e": 26360, "s": 26262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26369, "s": 26360, "text": "Comments" }, { "code": null, "e": 26382, "s": 26369, "text": "Old Comments" }, { "code": null, "e": 26419, "s": 26382, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26463, "s": 26419, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 26508, "s": 26463, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26568, "s": 26508, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26614, "s": 26568, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 26664, "s": 26614, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26684, "s": 26664, "text": "Client-Server Model" }, { "code": null, "e": 26727, "s": 26684, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26799, "s": 26727, "text": "Differences between Functional Components and Class Components in React" } ]
A Quick Introduction to Google Earth Engine | by Willy Hagi | Towards Data Science
Google Earth Engine (GEE) is a platform for cloud-based geospatial applications with tons of data from satellites, including the ones from the famous Landsat program to several climate datasets. The best thing is that the platform is available to anyone with enough interest and a relatively decent internet connection, making environmental processing easy to use and available to those who need it the most. There are several ways to use GEE and each one has its advantages and disadvantages. While the Javascript-based Code Editor is probably the most used tool and the Explorer is perfect for a casual look, here you’ll put your hands on the Python API. In the meanwhile, feel free to explore the available datasets and many successful case studies. Basically, any person with a Google account can sign up to use GEE and the installation of the necessary packages is quite straightforward. After signing up, you can install the Earth Engine Python API with pip: pip install earthengine-api After that, you need to set up your authentication credentials on your computer. The entire (not so long) process is described in detail in the manual and you’re encouraged to test the installation as described in the end. After these quick steps, you’re ready to go with an immense collection of datasets ready to be explored. The Earth Engine Package is simply called ee, and with that, you can start to set up your toolbox. Apart from ee, here in this tutorial, you’ll also need Folium for interactive maps and geehydro, which is intended to be a package for inundation dynamics in the GEE platform but is extraordinarily useful as it emulates some of the functions from the Javascript API. You can install these other packages with pip as well: pip install foliumpip install geehydro To import all the packages: import ee import foliumimport geehydrofrom datetime import datetime as dtfrom IPython.display import Image When you use the API, the first thing you need to do is to initialize the connection to the server: # initialize the connection to the server>>> ee.Initialize() With satellite imagery you can investigate any spot on Earth, even remote places where you could never set foot on (or at least you shouldn’t). In this tutorial, you’ll explore the recent conditions in the Ituna/Itatá Indigenous Land in the Brazilian state of Pará. This protected land is home to a few isolated indigenous tribes and is one of the places in the Amazon where mining, logging and ranching are absolutely illegal practices. Unfortunately, according to the Brazilian National Institute of Space Research (INPE) this place also became the most affected of all during last year by the advance of the agricultural border in Brazil, menacing the lives of the tribes who live there and the biodiversity within. Aided by Folium, you can take a look at where this distant place is: # the Ituna/Itatá Indigenous Land in Brazil.Ituna_map = folium.Map(location=[-4.06738, -52.034], zoom_start=10)>>> Ituna_map Landsat 8 is the most recent addition to the long-running Landsat Program and it’s been in orbit since 2013, continuously estimating the land-surface conditions around the globe. Applications of Landsat imagery are widely known and well-established in the fields of agronomy, environmental conservation and changes related to land-use. There are several technical details about Landsat 8, but the basics you should know is that it collects multispectral spatial information in a medium resolution, with bands a range of 15 to 100 meters resolutions in 11 different bands of the electromagnetic spectrum. It also has a revisit time of 16 days, which means you have a new image of a particular place every 16 days cycle. With ee, you can have access to the entire Landsat 8 collection with a single line of code: landsat = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR") Each collection has its own id and you can find them in the GEE catalog. Above, the EE snippet id for the Landsat 8 Surface Reflectance Tier 1 product is "LANDSAT/LC08/C01/T1_SR" as described in the catalog. This will get you the entire collection of imagery of the entire world, so you’ll have to tailor it out according to both your area and time of interests. For the area, you’ll set up a rectangle around the Ituna/Itatá Land using latitude/longitude information with ee.Geometry.Rectangle: # setting the Area of Interest (AOI)Ituna_AOI = ee.Geometry.Rectangle([-51.84448, -3.92180, -52.23999, -4.38201]) The .filterBounds() method allows you to select the AOI you defined above: # filter arealandsat_AOI = landsat.filterBounds(Ituna_AOI) Another detail is that you might not be interested in the entire time span of the collection, but in a particular period. For the Ituna/Itatá Land, you’ll select a brief period of time during the dry season in the region in 2019. Why the dry season? Clouds are a major problem for satellite imagery analysis and in the Amazon, this problem is severely increased, so selecting months without intense rainfall and cloud cover is a nice strategy. Also, these are the months where deforestation goes rampant and the (human-induced) fire season starts. # choose dateslandsat = landsat.filterDate('2019-07-01','2019-12-01') You can easily .getInfo() about the Landsat collection above or any particular information you might be interested in. For the landsat_AOI collection tailored above, it will get you all the information there’s to know about it, which could be a little messy and too technical. >>> landsat_AOI.getInfo() It’s possible to be more selective and filter out the information you don’t want. Assuming you just need to know how many images from Landsat you got from the period of time selected above, simply do: >>> print('Total number:', landsat_AOI.size().getInfo())Total number: 9 Another example is to show how each band from Landsat 8 is named — something useful for the next steps: # the names of each Landsat 8 band>>> landsat_AOI.first().bandNames().getInfo()['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10', 'B11', 'sr_aerosol', 'pixel_qa', 'radsat_qa'] It’s possible to be more selective and set up the collection according to a particular criterion. In this tutorial, you’ll select the least cloudy image from the landsat_AOI collection according to its 'CLOUD_COVER' id. # the least cloudy imageleast_cloudy = ee.Image(landsat_AOI.sort('CLOUD_COVER').first())# how cloudy is it?>>> print('Cloud Cover (%):', least_cloudy.get('CLOUD_COVER').getInfo())Cloud Cover (%): 0 Conveniently so, satellite imagery with 0% of 'CLOUD_COVER' in the Amazon is something hard to see. This one is perfect, but when it was taken? # when was this image taken?date = ee.Date(least_cloudy.get('system:time_start'))time = date.getInfo()['value']/1000.>>> dt.utcfromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S')'2019-08-11 13:36:22' August is one of the driest months of the dry season in the Amazon, so it comes as no surprise that it has 0% 'CLOUD_COVER'. A common practice when doing an analysis with satellite imagery is to combine different bands. Since each band represents a portion of the electromagnetic spectrum, combining them allows different views of the same surface due to the spectral signature of types of vegetation, water, soil and things like that. The easiest one is the Red-Green-Blue (RGB) composite and when using Landsat 8 imagery, you’ll need to use Bands 4 (Red), 3 (Green) and 2 (Blue). The Javascript-based code editor easily allows interactive visualization using Map.AddLayer(), but unfortunately, this is not available for the standard Python API. A simple, static map can be made with both the .getThumbURL() module from ee and the native .display() module from IPython: parameters = {'min': 0, 'max': 1000, 'dimensions': 512, 'bands': ['B4', 'B3', 'B2'], 'region': Ituna_AOI} >>> Image(url = least_cloudy.getThumbUrl(parameters)) The parameters variable stores the options you can explore when analyzing satellite imagery with ee. It works in the same way as the Javascript API and you’re encouraged to combine different bands and tweak it out to get different visualizations of the same data. For the purpose of the tutorial, the simple RGB composite does justice to investigate the advance of illegal logging and other practices in a land where this is not supposed to happen. In the image above, everything that is not in a strong green tone is against the law. This happened in mid-August of 2019, but as February of our current year of 2020 the situation is, unfortunately, much worse. There are more quantitative ways to investigate the land-use changes and deforestation. Perhaps the best-known method is the use of the Normalized Difference Vegetation Index (NDVI), widely present in several land management, agriculture and conservation studies. NDVI needs information from the Near-Infrared (NIR) and Visible (VIS) bands, which for Landsat 8 are the bands 5 and 4. The calculation is simply NDVI = (NIR-VIS)/(NIR+VIS), but the insights from it can be huge. It ranges from -1 to 1 or 0 to 1 in some more classic studies. A pixel with a negative or 0 value could be many things, like a river body or a severely degraded land, while a pixel close to 1 is certainly a dense portion of vegetation. Since this is a common practice, you can quickly calculate any Normalized Difference Index (NDVI is not the only one)with .normalizedDifference: ndvi = least_cloudy.normalizedDifference(['B5', 'B4']) After this, you’ll certainly wish to visualize it on a pretty map. While you already know the native way, geehydro allows you to plot an interactive map with Folium just like the Code Editor does with Map.AddLayer(): palette = ['red', 'yellow', 'green']ndvi_parameters = {'min': 0, 'max': 1, 'dimensions': 512, 'palette': palette, 'region': Ituna_AOI}Ituna_map.addLayer(ndvi, ndvi_parameters)Ituna_map The use of geehydro allows an even greater degree of reproducibility between the Javascript and Python API, building a large bridge between often two separate kinds of people. If you don’t know a word about Javascript, now you can understand the code in the several GEE tutorials available around the internet. GEE is an excellent tool to learn how to use satellite imagery for good and the possibilities are huge. Land-use changes studies, sustainable farming and monitoring of sensitive areas like the Ituna/Itatá are available for anyone with a good internet connection and enough interest to go for it. The flexible Python API and the usefulness of geehydro can be combined to quickly set up the platform to use. With it, tons of different datasets and a wealth of information ready to be discovered. What a time to be alive. The interactive Jupyter Notebook for this tutorial is freely available in my Climate Data Science repository.
[ { "code": null, "e": 581, "s": 172, "text": "Google Earth Engine (GEE) is a platform for cloud-based geospatial applications with tons of data from satellites, including the ones from the famous Landsat program to several climate datasets. The best thing is that the platform is available to anyone with enough interest and a relatively decent internet connection, making environmental processing easy to use and available to those who need it the most." }, { "code": null, "e": 925, "s": 581, "text": "There are several ways to use GEE and each one has its advantages and disadvantages. While the Javascript-based Code Editor is probably the most used tool and the Explorer is perfect for a casual look, here you’ll put your hands on the Python API. In the meanwhile, feel free to explore the available datasets and many successful case studies." }, { "code": null, "e": 1137, "s": 925, "text": "Basically, any person with a Google account can sign up to use GEE and the installation of the necessary packages is quite straightforward. After signing up, you can install the Earth Engine Python API with pip:" }, { "code": null, "e": 1165, "s": 1137, "text": "pip install earthengine-api" }, { "code": null, "e": 1493, "s": 1165, "text": "After that, you need to set up your authentication credentials on your computer. The entire (not so long) process is described in detail in the manual and you’re encouraged to test the installation as described in the end. After these quick steps, you’re ready to go with an immense collection of datasets ready to be explored." }, { "code": null, "e": 1914, "s": 1493, "text": "The Earth Engine Package is simply called ee, and with that, you can start to set up your toolbox. Apart from ee, here in this tutorial, you’ll also need Folium for interactive maps and geehydro, which is intended to be a package for inundation dynamics in the GEE platform but is extraordinarily useful as it emulates some of the functions from the Javascript API. You can install these other packages with pip as well:" }, { "code": null, "e": 1953, "s": 1914, "text": "pip install foliumpip install geehydro" }, { "code": null, "e": 1981, "s": 1953, "text": "To import all the packages:" }, { "code": null, "e": 2088, "s": 1981, "text": "import ee import foliumimport geehydrofrom datetime import datetime as dtfrom IPython.display import Image" }, { "code": null, "e": 2188, "s": 2088, "text": "When you use the API, the first thing you need to do is to initialize the connection to the server:" }, { "code": null, "e": 2249, "s": 2188, "text": "# initialize the connection to the server>>> ee.Initialize()" }, { "code": null, "e": 2970, "s": 2249, "text": "With satellite imagery you can investigate any spot on Earth, even remote places where you could never set foot on (or at least you shouldn’t). In this tutorial, you’ll explore the recent conditions in the Ituna/Itatá Indigenous Land in the Brazilian state of Pará. This protected land is home to a few isolated indigenous tribes and is one of the places in the Amazon where mining, logging and ranching are absolutely illegal practices. Unfortunately, according to the Brazilian National Institute of Space Research (INPE) this place also became the most affected of all during last year by the advance of the agricultural border in Brazil, menacing the lives of the tribes who live there and the biodiversity within." }, { "code": null, "e": 3039, "s": 2970, "text": "Aided by Folium, you can take a look at where this distant place is:" }, { "code": null, "e": 3165, "s": 3039, "text": "# the Ituna/Itatá Indigenous Land in Brazil.Ituna_map = folium.Map(location=[-4.06738, -52.034], zoom_start=10)>>> Ituna_map" }, { "code": null, "e": 3501, "s": 3165, "text": "Landsat 8 is the most recent addition to the long-running Landsat Program and it’s been in orbit since 2013, continuously estimating the land-surface conditions around the globe. Applications of Landsat imagery are widely known and well-established in the fields of agronomy, environmental conservation and changes related to land-use." }, { "code": null, "e": 3884, "s": 3501, "text": "There are several technical details about Landsat 8, but the basics you should know is that it collects multispectral spatial information in a medium resolution, with bands a range of 15 to 100 meters resolutions in 11 different bands of the electromagnetic spectrum. It also has a revisit time of 16 days, which means you have a new image of a particular place every 16 days cycle." }, { "code": null, "e": 3976, "s": 3884, "text": "With ee, you can have access to the entire Landsat 8 collection with a single line of code:" }, { "code": null, "e": 4031, "s": 3976, "text": "landsat = ee.ImageCollection(\"LANDSAT/LC08/C01/T1_SR\")" }, { "code": null, "e": 4239, "s": 4031, "text": "Each collection has its own id and you can find them in the GEE catalog. Above, the EE snippet id for the Landsat 8 Surface Reflectance Tier 1 product is \"LANDSAT/LC08/C01/T1_SR\" as described in the catalog." }, { "code": null, "e": 4528, "s": 4239, "text": "This will get you the entire collection of imagery of the entire world, so you’ll have to tailor it out according to both your area and time of interests. For the area, you’ll set up a rectangle around the Ituna/Itatá Land using latitude/longitude information with ee.Geometry.Rectangle:" }, { "code": null, "e": 4676, "s": 4528, "text": "# setting the Area of Interest (AOI)Ituna_AOI = ee.Geometry.Rectangle([-51.84448, -3.92180, -52.23999, -4.38201])" }, { "code": null, "e": 4751, "s": 4676, "text": "The .filterBounds() method allows you to select the AOI you defined above:" }, { "code": null, "e": 4810, "s": 4751, "text": "# filter arealandsat_AOI = landsat.filterBounds(Ituna_AOI)" }, { "code": null, "e": 5359, "s": 4810, "text": "Another detail is that you might not be interested in the entire time span of the collection, but in a particular period. For the Ituna/Itatá Land, you’ll select a brief period of time during the dry season in the region in 2019. Why the dry season? Clouds are a major problem for satellite imagery analysis and in the Amazon, this problem is severely increased, so selecting months without intense rainfall and cloud cover is a nice strategy. Also, these are the months where deforestation goes rampant and the (human-induced) fire season starts." }, { "code": null, "e": 5429, "s": 5359, "text": "# choose dateslandsat = landsat.filterDate('2019-07-01','2019-12-01')" }, { "code": null, "e": 5706, "s": 5429, "text": "You can easily .getInfo() about the Landsat collection above or any particular information you might be interested in. For the landsat_AOI collection tailored above, it will get you all the information there’s to know about it, which could be a little messy and too technical." }, { "code": null, "e": 5732, "s": 5706, "text": ">>> landsat_AOI.getInfo()" }, { "code": null, "e": 5933, "s": 5732, "text": "It’s possible to be more selective and filter out the information you don’t want. Assuming you just need to know how many images from Landsat you got from the period of time selected above, simply do:" }, { "code": null, "e": 6005, "s": 5933, "text": ">>> print('Total number:', landsat_AOI.size().getInfo())Total number: 9" }, { "code": null, "e": 6109, "s": 6005, "text": "Another example is to show how each band from Landsat 8 is named — something useful for the next steps:" }, { "code": null, "e": 6284, "s": 6109, "text": "# the names of each Landsat 8 band>>> landsat_AOI.first().bandNames().getInfo()['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10', 'B11', 'sr_aerosol', 'pixel_qa', 'radsat_qa']" }, { "code": null, "e": 6504, "s": 6284, "text": "It’s possible to be more selective and set up the collection according to a particular criterion. In this tutorial, you’ll select the least cloudy image from the landsat_AOI collection according to its 'CLOUD_COVER' id." }, { "code": null, "e": 6702, "s": 6504, "text": "# the least cloudy imageleast_cloudy = ee.Image(landsat_AOI.sort('CLOUD_COVER').first())# how cloudy is it?>>> print('Cloud Cover (%):', least_cloudy.get('CLOUD_COVER').getInfo())Cloud Cover (%): 0" }, { "code": null, "e": 6846, "s": 6702, "text": "Conveniently so, satellite imagery with 0% of 'CLOUD_COVER' in the Amazon is something hard to see. This one is perfect, but when it was taken?" }, { "code": null, "e": 7044, "s": 6846, "text": "# when was this image taken?date = ee.Date(least_cloudy.get('system:time_start'))time = date.getInfo()['value']/1000.>>> dt.utcfromtimestamp(time).strftime('%Y-%m-%d %H:%M:%S')'2019-08-11 13:36:22'" }, { "code": null, "e": 7169, "s": 7044, "text": "August is one of the driest months of the dry season in the Amazon, so it comes as no surprise that it has 0% 'CLOUD_COVER'." }, { "code": null, "e": 7626, "s": 7169, "text": "A common practice when doing an analysis with satellite imagery is to combine different bands. Since each band represents a portion of the electromagnetic spectrum, combining them allows different views of the same surface due to the spectral signature of types of vegetation, water, soil and things like that. The easiest one is the Red-Green-Blue (RGB) composite and when using Landsat 8 imagery, you’ll need to use Bands 4 (Red), 3 (Green) and 2 (Blue)." }, { "code": null, "e": 7915, "s": 7626, "text": "The Javascript-based code editor easily allows interactive visualization using Map.AddLayer(), but unfortunately, this is not available for the standard Python API. A simple, static map can be made with both the .getThumbURL() module from ee and the native .display() module from IPython:" }, { "code": null, "e": 8139, "s": 7915, "text": "parameters = {'min': 0, 'max': 1000, 'dimensions': 512, 'bands': ['B4', 'B3', 'B2'], 'region': Ituna_AOI} >>> Image(url = least_cloudy.getThumbUrl(parameters))" }, { "code": null, "e": 8403, "s": 8139, "text": "The parameters variable stores the options you can explore when analyzing satellite imagery with ee. It works in the same way as the Javascript API and you’re encouraged to combine different bands and tweak it out to get different visualizations of the same data." }, { "code": null, "e": 8800, "s": 8403, "text": "For the purpose of the tutorial, the simple RGB composite does justice to investigate the advance of illegal logging and other practices in a land where this is not supposed to happen. In the image above, everything that is not in a strong green tone is against the law. This happened in mid-August of 2019, but as February of our current year of 2020 the situation is, unfortunately, much worse." }, { "code": null, "e": 9064, "s": 8800, "text": "There are more quantitative ways to investigate the land-use changes and deforestation. Perhaps the best-known method is the use of the Normalized Difference Vegetation Index (NDVI), widely present in several land management, agriculture and conservation studies." }, { "code": null, "e": 9512, "s": 9064, "text": "NDVI needs information from the Near-Infrared (NIR) and Visible (VIS) bands, which for Landsat 8 are the bands 5 and 4. The calculation is simply NDVI = (NIR-VIS)/(NIR+VIS), but the insights from it can be huge. It ranges from -1 to 1 or 0 to 1 in some more classic studies. A pixel with a negative or 0 value could be many things, like a river body or a severely degraded land, while a pixel close to 1 is certainly a dense portion of vegetation." }, { "code": null, "e": 9657, "s": 9512, "text": "Since this is a common practice, you can quickly calculate any Normalized Difference Index (NDVI is not the only one)with .normalizedDifference:" }, { "code": null, "e": 9712, "s": 9657, "text": "ndvi = least_cloudy.normalizedDifference(['B5', 'B4'])" }, { "code": null, "e": 9929, "s": 9712, "text": "After this, you’ll certainly wish to visualize it on a pretty map. While you already know the native way, geehydro allows you to plot an interactive map with Folium just like the Code Editor does with Map.AddLayer():" }, { "code": null, "e": 10186, "s": 9929, "text": "palette = ['red', 'yellow', 'green']ndvi_parameters = {'min': 0, 'max': 1, 'dimensions': 512, 'palette': palette, 'region': Ituna_AOI}Ituna_map.addLayer(ndvi, ndvi_parameters)Ituna_map" }, { "code": null, "e": 10497, "s": 10186, "text": "The use of geehydro allows an even greater degree of reproducibility between the Javascript and Python API, building a large bridge between often two separate kinds of people. If you don’t know a word about Javascript, now you can understand the code in the several GEE tutorials available around the internet." }, { "code": null, "e": 11017, "s": 10497, "text": "GEE is an excellent tool to learn how to use satellite imagery for good and the possibilities are huge. Land-use changes studies, sustainable farming and monitoring of sensitive areas like the Ituna/Itatá are available for anyone with a good internet connection and enough interest to go for it. The flexible Python API and the usefulness of geehydro can be combined to quickly set up the platform to use. With it, tons of different datasets and a wealth of information ready to be discovered. What a time to be alive." } ]
Set find() function in C++ programming STL
In this article we are going to discuss the set::find() function in C++ STL, their syntax, working and their return values. Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in a set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees. find() function is an inbuilt function in C++ STL, which is defined in header file. This function is used to find an element or a value in a set container. find() returns an iterator which points to the position of the element which is searched. If the element is not present in the set, then it returns the element just after the last element of the set container. Set1.find(const type_t& element); This function accepts one parameter, i.e., element which is to be found. This function returns an iterator which points to the element which is to be found. Input: set<int> myset = {10, 20, 40, 80, 90}; myset.find(40); Output: element found Live Demo #include <bits/stdc++.h> using namespace std; int main(){ set<int> mySet; mySet.insert(10); mySet.insert(20); mySet.insert(90); mySet.insert(80); mySet.insert(40); auto temp = mySet.find(40); cout<<"Elements after 40 are: "; for (auto i = temp; i != mySet.end(); i++) cout << *i << " "; return 0; } If we run the above code then it will generate the following output − Elements after 40 are: 40 80 90 Live Demo #include <iostream> #include <set> int main (){ std::set<int> mySet; std::set<int>::iterator i; for(int i=1; i<=4; i++) mySet.insert(i*2); i = mySet.find(6); mySet.erase(i); mySet.erase(mySet.find(4)); std::cout<<"elements are : "; for (i = mySet.begin(); i != mySet.end(); ++i) std::cout << ' ' << *i; std::cout << '\n'; return 0; } If we run the above code then it will generate the following output − Elements are : 2 8
[ { "code": null, "e": 1186, "s": 1062, "text": "In this article we are going to discuss the set::find() function in C++ STL, their syntax, working and their return values." }, { "code": null, "e": 1521, "s": 1186, "text": "Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in a set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees." }, { "code": null, "e": 1887, "s": 1521, "text": "find() function is an inbuilt function in C++ STL, which is defined in header file. This function is used to find an element or a value in a set container. find() returns an iterator which points to the position of the element which is searched. If the element is not present in the set, then it returns the element just after the last element of the set container." }, { "code": null, "e": 1921, "s": 1887, "text": "Set1.find(const type_t& element);" }, { "code": null, "e": 1994, "s": 1921, "text": "This function accepts one parameter, i.e., element which is to be found." }, { "code": null, "e": 2078, "s": 1994, "text": "This function returns an iterator which points to the element which is to be found." }, { "code": null, "e": 2162, "s": 2078, "text": "Input: set<int> myset = {10, 20, 40, 80, 90};\nmyset.find(40);\nOutput: element found" }, { "code": null, "e": 2173, "s": 2162, "text": " Live Demo" }, { "code": null, "e": 2508, "s": 2173, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n set<int> mySet;\n mySet.insert(10);\n mySet.insert(20);\n mySet.insert(90);\n mySet.insert(80);\n mySet.insert(40);\n auto temp = mySet.find(40);\n cout<<\"Elements after 40 are: \";\n for (auto i = temp; i != mySet.end(); i++)\n cout << *i << \" \";\n return 0;\n}" }, { "code": null, "e": 2578, "s": 2508, "text": "If we run the above code then it will generate the following output −" }, { "code": null, "e": 2610, "s": 2578, "text": "Elements after 40 are: 40 80 90" }, { "code": null, "e": 2621, "s": 2610, "text": " Live Demo" }, { "code": null, "e": 2997, "s": 2621, "text": "#include <iostream>\n#include <set>\nint main (){\n std::set<int> mySet;\n std::set<int>::iterator i;\n for(int i=1; i<=4; i++)\n mySet.insert(i*2);\n i = mySet.find(6);\n mySet.erase(i);\n mySet.erase(mySet.find(4));\n std::cout<<\"elements are : \";\n for (i = mySet.begin(); i != mySet.end(); ++i)\n std::cout << ' ' << *i;\n std::cout << '\\n';\n return 0;\n}" }, { "code": null, "e": 3067, "s": 2997, "text": "If we run the above code then it will generate the following output −" }, { "code": null, "e": 3086, "s": 3067, "text": "Elements are : 2 8" } ]
Node.js http.server.keepAliveTimeout Property - GeeksforGeeks
20 Jan, 2021 The http.server.keepAliveTimeout is an inbuilt application programming interface of class Server within http module which is used to get the number of milliseconds of inactivity a server needs to wait for additional incoming data. Syntax: server.keepAliveTimeout Parameters: This Api does not accept any argument as a parameter. Return Value: This Method returns the number of milliseconds of inactivity a server needs to wait for additional incoming data. Example 1: Filename: index.js Javascript // Node.js program to demonstrate the // server.keepAliveTimeout property // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer( function(request, response){ // Getting the reference of the // underlying socket object // by using socket API const value = response.socket; // Display result // by using end() api response.end( "Socket buffersize : " + value.bufferSize, 'utf8', () => { console.log("displaying the result..."); // Closing server // by using close() api httpServer.close(()=>{ console.log("server is closed") }) }); }); // Listening to http Server // by using listen() apihttpServer.listen(PORT, () => { console.log("Server is running at port 3000..."); }); // Getting keep alive timeout value// by using keepAliveTimeout apiconst v = httpServer.keepAliveTimeout // Display the resultconsole.log('keep alive time out value :-' + v) Run index.js file using below command: node index.js Console Output: keep alive time out value :-5000 Server is running at port 3000... displaying the result... displaying the result... server is closed server is closed Browser Output: Paste the localhost address http://localhost:3000/ in the search bar of the browser. Socket buffersize : 0 Example 2: Filename: index.js Javascript // Node.js program to demonstrate the // server.keepAliveTimeout property // Importing http module var http = require('http'); // Request and response handler const http2Handlers = (request, response) => { // Getting the reference of the // underlying socket object // by using socket API const value = response.socket; // Display result // by using end() api response.end( "Socket local address : " + value.localAddress, 'utf8', () => { console.log("displaying the result..."); // Closing server // by using close() api httpServer.close(()=>{ console.log("server is closed") }) });}; // Listening to http Server // by using listen() apivar httpServer = http.createServer( http2Handlers).listen(3000, () => { console.log("Server is running at port 3000..."); }); // Getting keep alive timeout value// by using keepAliveTimeout propertyconst v = httpServer.keepAliveTimeout // Display the resultconsole.log('keep alive time out value :-' + v) Run index.js file using below command: node index.js Console Output: keep alive time out value :-5000 Server is running at port 3000... displaying the result... displaying the result... server is closed server is closed Browser Output: Paste the localhost address http://localhost:3000/ in the search bar of the browser. Socket local address : ::1 Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_server_keepalivetimeout Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Difference between npm i and npm ci in Node.js Mongoose Populate() Method Roadmap to Become a Web Developer in 2022 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? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24842, "s": 24814, "text": "\n20 Jan, 2021" }, { "code": null, "e": 25073, "s": 24842, "text": "The http.server.keepAliveTimeout is an inbuilt application programming interface of class Server within http module which is used to get the number of milliseconds of inactivity a server needs to wait for additional incoming data." }, { "code": null, "e": 25081, "s": 25073, "text": "Syntax:" }, { "code": null, "e": 25105, "s": 25081, "text": "server.keepAliveTimeout" }, { "code": null, "e": 25171, "s": 25105, "text": "Parameters: This Api does not accept any argument as a parameter." }, { "code": null, "e": 25299, "s": 25171, "text": "Return Value: This Method returns the number of milliseconds of inactivity a server needs to wait for additional incoming data." }, { "code": null, "e": 25329, "s": 25299, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 25340, "s": 25329, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // server.keepAliveTimeout property // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer( function(request, response){ // Getting the reference of the // underlying socket object // by using socket API const value = response.socket; // Display result // by using end() api response.end( \"Socket buffersize : \" + value.bufferSize, 'utf8', () => { console.log(\"displaying the result...\"); // Closing server // by using close() api httpServer.close(()=>{ console.log(\"server is closed\") }) }); }); // Listening to http Server // by using listen() apihttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\"); }); // Getting keep alive timeout value// by using keepAliveTimeout apiconst v = httpServer.keepAliveTimeout // Display the resultconsole.log('keep alive time out value :-' + v)", "e": 26385, "s": 25340, "text": null }, { "code": null, "e": 26424, "s": 26385, "text": "Run index.js file using below command:" }, { "code": null, "e": 26438, "s": 26424, "text": "node index.js" }, { "code": null, "e": 26454, "s": 26438, "text": "Console Output:" }, { "code": null, "e": 26605, "s": 26454, "text": "keep alive time out value :-5000\nServer is running at port 3000...\ndisplaying the result...\ndisplaying the result...\nserver is closed\nserver is closed" }, { "code": null, "e": 26706, "s": 26605, "text": "Browser Output: Paste the localhost address http://localhost:3000/ in the search bar of the browser." }, { "code": null, "e": 26728, "s": 26706, "text": "Socket buffersize : 0" }, { "code": null, "e": 26758, "s": 26728, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 26769, "s": 26758, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // server.keepAliveTimeout property // Importing http module var http = require('http'); // Request and response handler const http2Handlers = (request, response) => { // Getting the reference of the // underlying socket object // by using socket API const value = response.socket; // Display result // by using end() api response.end( \"Socket local address : \" + value.localAddress, 'utf8', () => { console.log(\"displaying the result...\"); // Closing server // by using close() api httpServer.close(()=>{ console.log(\"server is closed\") }) });}; // Listening to http Server // by using listen() apivar httpServer = http.createServer( http2Handlers).listen(3000, () => { console.log(\"Server is running at port 3000...\"); }); // Getting keep alive timeout value// by using keepAliveTimeout propertyconst v = httpServer.keepAliveTimeout // Display the resultconsole.log('keep alive time out value :-' + v)", "e": 27793, "s": 26769, "text": null }, { "code": null, "e": 27832, "s": 27793, "text": "Run index.js file using below command:" }, { "code": null, "e": 27846, "s": 27832, "text": "node index.js" }, { "code": null, "e": 27862, "s": 27846, "text": "Console Output:" }, { "code": null, "e": 28013, "s": 27862, "text": "keep alive time out value :-5000\nServer is running at port 3000...\ndisplaying the result...\ndisplaying the result...\nserver is closed\nserver is closed" }, { "code": null, "e": 28114, "s": 28013, "text": "Browser Output: Paste the localhost address http://localhost:3000/ in the search bar of the browser." }, { "code": null, "e": 28141, "s": 28114, "text": "Socket local address : ::1" }, { "code": null, "e": 28237, "s": 28141, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_server_keepalivetimeout" }, { "code": null, "e": 28253, "s": 28237, "text": "Node.js-Methods" }, { "code": null, "e": 28261, "s": 28253, "text": "Node.js" }, { "code": null, "e": 28278, "s": 28261, "text": "Web Technologies" }, { "code": null, "e": 28376, "s": 28278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28385, "s": 28376, "text": "Comments" }, { "code": null, "e": 28398, "s": 28385, "text": "Old Comments" }, { "code": null, "e": 28435, "s": 28398, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28467, "s": 28435, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 28498, "s": 28467, "text": "Express.js req.params Property" }, { "code": null, "e": 28545, "s": 28498, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 28572, "s": 28545, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28614, "s": 28572, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28676, "s": 28614, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28719, "s": 28676, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28769, "s": 28719, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Access to file download dialog in Firefox in Selenium.
We can access file download dialog in Firefox in Selenium. For this we have to first modify the default directory where the downloaded file gets stored. This is done by the addpreference method. p.addPreference("browser.download.folderList", 2); Then, define the new path of the download directory. Finally, we shall ignore the save to disk and open file options in dialog for the file types via their MIME code. The addPreference method can be called with the help of FirefoxOptions class. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import java.util.concurrent.TimeUnit; public class FileDwnloadWithoutDialg{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); // instance of FirefoxOptions class FirefoxOptions profile = new FirefoxOptions(); // adding browser preferences with addPreference method profile.addPreference("browser.download.folderList", 2); // location of downloaded file profile.addPreference("browser.download.dir", "C:\\Users\\ghs6kor\\Documents\\Download"); profile.addPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x-msexcel,application/excel," + "application/x-excel,application/vnd.ms-excel," + "image/png,image/jpeg,text/html,text/plain," + "application/msword,application/xml"); profile.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel," + "application/excel," + "application/x-excel," +"application/vnd.ms excel,image/png,image/jpeg,text/html," +"text/plain,application/msword,application/xml"); // connecting browser options to webdriver WebDriver driver = new FirefoxDriver(profile); driver.get("https://the-internet.herokuapp.com/download"); //maximize window driver.manage().window().maximize(); // identify element and start download driver.findElement(By.linkText("xls-sample3.xls")).click(); } }
[ { "code": null, "e": 1257, "s": 1062, "text": "We can access file download dialog in Firefox in Selenium. For this we have to first modify the default directory where the downloaded file gets stored. This is done by the addpreference method." }, { "code": null, "e": 1308, "s": 1257, "text": "p.addPreference(\"browser.download.folderList\", 2);" }, { "code": null, "e": 1361, "s": 1308, "text": "Then, define the new path of the download directory." }, { "code": null, "e": 1553, "s": 1361, "text": "Finally, we shall ignore the save to disk and open file options in dialog for the file types via their MIME code. The addPreference method can be called with the help of FirefoxOptions class." }, { "code": null, "e": 1574, "s": 1553, "text": "Code Implementation." }, { "code": null, "e": 3223, "s": 1574, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.firefox.FirefoxOptions;\nimport java.util.concurrent.TimeUnit;\npublic class FileDwnloadWithoutDialg{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n // instance of FirefoxOptions class\n FirefoxOptions profile = new FirefoxOptions();\n // adding browser preferences with addPreference method profile.addPreference(\"browser.download.folderList\", 2);\n // location of downloaded file\n profile.addPreference(\"browser.download.dir\", \"C:\\\\Users\\\\ghs6kor\\\\Documents\\\\Download\");\n profile.addPreference(\"browser.helperApps.neverAsk.openFile\", \"text/csv,application/x-msexcel,application/excel,\" + \"application/x-excel,application/vnd.ms-excel,\" + \"image/png,image/jpeg,text/html,text/plain,\" + \"application/msword,application/xml\");\nprofile.addPreference(\"browser.helperApps.neverAsk.saveToDisk\", \"text/csv,application/x-msexcel,\" + \"application/excel,\" + \"application/x-excel,\" +\"application/vnd.ms excel,image/png,image/jpeg,text/html,\" +\"text/plain,application/msword,application/xml\");\n // connecting browser options to webdriver\n WebDriver driver = new FirefoxDriver(profile);\n driver.get(\"https://the-internet.herokuapp.com/download\");\n //maximize window\n driver.manage().window().maximize();\n // identify element and start download\n driver.findElement(By.linkText(\"xls-sample3.xls\")).click();\n }\n}" } ]
MEX of generated sequence of N+1 integers where ith integer is XOR of (i-1) and K - GeeksforGeeks
07 Jan, 2022 Given two integers N and K, generate a sequence of size N+1 where the ith element is (i-1)⊕K, the task is to find the MEX of this sequence. Here, the MEX of a sequence is the smallest non-negative integer that does not occur in the sequence. Examples: Input: N = 7, K=3Output: 8Explanation: Sequence formed by given N and K is {0⊕3, 1⊕3, 2⊕3, 3⊕3, 4⊕3, 5⊕3, 6⊕3, 7⊕3} i.e {3, 2, 1, 0, 7, 6, 5, 4}Smallest non-negative number not present in the given sequence is 8 Input: N = 6, K=4Output: 3 Native Approach: The simplest approach to solve this problem is to simply make the array of the given and calculate its MEX. Following are the steps to solve this problem: Generate the sequence and sort it.Initialize MEX to 0 and iterate over the sorted array, if the current element is equal to MEX increase MEX by 1 otherwise break the loop.Print MEX as the answer to this problem. Generate the sequence and sort it. Initialize MEX to 0 and iterate over the sorted array, if the current element is equal to MEX increase MEX by 1 otherwise break the loop. Print MEX as the answer to this problem. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the MEX of sequenceint findMex(int N, int K){ // Generating the sequence int A[N + 1]; for (int i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array sort(A, A + N + 1); // Calculating the MEX // Initialising the MEX variable int MEX = 0; for (int x : A) { if (x == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX;} // Driver codeint main(){ // Given Input int N = 7, K = 3; cout << findMex(N, K); return 0;} // Java program to find the Highest// Power of M that divides Nimport java.util.*;public class GFG{ // Function to find the MEX of sequence static int findMex(int N, int K) { // Generating the sequence int[] A = new int[N + 1]; for(int i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array Arrays.sort(A); // Calculating the MEX // Initialising the MEX variable int MEX = 0; for(int i = 0; i < A.length; i++) { if (A[i] == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX; } // Driver code public static void main(String args[]) { // Given Input int N = 7, K = 3; System.out.println(findMex(N, K)); }} // This code is contributed by Samim Hossain Mondal. # Python program for the above approach # Function to find the MEX of sequencedef findMex(N, K): # Generating the sequence A = [0] * (N + 1) for i in range(N + 1): A[i] = i ^ K # Sorting the array A.sort() # Calculating the MEX # Initialising the MEX variable MEX = 0 for x in A: if (x == MEX): # If current MEX is equal # to the element # increase MEX by one MEX += 1 else: # If current MEX is not equal # to the element then # the current MEX is the answer break return MEX # Driver code # Given InputN = 7K = 3print(findMex(N, K)) # This code is contributed by Saurabh Jaiswal // C# program for the above approachusing System; class GFG{ // Function to find the MEX of sequencestatic int findMex(int N, int K){ // Generating the sequence int[] A = new int[N + 1]; for(int i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array Array.Sort(A); // Calculating the MEX // Initialising the MEX variable int MEX = 0; foreach(int x in A) { if (x == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX;} // Driver codepublic static void Main(){ // Given Input int N = 7, K = 3; Console.WriteLine(findMex(N, K));}} // This code is contributed by ukasp <script>// Javascript program for the above approach // Function to find the MEX of sequencefunction findMex(N, K) { // Generating the sequence let A = new Array(N + 1); for (let i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array A.sort(); // Calculating the MEX // Initialising the MEX variable let MEX = 0; for (x of A) { if (x == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX;} // Driver code // Given Inputlet N = 7let K = 3;document.write(findMex(N, K)) // This code is contributed by gfgking.</script> 8 Time Complexity: O(N*log(N))Auxiliary Space: O(N) Efficient Approach: If a number M is occurring in this sequence then for some ith term (i-1)⊕K = M, which also means M⊕K = (i-1), where the maximum value of (i-1) is N. Now, assume that X is the MEX of the given sequence, then X⊕K must be greater than N, i.e X⊕K > N. So, the minimum value of X is the MEX of the sequence. Follow the below steps, to solve this problem: Iterate through the bits of both N+1 and K from backwards.If the ith bit of K is equal to the ith bit of N+1, set the ith bit of X to 0.If the ith bit of K is equal to 0 and the ith bit of N+1 is equal to 1, set the ith bit of X to 1.If the ith bit of K is equal to 1 and the ith bit of N+1 is equal to 0, set all the remaining lower bits of X to 0 because this means that the number which contains a set bit in this position is missing and it is the MEX of the sequence.Print the answer according to the above observation. Iterate through the bits of both N+1 and K from backwards. If the ith bit of K is equal to the ith bit of N+1, set the ith bit of X to 0. If the ith bit of K is equal to 0 and the ith bit of N+1 is equal to 1, set the ith bit of X to 1. If the ith bit of K is equal to 1 and the ith bit of N+1 is equal to 0, set all the remaining lower bits of X to 0 because this means that the number which contains a set bit in this position is missing and it is the MEX of the sequence. Print the answer according to the above observation. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the MEX of the sequenceint findMEX(int N, int K){ // Calculating the last possible bit int lastBit = max(round(log2(N + 1)), round(log2(K))); // Initialising X int X = 0; for (int i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X;} // Driver Codeint main(){ // Given Input int N = 6, K = 4; cout << findMEX(N, K); return 0;} // Java program for the above approachimport java.util.*;public class GFG{ // Function to calculate the// log base 2 of an integerstatic int log2(int N){ // calculate log2 N indirectly // using log() method int result = (int)(Math.log(N) / Math.log(2)); return result;} // Function to find the MEX of the sequencestatic int findMEX(int N, int K){ // Calculating the last possible bit int lastBit = Math.max(Math.round(log2(N + 1)), Math.round(log2(K))); // Initialising X int X = 0; for (int i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X;} // Driver Codepublic static void main(String args[]){ // Given Input int N = 6, K = 4; System.out.println(findMEX(N, K)); }} // This code is contributed by Samim Hossain Mondal. # Python program for the above approachfrom math import * # Function to find the MEX of the sequencedef findMEX(N, K): # Calculating the last possible bit lastBit = max(round(log2(N + 1)), round(log2(K))) # Initialising X X = 0 for i in range(lastBit, -1, -1): # If the ith bit of K is equal # to the ith bit of N+1 then the # ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)): continue # If the ith bit of K is equal to 0 # and the ith bit of N+1 is equal to 1, # set the ith bit of X to 1 elif ((K >> i & 1) == 0): X = X | (1 << i) # If the ith bit of K is equal to 1 # and the ith bit of N+1 is equal to 0, # all the remaining bits will # remain unset else: break return X # Driver Code # Given InputN = 6K = 4print(findMEX(N, K)) # This code is contributed by Shubham Singh // C# program for the above approachusing System;class GFG{ // Function to calculate the // log base 2 of an integer static double log2(int N) { // calculate log2 N indirectly // using log() method double result = (Math.Log(N) / Math.Log(2)); return result; } // Function to find the MEX of the sequence static int findMEX(int N, int K) { // Calculating the last possible bit int lastBit = Math.Max((int)Math.Round(log2(N + 1)), (int)Math.Round(log2(K))); // Initialising X int X = 0; for (int i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X; } // Driver Code public static void Main() { // Given Input int N = 6, K = 4; Console.Write(findMEX(N, K)); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript program for the above approach // Function to find the MEX of the sequence const findMEX = (N, K) => { // Calculating the last possible bit let lastBit = Math.max(Math.round(Math.log2(N + 1)), Math.round(Math.log2(K))); // Initialising X let X = 0; for (let i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X; } // Driver Code // Given Input let N = 6, K = 4; document.write(findMEX(N, K)); // This code is contributed by rakeshsahni </script> 3 Time Complexity: O(log(max(N, K))Auxiliary Space: O(1) rakeshsahni gfgking ukasp _saurabh_jaiswal samim2000 SHUBHAMSINGH10 Bitwise-XOR Sequence and Series Mathematical Pattern Searching Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Segment Tree | Set 1 (Sum of given range) KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching Check if a string is substring of another
[ { "code": null, "e": 26047, "s": 26019, "text": "\n07 Jan, 2022" }, { "code": null, "e": 26289, "s": 26047, "text": "Given two integers N and K, generate a sequence of size N+1 where the ith element is (i-1)⊕K, the task is to find the MEX of this sequence. Here, the MEX of a sequence is the smallest non-negative integer that does not occur in the sequence." }, { "code": null, "e": 26299, "s": 26289, "text": "Examples:" }, { "code": null, "e": 26511, "s": 26299, "text": "Input: N = 7, K=3Output: 8Explanation: Sequence formed by given N and K is {0⊕3, 1⊕3, 2⊕3, 3⊕3, 4⊕3, 5⊕3, 6⊕3, 7⊕3} i.e {3, 2, 1, 0, 7, 6, 5, 4}Smallest non-negative number not present in the given sequence is 8" }, { "code": null, "e": 26538, "s": 26511, "text": "Input: N = 6, K=4Output: 3" }, { "code": null, "e": 26710, "s": 26538, "text": "Native Approach: The simplest approach to solve this problem is to simply make the array of the given and calculate its MEX. Following are the steps to solve this problem:" }, { "code": null, "e": 26922, "s": 26710, "text": "Generate the sequence and sort it.Initialize MEX to 0 and iterate over the sorted array, if the current element is equal to MEX increase MEX by 1 otherwise break the loop.Print MEX as the answer to this problem." }, { "code": null, "e": 26957, "s": 26922, "text": "Generate the sequence and sort it." }, { "code": null, "e": 27095, "s": 26957, "text": "Initialize MEX to 0 and iterate over the sorted array, if the current element is equal to MEX increase MEX by 1 otherwise break the loop." }, { "code": null, "e": 27136, "s": 27095, "text": "Print MEX as the answer to this problem." }, { "code": null, "e": 27187, "s": 27136, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27191, "s": 27187, "text": "C++" }, { "code": null, "e": 27196, "s": 27191, "text": "Java" }, { "code": null, "e": 27204, "s": 27196, "text": "Python3" }, { "code": null, "e": 27207, "s": 27204, "text": "C#" }, { "code": null, "e": 27218, "s": 27207, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the MEX of sequenceint findMex(int N, int K){ // Generating the sequence int A[N + 1]; for (int i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array sort(A, A + N + 1); // Calculating the MEX // Initialising the MEX variable int MEX = 0; for (int x : A) { if (x == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX;} // Driver codeint main(){ // Given Input int N = 7, K = 3; cout << findMex(N, K); return 0;}", "e": 28061, "s": 27218, "text": null }, { "code": "// Java program to find the Highest// Power of M that divides Nimport java.util.*;public class GFG{ // Function to find the MEX of sequence static int findMex(int N, int K) { // Generating the sequence int[] A = new int[N + 1]; for(int i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array Arrays.sort(A); // Calculating the MEX // Initialising the MEX variable int MEX = 0; for(int i = 0; i < A.length; i++) { if (A[i] == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX; } // Driver code public static void main(String args[]) { // Given Input int N = 7, K = 3; System.out.println(findMex(N, K)); }} // This code is contributed by Samim Hossain Mondal.", "e": 29029, "s": 28061, "text": null }, { "code": "# Python program for the above approach # Function to find the MEX of sequencedef findMex(N, K): # Generating the sequence A = [0] * (N + 1) for i in range(N + 1): A[i] = i ^ K # Sorting the array A.sort() # Calculating the MEX # Initialising the MEX variable MEX = 0 for x in A: if (x == MEX): # If current MEX is equal # to the element # increase MEX by one MEX += 1 else: # If current MEX is not equal # to the element then # the current MEX is the answer break return MEX # Driver code # Given InputN = 7K = 3print(findMex(N, K)) # This code is contributed by Saurabh Jaiswal", "e": 29752, "s": 29029, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the MEX of sequencestatic int findMex(int N, int K){ // Generating the sequence int[] A = new int[N + 1]; for(int i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array Array.Sort(A); // Calculating the MEX // Initialising the MEX variable int MEX = 0; foreach(int x in A) { if (x == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX;} // Driver codepublic static void Main(){ // Given Input int N = 7, K = 3; Console.WriteLine(findMex(N, K));}} // This code is contributed by ukasp", "e": 30701, "s": 29752, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the MEX of sequencefunction findMex(N, K) { // Generating the sequence let A = new Array(N + 1); for (let i = 0; i <= N; i++) { A[i] = i ^ K; } // Sorting the array A.sort(); // Calculating the MEX // Initialising the MEX variable let MEX = 0; for (x of A) { if (x == MEX) { // If current MEX is equal // to the element // increase MEX by one MEX++; } else { // If current MEX is not equal // to the element then // the current MEX is the answer break; } } return MEX;} // Driver code // Given Inputlet N = 7let K = 3;document.write(findMex(N, K)) // This code is contributed by gfgking.</script>", "e": 31534, "s": 30701, "text": null }, { "code": null, "e": 31536, "s": 31534, "text": "8" }, { "code": null, "e": 31586, "s": 31536, "text": "Time Complexity: O(N*log(N))Auxiliary Space: O(N)" }, { "code": null, "e": 31957, "s": 31586, "text": "Efficient Approach: If a number M is occurring in this sequence then for some ith term (i-1)⊕K = M, which also means M⊕K = (i-1), where the maximum value of (i-1) is N. Now, assume that X is the MEX of the given sequence, then X⊕K must be greater than N, i.e X⊕K > N. So, the minimum value of X is the MEX of the sequence. Follow the below steps, to solve this problem:" }, { "code": null, "e": 32481, "s": 31957, "text": "Iterate through the bits of both N+1 and K from backwards.If the ith bit of K is equal to the ith bit of N+1, set the ith bit of X to 0.If the ith bit of K is equal to 0 and the ith bit of N+1 is equal to 1, set the ith bit of X to 1.If the ith bit of K is equal to 1 and the ith bit of N+1 is equal to 0, set all the remaining lower bits of X to 0 because this means that the number which contains a set bit in this position is missing and it is the MEX of the sequence.Print the answer according to the above observation." }, { "code": null, "e": 32540, "s": 32481, "text": "Iterate through the bits of both N+1 and K from backwards." }, { "code": null, "e": 32619, "s": 32540, "text": "If the ith bit of K is equal to the ith bit of N+1, set the ith bit of X to 0." }, { "code": null, "e": 32718, "s": 32619, "text": "If the ith bit of K is equal to 0 and the ith bit of N+1 is equal to 1, set the ith bit of X to 1." }, { "code": null, "e": 32956, "s": 32718, "text": "If the ith bit of K is equal to 1 and the ith bit of N+1 is equal to 0, set all the remaining lower bits of X to 0 because this means that the number which contains a set bit in this position is missing and it is the MEX of the sequence." }, { "code": null, "e": 33009, "s": 32956, "text": "Print the answer according to the above observation." }, { "code": null, "e": 33060, "s": 33009, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 33064, "s": 33060, "text": "C++" }, { "code": null, "e": 33069, "s": 33064, "text": "Java" }, { "code": null, "e": 33077, "s": 33069, "text": "Python3" }, { "code": null, "e": 33080, "s": 33077, "text": "C#" }, { "code": null, "e": 33091, "s": 33080, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the MEX of the sequenceint findMEX(int N, int K){ // Calculating the last possible bit int lastBit = max(round(log2(N + 1)), round(log2(K))); // Initialising X int X = 0; for (int i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X;} // Driver Codeint main(){ // Given Input int N = 6, K = 4; cout << findMEX(N, K); return 0;}", "e": 34187, "s": 33091, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class GFG{ // Function to calculate the// log base 2 of an integerstatic int log2(int N){ // calculate log2 N indirectly // using log() method int result = (int)(Math.log(N) / Math.log(2)); return result;} // Function to find the MEX of the sequencestatic int findMEX(int N, int K){ // Calculating the last possible bit int lastBit = Math.max(Math.round(log2(N + 1)), Math.round(log2(K))); // Initialising X int X = 0; for (int i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X;} // Driver Codepublic static void main(String args[]){ // Given Input int N = 6, K = 4; System.out.println(findMEX(N, K)); }} // This code is contributed by Samim Hossain Mondal.", "e": 35569, "s": 34187, "text": null }, { "code": "# Python program for the above approachfrom math import * # Function to find the MEX of the sequencedef findMEX(N, K): # Calculating the last possible bit lastBit = max(round(log2(N + 1)), round(log2(K))) # Initialising X X = 0 for i in range(lastBit, -1, -1): # If the ith bit of K is equal # to the ith bit of N+1 then the # ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)): continue # If the ith bit of K is equal to 0 # and the ith bit of N+1 is equal to 1, # set the ith bit of X to 1 elif ((K >> i & 1) == 0): X = X | (1 << i) # If the ith bit of K is equal to 1 # and the ith bit of N+1 is equal to 0, # all the remaining bits will # remain unset else: break return X # Driver Code # Given InputN = 6K = 4print(findMEX(N, K)) # This code is contributed by Shubham Singh", "e": 36553, "s": 35569, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to calculate the // log base 2 of an integer static double log2(int N) { // calculate log2 N indirectly // using log() method double result = (Math.Log(N) / Math.Log(2)); return result; } // Function to find the MEX of the sequence static int findMEX(int N, int K) { // Calculating the last possible bit int lastBit = Math.Max((int)Math.Round(log2(N + 1)), (int)Math.Round(log2(K))); // Initialising X int X = 0; for (int i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X; } // Driver Code public static void Main() { // Given Input int N = 6, K = 4; Console.Write(findMEX(N, K)); }} // This code is contributed by Samim Hossain Mondal.", "e": 37892, "s": 36553, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the MEX of the sequence const findMEX = (N, K) => { // Calculating the last possible bit let lastBit = Math.max(Math.round(Math.log2(N + 1)), Math.round(Math.log2(K))); // Initialising X let X = 0; for (let i = lastBit; i >= 0; i--) { // If the ith bit of K is equal // to the ith bit of N+1 then the // ith bit of X will remain 0 if ((K >> i & 1) == ((N + 1) >> i & 1)) continue; // If the ith bit of K is equal to 0 // and the ith bit of N+1 is equal to 1, // set the ith bit of X to 1 else if ((K >> i & 1) == 0) X = X | (1 << i); // If the ith bit of K is equal to 1 // and the ith bit of N+1 is equal to 0, // all the remaining bits will // remain unset else break; } return X; } // Driver Code // Given Input let N = 6, K = 4; document.write(findMEX(N, K)); // This code is contributed by rakeshsahni </script>", "e": 39098, "s": 37892, "text": null }, { "code": null, "e": 39100, "s": 39098, "text": "3" }, { "code": null, "e": 39155, "s": 39100, "text": "Time Complexity: O(log(max(N, K))Auxiliary Space: O(1)" }, { "code": null, "e": 39169, "s": 39157, "text": "rakeshsahni" }, { "code": null, "e": 39177, "s": 39169, "text": "gfgking" }, { "code": null, "e": 39183, "s": 39177, "text": "ukasp" }, { "code": null, "e": 39200, "s": 39183, "text": "_saurabh_jaiswal" }, { "code": null, "e": 39210, "s": 39200, "text": "samim2000" }, { "code": null, "e": 39225, "s": 39210, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 39237, "s": 39225, "text": "Bitwise-XOR" }, { "code": null, "e": 39257, "s": 39237, "text": "Sequence and Series" }, { "code": null, "e": 39270, "s": 39257, "text": "Mathematical" }, { "code": null, "e": 39288, "s": 39270, "text": "Pattern Searching" }, { "code": null, "e": 39301, "s": 39288, "text": "Mathematical" }, { "code": null, "e": 39319, "s": 39301, "text": "Pattern Searching" }, { "code": null, "e": 39417, "s": 39319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39461, "s": 39417, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 39492, "s": 39461, "text": "Modular multiplicative inverse" }, { "code": null, "e": 39517, "s": 39492, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 39549, "s": 39517, "text": "Check if a number is Palindrome" }, { "code": null, "e": 39591, "s": 39549, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 39627, "s": 39591, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 39670, "s": 39627, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 39708, "s": 39670, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 39752, "s": 39708, "text": "Boyer Moore Algorithm for Pattern Searching" } ]
Cropping Faces from Images using OpenCV - Python - GeeksforGeeks
13 Jan, 2021 Opencv is a python library mainly used for image processing and computer vision. In this article first, we detect faces after that we crop the face from the image. Face detection is the branch of image processing that uses to detect faces. We will use a pre-trained Haar Cascade model to detect faces from the image. A haar cascade is the object detection method used to detect objects from the image. This algorithm was trained by numerous images. You can download the face haar cascade file by click here. Let’s Implementation in stepwise: Step 1: In this step, we will read the image and converted it into grayscale. Python3 import cv2 # Read the input imageimg = cv2.imread('mpw.jpeg') # Convert into grayscalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) Explanation: In this code first we import our opencv library using import cv2. cv2.imread() method loads the image from the given path(ex:mpw.jpeg or filepath/mpw.jpeg) After loading the image we convert the image to a grayscale image using COLOR_BGR2GRAY. Step 2: Use the Haar Cascade model to detect faces from the image. Python3 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') # Detect facesfaces = face_cascade.detectMultiScale(gray, 1.1, 4) Explanation: We use cv2.CascadeClassifier for load haarcascade file in face_cascade. detectMultiScale() function used for detect faces.It takes 3 parameters: Gray: input image(gray scale image) 1.1: scale factor, it specifies how much the image size is reduced with each scale. It improves detection. 4: MinNeighbours, specifies how many neighbors each candidate rectangle should have to retain. Step 3: Find the face in the image. Python3 for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2) faces = img[y:y + h, x:x + w] cv2.imshow("face",faces) cv2.imwrite('face.jpg', faces) cv2.imshow('img', img)cv2.waitKey() Explanation: x,y are pixel location of faces, w,h are width and height of faces. cv2.rectangle() function used for draw rectangle over the detected object, img is input image, (x,y),(x+w, y+h) are locations of rectangle,(0,0,255) is color of a rectangle this argument gets passed as a tuple for BGR,we would use (0,0,255) for red, 2 is thickness of rectangle. Below is the full implementation: Image Used – input image Python3 import cv2 # Read the input imageimg = cv2.imread('mpw.jpeg') # Convert into grayscalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Load the cascadeface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') # Detect facesfaces = face_cascade.detectMultiScale(gray, 1.1, 4) # Draw rectangle around the faces and crop the facesfor (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2) faces = img[y:y + h, x:x + w] cv2.imshow("face",faces) cv2.imwrite('face.jpg', faces) # Display the outputcv2.imwrite('detcted.jpg', img)cv2.imshow('img', img)cv2.waitKey() Output: Detected face cropped image Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python Iterate over a list in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python Selecting rows in pandas DataFrame based on conditions
[ { "code": null, "e": 24141, "s": 24113, "text": "\n13 Jan, 2021" }, { "code": null, "e": 24381, "s": 24141, "text": "Opencv is a python library mainly used for image processing and computer vision. In this article first, we detect faces after that we crop the face from the image. Face detection is the branch of image processing that uses to detect faces." }, { "code": null, "e": 24650, "s": 24381, "text": "We will use a pre-trained Haar Cascade model to detect faces from the image. A haar cascade is the object detection method used to detect objects from the image. This algorithm was trained by numerous images. You can download the face haar cascade file by click here." }, { "code": null, "e": 24684, "s": 24650, "text": "Let’s Implementation in stepwise:" }, { "code": null, "e": 24762, "s": 24684, "text": "Step 1: In this step, we will read the image and converted it into grayscale." }, { "code": null, "e": 24770, "s": 24762, "text": "Python3" }, { "code": "import cv2 # Read the input imageimg = cv2.imread('mpw.jpeg') # Convert into grayscalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)", "e": 24903, "s": 24770, "text": null }, { "code": null, "e": 25160, "s": 24903, "text": "Explanation: In this code first we import our opencv library using import cv2. cv2.imread() method loads the image from the given path(ex:mpw.jpeg or filepath/mpw.jpeg) After loading the image we convert the image to a grayscale image using COLOR_BGR2GRAY." }, { "code": null, "e": 25227, "s": 25160, "text": "Step 2: Use the Haar Cascade model to detect faces from the image." }, { "code": null, "e": 25235, "s": 25227, "text": "Python3" }, { "code": "face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') # Detect facesfaces = face_cascade.detectMultiScale(gray, 1.1, 4)", "e": 25375, "s": 25235, "text": null }, { "code": null, "e": 25539, "s": 25381, "text": "Explanation: We use cv2.CascadeClassifier for load haarcascade file in face_cascade. detectMultiScale() function used for detect faces.It takes 3 parameters:" }, { "code": null, "e": 25575, "s": 25539, "text": "Gray: input image(gray scale image)" }, { "code": null, "e": 25682, "s": 25575, "text": "1.1: scale factor, it specifies how much the image size is reduced with each scale. It improves detection." }, { "code": null, "e": 25777, "s": 25682, "text": "4: MinNeighbours, specifies how many neighbors each candidate rectangle should have to retain." }, { "code": null, "e": 25813, "s": 25777, "text": "Step 3: Find the face in the image." }, { "code": null, "e": 25821, "s": 25813, "text": "Python3" }, { "code": "for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2) faces = img[y:y + h, x:x + w] cv2.imshow(\"face\",faces) cv2.imwrite('face.jpg', faces) cv2.imshow('img', img)cv2.waitKey()", "e": 26062, "s": 25821, "text": null }, { "code": null, "e": 26422, "s": 26062, "text": "Explanation: x,y are pixel location of faces, w,h are width and height of faces. cv2.rectangle() function used for draw rectangle over the detected object, img is input image, (x,y),(x+w, y+h) are locations of rectangle,(0,0,255) is color of a rectangle this argument gets passed as a tuple for BGR,we would use (0,0,255) for red, 2 is thickness of rectangle." }, { "code": null, "e": 26456, "s": 26422, "text": "Below is the full implementation:" }, { "code": null, "e": 26470, "s": 26456, "text": "Image Used – " }, { "code": null, "e": 26482, "s": 26470, "text": "input image" }, { "code": null, "e": 26490, "s": 26482, "text": "Python3" }, { "code": "import cv2 # Read the input imageimg = cv2.imread('mpw.jpeg') # Convert into grayscalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Load the cascadeface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') # Detect facesfaces = face_cascade.detectMultiScale(gray, 1.1, 4) # Draw rectangle around the faces and crop the facesfor (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2) faces = img[y:y + h, x:x + w] cv2.imshow(\"face\",faces) cv2.imwrite('face.jpg', faces) # Display the outputcv2.imwrite('detcted.jpg', img)cv2.imshow('img', img)cv2.waitKey()", "e": 27107, "s": 26490, "text": null }, { "code": null, "e": 27115, "s": 27107, "text": "Output:" }, { "code": null, "e": 27129, "s": 27115, "text": "Detected face" }, { "code": null, "e": 27143, "s": 27129, "text": "cropped image" }, { "code": null, "e": 27150, "s": 27143, "text": "Picked" }, { "code": null, "e": 27164, "s": 27150, "text": "Python-OpenCV" }, { "code": null, "e": 27171, "s": 27164, "text": "Python" }, { "code": null, "e": 27269, "s": 27171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27278, "s": 27269, "text": "Comments" }, { "code": null, "e": 27291, "s": 27278, "text": "Old Comments" }, { "code": null, "e": 27326, "s": 27291, "text": "Read a file line by line in Python" }, { "code": null, "e": 27348, "s": 27326, "text": "Enumerate() in Python" }, { "code": null, "e": 27378, "s": 27348, "text": "Iterate over a list in Python" }, { "code": null, "e": 27410, "s": 27378, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27452, "s": 27410, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27478, "s": 27452, "text": "Python String | replace()" }, { "code": null, "e": 27515, "s": 27478, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27558, "s": 27515, "text": "Python program to convert a list to string" }, { "code": null, "e": 27602, "s": 27558, "text": "Reading and Writing to text files in Python" } ]
Difference Between Constructor and Destructor in C++ - GeeksforGeeks
29 Dec, 2021 Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with arguments or without arguments. There can be many constructors in a class. It can be overloaded but it can not be inherited or virtual. There is a concept of copy constructor which is used to initialize an object from another object. Syntax: ClassName() { //Constructor's Body } Destructor: Like a constructor, Destructor is also a member function of a class that has the same name as the class name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is called while the object of the class is freed or deleted. In a class, there is always a single destructor without any parameters so it can’t be overloaded. It is always called in the reverse order of the constructor. if a class is inherited by another class and both the classes have a destructor then the destructor of the child class is called first, followed by the destructor of the parent or base class. Syntax: ~ClassName() { //Destuctor's Body } Note: If we do not specify any access modifiers for the members inside the class then by default the access modifier for the members will be Private. Example/Implementation of Constructor and Destructor: C++ #include <iostream>using namespace std; class Z{public: // constructor Z() { cout<<"Constructor called"<<endl; } // destructor ~Z() { cout<<"Destructor called"<<endl; }}; int main(){ Z z1; // Constructor Called int a = 1; if(a==1) { Z z2; // Constructor Called } // Destructor Called for z2} // Destructor called for z1 Output: Constructor called Constructor called Destructor called Destructor called Difference between Constructor and Destructor in C++ : Aniket Ray vinaygb456 anantverma2001 sagar0719kumar geeky01adarsh C++-Constructors C++-Destructors C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Stack vs Heap Memory Allocation Difference between Process and Thread
[ { "code": null, "e": 24122, "s": 24094, "text": "\n29 Dec, 2021" }, { "code": null, "e": 24699, "s": 24122, "text": "Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with arguments or without arguments. There can be many constructors in a class. It can be overloaded but it can not be inherited or virtual. There is a concept of copy constructor which is used to initialize an object from another object. " }, { "code": null, "e": 24709, "s": 24699, "text": "Syntax: " }, { "code": null, "e": 24761, "s": 24709, "text": " ClassName()\n {\n //Constructor's Body \n } " }, { "code": null, "e": 25379, "s": 24761, "text": "Destructor: Like a constructor, Destructor is also a member function of a class that has the same name as the class name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is called while the object of the class is freed or deleted. In a class, there is always a single destructor without any parameters so it can’t be overloaded. It is always called in the reverse order of the constructor. if a class is inherited by another class and both the classes have a destructor then the destructor of the child class is called first, followed by the destructor of the parent or base class. " }, { "code": null, "e": 25389, "s": 25379, "text": "Syntax: " }, { "code": null, "e": 25441, "s": 25389, "text": " ~ClassName()\n { \n //Destuctor's Body\n }" }, { "code": null, "e": 25592, "s": 25441, "text": "Note: If we do not specify any access modifiers for the members inside the class then by default the access modifier for the members will be Private. " }, { "code": null, "e": 25647, "s": 25592, "text": "Example/Implementation of Constructor and Destructor: " }, { "code": null, "e": 25651, "s": 25647, "text": "C++" }, { "code": "#include <iostream>using namespace std; class Z{public: // constructor Z() { cout<<\"Constructor called\"<<endl; } // destructor ~Z() { cout<<\"Destructor called\"<<endl; }}; int main(){ Z z1; // Constructor Called int a = 1; if(a==1) { Z z2; // Constructor Called } // Destructor Called for z2} // Destructor called for z1", "e": 26037, "s": 25651, "text": null }, { "code": null, "e": 26047, "s": 26037, "text": "Output: " }, { "code": null, "e": 26122, "s": 26047, "text": "Constructor called\nConstructor called\nDestructor called\nDestructor called " }, { "code": null, "e": 26178, "s": 26122, "text": "Difference between Constructor and Destructor in C++ : " }, { "code": null, "e": 26189, "s": 26178, "text": "Aniket Ray" }, { "code": null, "e": 26200, "s": 26189, "text": "vinaygb456" }, { "code": null, "e": 26215, "s": 26200, "text": "anantverma2001" }, { "code": null, "e": 26230, "s": 26215, "text": "sagar0719kumar" }, { "code": null, "e": 26244, "s": 26230, "text": "geeky01adarsh" }, { "code": null, "e": 26261, "s": 26244, "text": "C++-Constructors" }, { "code": null, "e": 26277, "s": 26261, "text": "C++-Destructors" }, { "code": null, "e": 26281, "s": 26277, "text": "C++" }, { "code": null, "e": 26300, "s": 26281, "text": "Difference Between" }, { "code": null, "e": 26304, "s": 26300, "text": "CPP" }, { "code": null, "e": 26402, "s": 26304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26411, "s": 26402, "text": "Comments" }, { "code": null, "e": 26424, "s": 26411, "text": "Old Comments" }, { "code": null, "e": 26452, "s": 26424, "text": "Operator Overloading in C++" }, { "code": null, "e": 26473, "s": 26452, "text": "Iterators in C++ STL" }, { "code": null, "e": 26506, "s": 26473, "text": "Friend class and function in C++" }, { "code": null, "e": 26526, "s": 26506, "text": "Polymorphism in C++" }, { "code": null, "e": 26550, "s": 26526, "text": "Sorting a vector in C++" }, { "code": null, "e": 26581, "s": 26550, "text": "Difference between BFS and DFS" }, { "code": null, "e": 26621, "s": 26581, "text": "Class method vs Static method in Python" }, { "code": null, "e": 26653, "s": 26621, "text": "Differences between TCP and UDP" }, { "code": null, "e": 26685, "s": 26653, "text": "Stack vs Heap Memory Allocation" } ]
How to Use Reserved Words as Column Names in SQL? - GeeksforGeeks
28 Oct, 2021 In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL. But, there is an exception to this rule too. In this article, we will discuss how to use Reserved Words as column names in SQL. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command Query: USE GeeksForGeeks Output: Step 3: Create a table inside the database GeeksForGeeks. We will name the table BIKE. It will contain 2 columns named SELECT and TABLE. Both these are keywords in SQL. The trick here is to type the column names inside the square brackets ‘[]’ so that they are not read as a Reserved Word by the compiler. Query: CREATE TABLE BIKE( [SELECT] VARCHAR(10), [TABLE] INT); Output: Note: Here, the SELECT column stores the names of the bikes, and the TABLE column stores the cost of the bikes. Step 4: Add data to the BIKE table. Query: INSERT INTO BIKE VALUES('HERO',10000); INSERT INTO BIKE VALUES('TVS',20000); INSERT INTO BIKE VALUES('YAMAHA',30000); INSERT INTO BIKE VALUES('HONDA',40000); INSERT INTO BIKE VALUES('BAJAJ',50000); Output: Step 4: Display the SELECT column from the BIKE table. Query: SELECT [SELECT] FROM BIKE; Output: Step 5: Display the TABLE column from the BIKE table. Query: SELECT [TABLE] FROM BIKE; Output: Step 5: We can even display both the columns using the comma separator. Query: SELECT [SELECT],[TABLE] FROM BIKE; Output: Hence, in a similar fashion, we can use any of the reserved names in SQL as a column name. Picked SQL-Query SQL-Server 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 Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25649, "s": 25621, "text": "\n28 Oct, 2021" }, { "code": null, "e": 26006, "s": 25649, "text": "In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL. But, there is an exception to this rule too. In this article, we will discuss how to use Reserved Words as column names in SQL. For this article, we will be using the Microsoft SQL Server as our database." }, { "code": null, "e": 26105, "s": 26006, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks" }, { "code": null, "e": 26112, "s": 26105, "text": "Query:" }, { "code": null, "e": 26142, "s": 26112, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 26150, "s": 26142, "text": "Output:" }, { "code": null, "e": 26221, "s": 26150, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command" }, { "code": null, "e": 26228, "s": 26221, "text": "Query:" }, { "code": null, "e": 26246, "s": 26228, "text": "USE GeeksForGeeks" }, { "code": null, "e": 26254, "s": 26246, "text": "Output:" }, { "code": null, "e": 26560, "s": 26254, "text": "Step 3: Create a table inside the database GeeksForGeeks. We will name the table BIKE. It will contain 2 columns named SELECT and TABLE. Both these are keywords in SQL. The trick here is to type the column names inside the square brackets ‘[]’ so that they are not read as a Reserved Word by the compiler." }, { "code": null, "e": 26567, "s": 26560, "text": "Query:" }, { "code": null, "e": 26622, "s": 26567, "text": "CREATE TABLE BIKE(\n[SELECT] VARCHAR(10),\n[TABLE] INT);" }, { "code": null, "e": 26630, "s": 26622, "text": "Output:" }, { "code": null, "e": 26742, "s": 26630, "text": "Note: Here, the SELECT column stores the names of the bikes, and the TABLE column stores the cost of the bikes." }, { "code": null, "e": 26778, "s": 26742, "text": "Step 4: Add data to the BIKE table." }, { "code": null, "e": 26785, "s": 26778, "text": "Query:" }, { "code": null, "e": 26983, "s": 26785, "text": "INSERT INTO BIKE VALUES('HERO',10000);\nINSERT INTO BIKE VALUES('TVS',20000);\nINSERT INTO BIKE VALUES('YAMAHA',30000);\nINSERT INTO BIKE VALUES('HONDA',40000);\nINSERT INTO BIKE VALUES('BAJAJ',50000);" }, { "code": null, "e": 26991, "s": 26983, "text": "Output:" }, { "code": null, "e": 27046, "s": 26991, "text": "Step 4: Display the SELECT column from the BIKE table." }, { "code": null, "e": 27053, "s": 27046, "text": "Query:" }, { "code": null, "e": 27080, "s": 27053, "text": "SELECT [SELECT] FROM BIKE;" }, { "code": null, "e": 27088, "s": 27080, "text": "Output:" }, { "code": null, "e": 27142, "s": 27088, "text": "Step 5: Display the TABLE column from the BIKE table." }, { "code": null, "e": 27149, "s": 27142, "text": "Query:" }, { "code": null, "e": 27175, "s": 27149, "text": "SELECT [TABLE] FROM BIKE;" }, { "code": null, "e": 27183, "s": 27175, "text": "Output:" }, { "code": null, "e": 27255, "s": 27183, "text": "Step 5: We can even display both the columns using the comma separator." }, { "code": null, "e": 27262, "s": 27255, "text": "Query:" }, { "code": null, "e": 27297, "s": 27262, "text": "SELECT [SELECT],[TABLE] FROM BIKE;" }, { "code": null, "e": 27305, "s": 27297, "text": "Output:" }, { "code": null, "e": 27396, "s": 27305, "text": "Hence, in a similar fashion, we can use any of the reserved names in SQL as a column name." }, { "code": null, "e": 27403, "s": 27396, "text": "Picked" }, { "code": null, "e": 27413, "s": 27403, "text": "SQL-Query" }, { "code": null, "e": 27424, "s": 27413, "text": "SQL-Server" }, { "code": null, "e": 27428, "s": 27424, "text": "SQL" }, { "code": null, "e": 27432, "s": 27428, "text": "SQL" }, { "code": null, "e": 27530, "s": 27432, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27596, "s": 27530, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27653, "s": 27596, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27685, "s": 27653, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27700, "s": 27685, "text": "SQL | Subquery" }, { "code": null, "e": 27778, "s": 27700, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27814, "s": 27778, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27831, "s": 27814, "text": "SQL using Python" }, { "code": null, "e": 27897, "s": 27831, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27959, "s": 27897, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Comparing Python and SQL for Building Data Pipelines | by Marc Laforet | Towards Data Science
Breaking into the workforce as a web developer, my first interaction with databases and SQL was using an Object Relational Model (ORM). I was using the Django query sets API and had an excellent experience using the interface. Thereon-after, I changed to a data engineering role and became much more involved in leveraging datasets to build AI. It became my responsibility to take the data from the user application and turn it into something usable by Data Scientists, a process commonly known as ETL. As the story goes, the data in the production system was messy and required a lot of transformation before anyone was going to be able to build AI from it. There were JSON columns that had different schemas per row, columns contained mixed data types and some rows had erroneous values. Additionally, features like how long the user has been a customer and how long they waited in-between visits needed to be calculated. As I set out on cleaning, aggregating and engineering features for the data, I tried to decide which language would be best for the task. Having come from a job where I used python all day every day, I knew that it could do the job. However, what I learned through this experience was that just because python could do the job doesn’t mean it should. We are working with a time-series dataset where we wanted to track particular users over time. Privacy laws prevent us from knowing the specific dates of the user visits, so we decided that we would normalize the date of the record to the users first visit (ie 5 days after their first visit etc.). For our analysis, it was important to know the time since the last visit as well as the time since their first visit. A had two sample datasets, one with approximately 7.5 million rows measuring 6.5 GBs, and the other with 550 000 rows measuring 900 MB. Using the python and SQL code seen below, I used the smaller dataset to first test the transformations. Python and SQL completed the task in 591 and 40.9 seconds respectively. This means that SQL was able to provide a speed-up of roughly 14.5X! # PYTHON# connect to db using wrapper around psycopg2db = DatabaseConnection(db='db', user='username', password='password')# grab data from db and load into memorydf = db.run_query("SELECT * FROM cleaned_table;")df = pd.DataFrame(df, columns=['user_id', 'series_id', 'timestamp'])# calculate time since first visitdf = df.assign(time_since_first=df.groupby('user_id', sort=False).timestamp.apply(lambda x: x - x.min()))# calculate time since last visitdf = df.assign(time_since_last=df.sort_values(['timestamp'], ascending=True).groupby('user_id', sort=False)['timestamp'].transform(pd.Series.diff))# save df to compressed csvdf.to_csv('transform_time_test.gz', compression='gzip')-- SQL equivalent-- increase the working memory (be careful with this)set work_mem='600MB';-- create a dual index on the partitionCREATE INDEX IF NOT EXISTS user_time_index ON table(user_id, timestamp);-- calculate time since last visit and time since first visit in one pass SELECT *, AGE(timestamp, LAG(timestamp, 1, timestamp) OVER w) AS time_since_last, AGE(timestamp, FIRST_VALUE(timestamp) OVER w) AS time_since_first FROM table WINDOW w AS (PARTITION BY user_id ORDER BY timestamp); This SQL transformation was not only faster but the code is also more readable and thus easier to maintain. Here, I used the lag and first_value functions to find specific records in the users history (called a partition). I then used the age function to determine the time difference between visits. What’s even more interesting is that when these transformation scripts were applied to the 6.5 GB dataset, python completely failed. Out of 3 attempts, python crashed 2 times and my computer completely froze the 3rd time... while SQL took 226 seconds. More info:https://www.postgresql.org/docs/9.5/functions-window.htmlhttp://www.postgresqltutorial.com/postgresql-window-function/ Another game changer for me was realizing that Postgres worked with JSON quite well. I initially thought that it would be impossible to flatten or parse json in postgres...I can’t believe that I was so dumb. If you want to relationize json and its schema is consistent between rows, then your best bet is probably to use Postgres built in ability to parse json. -- SQL (the -> syntax is how you parse json)SELECT user_json->'info'->>'name' as user_name FROM user_table; On the other hand, half the json in my sample dataset isn’t valid json and thus is stored as text. In which case I was left with a choice, I could either recode the data to make it valid OR I could just drop the rows that didn’t follow the rules. To do this, I created a new SQL function called is_json that I could then use to qualify valid json in a WHERE clause. -- SQLcreate or replace function is_json(text)returns boolean language plpgsql immutable as $$begin perform $1::json; return true;exception when invalid_text_representation then return false;end $$;SELECT user_json->'info'->>'name' as user_name FROM user_table WHERE is_json(user_json); Unfortunately, I found that the user_json had a different schema depending on what app version the user was on. Although this makes sense from an application development point of view, it makes it really expensive to conditionally parse every possibility per row. Was I destined to enter python again... not a chance! I found another function on stack-overflow written by a postgres god named klin. -- SQLcreate or replace function create_jsonb_flat_view (table_name text, regular_columns text, json_column text) returns text language plpgsql as $$declare cols text;begin execute format ($ex$ select string_agg(format('%2$s->>%%1$L "%%1$s"', key), ', ') from ( select distinct key from %1$s, jsonb_each(%2$s) order by 1 ) s; $ex$, table_name, json_column) into cols; execute format($ex$ drop view if exists %1$s_view; create view %1$s_view as select %2$s, %3$s from %1$s $ex$, table_name, regular_columns, cols); return cols;end $$; This function was able to successfully flatten my json and solve my worst nightmare quite easily. Final Comments There is an idiom that declares Python as the second best language to do almost anything. I believe this to be true and in some instances have found the performance difference between Python and the ‘best’ language to be negligible. In this case however, python was unable to compete with SQL. These realizations along with readings I’ve been doing has completely changed my approach to ETL. I now work under the paradigm of “Do not move data to code, move code to your data”. Python moves your data to the code while SQL acts on it in place. What’s more is that I know that I’ve only scratched the surface of sql and postgres abilities. I’m looking forward to more awesome functionality, and the possibility of getting speed ups from using an analytical warehouse.
[ { "code": null, "e": 675, "s": 172, "text": "Breaking into the workforce as a web developer, my first interaction with databases and SQL was using an Object Relational Model (ORM). I was using the Django query sets API and had an excellent experience using the interface. Thereon-after, I changed to a data engineering role and became much more involved in leveraging datasets to build AI. It became my responsibility to take the data from the user application and turn it into something usable by Data Scientists, a process commonly known as ETL." }, { "code": null, "e": 1447, "s": 675, "text": "As the story goes, the data in the production system was messy and required a lot of transformation before anyone was going to be able to build AI from it. There were JSON columns that had different schemas per row, columns contained mixed data types and some rows had erroneous values. Additionally, features like how long the user has been a customer and how long they waited in-between visits needed to be calculated. As I set out on cleaning, aggregating and engineering features for the data, I tried to decide which language would be best for the task. Having come from a job where I used python all day every day, I knew that it could do the job. However, what I learned through this experience was that just because python could do the job doesn’t mean it should." }, { "code": null, "e": 2000, "s": 1447, "text": "We are working with a time-series dataset where we wanted to track particular users over time. Privacy laws prevent us from knowing the specific dates of the user visits, so we decided that we would normalize the date of the record to the users first visit (ie 5 days after their first visit etc.). For our analysis, it was important to know the time since the last visit as well as the time since their first visit. A had two sample datasets, one with approximately 7.5 million rows measuring 6.5 GBs, and the other with 550 000 rows measuring 900 MB." }, { "code": null, "e": 2245, "s": 2000, "text": "Using the python and SQL code seen below, I used the smaller dataset to first test the transformations. Python and SQL completed the task in 591 and 40.9 seconds respectively. This means that SQL was able to provide a speed-up of roughly 14.5X!" }, { "code": null, "e": 3416, "s": 2245, "text": "# PYTHON# connect to db using wrapper around psycopg2db = DatabaseConnection(db='db', user='username', password='password')# grab data from db and load into memorydf = db.run_query(\"SELECT * FROM cleaned_table;\")df = pd.DataFrame(df, columns=['user_id', 'series_id', 'timestamp'])# calculate time since first visitdf = df.assign(time_since_first=df.groupby('user_id', sort=False).timestamp.apply(lambda x: x - x.min()))# calculate time since last visitdf = df.assign(time_since_last=df.sort_values(['timestamp'], ascending=True).groupby('user_id', sort=False)['timestamp'].transform(pd.Series.diff))# save df to compressed csvdf.to_csv('transform_time_test.gz', compression='gzip')-- SQL equivalent-- increase the working memory (be careful with this)set work_mem='600MB';-- create a dual index on the partitionCREATE INDEX IF NOT EXISTS user_time_index ON table(user_id, timestamp);-- calculate time since last visit and time since first visit in one pass SELECT *, AGE(timestamp, LAG(timestamp, 1, timestamp) OVER w) AS time_since_last, AGE(timestamp, FIRST_VALUE(timestamp) OVER w) AS time_since_first FROM table WINDOW w AS (PARTITION BY user_id ORDER BY timestamp);" }, { "code": null, "e": 3717, "s": 3416, "text": "This SQL transformation was not only faster but the code is also more readable and thus easier to maintain. Here, I used the lag and first_value functions to find specific records in the users history (called a partition). I then used the age function to determine the time difference between visits." }, { "code": null, "e": 3969, "s": 3717, "text": "What’s even more interesting is that when these transformation scripts were applied to the 6.5 GB dataset, python completely failed. Out of 3 attempts, python crashed 2 times and my computer completely froze the 3rd time... while SQL took 226 seconds." }, { "code": null, "e": 4098, "s": 3969, "text": "More info:https://www.postgresql.org/docs/9.5/functions-window.htmlhttp://www.postgresqltutorial.com/postgresql-window-function/" }, { "code": null, "e": 4460, "s": 4098, "text": "Another game changer for me was realizing that Postgres worked with JSON quite well. I initially thought that it would be impossible to flatten or parse json in postgres...I can’t believe that I was so dumb. If you want to relationize json and its schema is consistent between rows, then your best bet is probably to use Postgres built in ability to parse json." }, { "code": null, "e": 4568, "s": 4460, "text": "-- SQL (the -> syntax is how you parse json)SELECT user_json->'info'->>'name' as user_name FROM user_table;" }, { "code": null, "e": 4934, "s": 4568, "text": "On the other hand, half the json in my sample dataset isn’t valid json and thus is stored as text. In which case I was left with a choice, I could either recode the data to make it valid OR I could just drop the rows that didn’t follow the rules. To do this, I created a new SQL function called is_json that I could then use to qualify valid json in a WHERE clause." }, { "code": null, "e": 5238, "s": 4934, "text": "-- SQLcreate or replace function is_json(text)returns boolean language plpgsql immutable as $$begin perform $1::json; return true;exception when invalid_text_representation then return false;end $$;SELECT user_json->'info'->>'name' as user_name FROM user_table WHERE is_json(user_json);" }, { "code": null, "e": 5637, "s": 5238, "text": "Unfortunately, I found that the user_json had a different schema depending on what app version the user was on. Although this makes sense from an application development point of view, it makes it really expensive to conditionally parse every possibility per row. Was I destined to enter python again... not a chance! I found another function on stack-overflow written by a postgres god named klin." }, { "code": null, "e": 6286, "s": 5637, "text": "-- SQLcreate or replace function create_jsonb_flat_view (table_name text, regular_columns text, json_column text) returns text language plpgsql as $$declare cols text;begin execute format ($ex$ select string_agg(format('%2$s->>%%1$L \"%%1$s\"', key), ', ') from ( select distinct key from %1$s, jsonb_each(%2$s) order by 1 ) s; $ex$, table_name, json_column) into cols; execute format($ex$ drop view if exists %1$s_view; create view %1$s_view as select %2$s, %3$s from %1$s $ex$, table_name, regular_columns, cols); return cols;end $$;" }, { "code": null, "e": 6384, "s": 6286, "text": "This function was able to successfully flatten my json and solve my worst nightmare quite easily." }, { "code": null, "e": 6399, "s": 6384, "text": "Final Comments" } ]
How to convert a matrix to a data frame with column names and row names as new columns in R?
Sometimes we want to create a factor column of the column names and row names of a matrix so that we can use them in the analysis. It is required in situations where we want to know the effect of factor variables on the response and the factor variables were recorded as column names and row names in a matrix. To do this, we can convert the matrix into table and the table obtained is converted to data frame. Consider the below matrix − M1<-matrix(1:25,nrow=5,dimnames=list(c("R1","R2","R3","R4","R5"),c("S1","S2","S3","S4","S5"))) M1 S1 S2 S3 S4 S5 R1 1 6 11 16 21 R2 2 7 12 17 22 R3 3 8 13 18 23 R4 4 9 14 19 24 R5 5 10 15 20 25 as.data.frame(as.table(M1)) Var1 Var2 Freq 1 R1 S1 1 2 R2 S1 2 3 R3 S1 3 4 R4 S1 4 5 R5 S1 5 6 R1 S2 6 7 R2 S2 7 8 R3 S2 8 9 R4 S2 9 10 R5 S2 10 11 R1 S3 11 12 R2 S3 12 13 R3 S3 13 14 R4 S3 14 15 R5 S3 15 16 R1 S4 16 17 R2 S4 17 18 R3 S4 18 19 R4 S4 19 20 R5 S4 20 21 R1 S5 21 22 R2 S5 22 23 R3 S5 23 24 R4 S5 24 25 R5 S5 25 Let’s have a look at two more examples − M2<-matrix(sample(1:50,16),nrow=4,dimnames=list(c("R1","R2","R3","R4"),c("C1","C2","C3","C4"))) M2 C1 C2 C3 C4 R1 38 23 30 34 R2 17 19 32 10 R3 9 26 47 1 R4 39 43 29 44 as.data.frame(as.table(M2)) Var1 Var2 Freq 1 R1 C1 38 2 R2 C1 17 3 R3 C1 9 4 R4 C1 39 5 R1 C2 23 6 R2 C2 19 7 R3 C2 26 8 R4 C2 43 9 R1 C3 30 10 R2 C3 32 11 R3 C3 47 12 R4 C3 29 13 R1 C4 34 14 R2 C4 10 15 R3 C4 1 16 R4 C4 44 M3 <-matrix(sample(1:100,16),ncol=4,dimnames=list(c("Cold","Hot","Sweet","Bitter"),c("Winter","Autumn","Rainy","Summer"))) > M3 Winter Autumn Rainy Summer Cold 15 42 97 83 Hot 58 48 53 35 Sweet 29 76 86 43 Bitter 24 39 40 1 as.data.frame(as.table(M3)) Var1 Var2 Freq 1 Cold Winter 15 2 Hot Winter 58 3 Sweet Winter 29 4 Bitter Winter 24 5 Cold Autumn 42 6 Hot Autumn 48 7 Sweet Autumn 76 8 Bitter Autumn 39 9 Cold Rainy 97 10 Hot Rainy 53 11 Sweet Rainy 86 12 Bitter Rainy 40 13 Cold Summer 83 14 Hot Summer 35 15 Sweet Summer 43 16 Bitter Summer 1
[ { "code": null, "e": 1473, "s": 1062, "text": "Sometimes we want to create a factor column of the column names and row names of a matrix so that we can use them in the analysis. It is required in situations where we want to know the effect of factor variables on the response and the factor variables were recorded as column names and row names in a matrix. To do this, we can convert the matrix into table and the table obtained is converted to data frame." }, { "code": null, "e": 1501, "s": 1473, "text": "Consider the below matrix −" }, { "code": null, "e": 1599, "s": 1501, "text": "M1<-matrix(1:25,nrow=5,dimnames=list(c(\"R1\",\"R2\",\"R3\",\"R4\",\"R5\"),c(\"S1\",\"S2\",\"S3\",\"S4\",\"S5\")))\nM1" }, { "code": null, "e": 1695, "s": 1599, "text": "S1 S2 S3 S4 S5\nR1 1 6 11 16 21\nR2 2 7 12 17 22\nR3 3 8 13 18 23\nR4 4 9 14 19 24\nR5 5 10 15 20 25" }, { "code": null, "e": 1723, "s": 1695, "text": "as.data.frame(as.table(M1))" }, { "code": null, "e": 2020, "s": 1723, "text": "Var1 Var2 Freq\n1 R1 S1 1\n2 R2 S1 2\n3 R3 S1 3\n4 R4 S1 4\n5 R5 S1 5\n6 R1 S2 6\n7 R2 S2 7\n8 R3 S2 8\n9 R4 S2 9\n10 R5 S2 10\n11 R1 S3 11\n12 R2 S3 12\n13 R3 S3 13\n14 R4 S3 14\n15 R5 S3 15\n16 R1 S4 16\n17 R2 S4 17\n18 R3 S4 18\n19 R4 S4 19\n20 R5 S4 20\n21 R1 S5 21\n22 R2 S5 22\n23 R3 S5 23\n24 R4 S5 24\n25 R5 S5 25" }, { "code": null, "e": 2061, "s": 2020, "text": "Let’s have a look at two more examples −" }, { "code": null, "e": 2160, "s": 2061, "text": "M2<-matrix(sample(1:50,16),nrow=4,dimnames=list(c(\"R1\",\"R2\",\"R3\",\"R4\"),c(\"C1\",\"C2\",\"C3\",\"C4\")))\nM2" }, { "code": null, "e": 2230, "s": 2160, "text": "C1 C2 C3 C4\nR1 38 23 30 34\nR2 17 19 32 10\nR3 9 26 47 1\nR4 39 43 29 44" }, { "code": null, "e": 2258, "s": 2230, "text": "as.data.frame(as.table(M2))" }, { "code": null, "e": 2454, "s": 2258, "text": "Var1 Var2 Freq\n1 R1 C1 38\n2 R2 C1 17\n3 R3 C1 9\n4 R4 C1 39\n5 R1 C2 23\n6 R2 C2 19\n7 R3 C2 26\n8 R4 C2 43\n9 R1 C3 30\n10 R2 C3 32\n11 R3 C3 47\n12 R4 C3 29\n13 R1 C4 34\n14 R2 C4 10\n15 R3 C4 1\n16 R4 C4 44" }, { "code": null, "e": 2582, "s": 2454, "text": "M3 <-matrix(sample(1:100,16),ncol=4,dimnames=list(c(\"Cold\",\"Hot\",\"Sweet\",\"Bitter\"),c(\"Winter\",\"Autumn\",\"Rainy\",\"Summer\")))\n> M3" }, { "code": null, "e": 2678, "s": 2582, "text": "Winter Autumn Rainy Summer\nCold 15 42 97 83\nHot 58 48 53 35\nSweet 29 76 86 43\nBitter 24 39 40 1" }, { "code": null, "e": 2706, "s": 2678, "text": "as.data.frame(as.table(M3))" }, { "code": null, "e": 3003, "s": 2706, "text": "Var1 Var2 Freq\n1 Cold Winter 15\n2 Hot Winter 58\n3 Sweet Winter 29\n4 Bitter Winter 24\n5 Cold Autumn 42\n6 Hot Autumn 48\n7 Sweet Autumn 76\n8 Bitter Autumn 39\n9 Cold Rainy 97\n10 Hot Rainy 53\n11 Sweet Rainy 86\n12 Bitter Rainy 40\n13 Cold Summer 83\n14 Hot Summer 35\n15 Sweet Summer 43\n16 Bitter Summer 1" } ]
Dart Programming - floor Method
This method returns the largest integer less than or equal to a number. Number.floor() Returns the largest integer less than or equal to a number x. void main() { var a = 2.9; print("The floor value of 2.9 = ${a.floor()}"); } It will produce the following output −. The floor value of 2.9 = 2 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": 2597, "s": 2525, "text": "This method returns the largest integer less than or equal to a number." }, { "code": null, "e": 2613, "s": 2597, "text": "Number.floor()\n" }, { "code": null, "e": 2675, "s": 2613, "text": "Returns the largest integer less than or equal to a number x." }, { "code": null, "e": 2762, "s": 2675, "text": "void main() { \n var a = 2.9; \n print(\"The floor value of 2.9 = ${a.floor()}\"); \n} " }, { "code": null, "e": 2802, "s": 2762, "text": "It will produce the following output −." }, { "code": null, "e": 2830, "s": 2802, "text": "The floor value of 2.9 = 2\n" }, { "code": null, "e": 2865, "s": 2830, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2885, "s": 2865, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2918, "s": 2885, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 2938, "s": 2918, "text": " Sriyank Siddhartha" }, { "code": null, "e": 2971, "s": 2938, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 2988, "s": 2971, "text": " Frahaan Hussain" }, { "code": null, "e": 3023, "s": 2988, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3040, "s": 3023, "text": " Frahaan Hussain" }, { "code": null, "e": 3075, "s": 3040, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3095, "s": 3075, "text": " Pranjal Srivastava" }, { "code": null, "e": 3128, "s": 3095, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3148, "s": 3128, "text": " Pranjal Srivastava" }, { "code": null, "e": 3155, "s": 3148, "text": " Print" }, { "code": null, "e": 3166, "s": 3155, "text": " Add Notes" } ]
Spring - Environment Setup
This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Tomcat and Eclipse on your machine before you set up Spring Framework − You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:\jdk1.6.0_15, you would have to put the following line in your C:\autoexec.bat file. set PATH=C:\jdk1.6.0_15\bin;%PATH% set JAVA_HOME=C:\jdk1.6.0_15 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.6.0_15 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. You can download the latest version of Apache Commons Logging API from https://commons.apache.org/logging/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\commons-logging-1.1.1 on Windows, or /usr/local/commons-logging-1.1.1 on Linux/Unix. This directory will have the following jar files and other supporting documents, etc. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Now if everything is fine, then you can proceed to set up your Spring framework. Following are the simple steps to download and install the framework on your machine. Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix. Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix. Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring. Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring. At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\spring. At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\spring. You will find all the Spring libraries in the directory E:\spring\libs. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the setting will be done through Eclipse. Once you are done with this last step, you are ready to proceed to your first Spring Example in the next chapter. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2292, "text": "This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Tomcat and Eclipse on your machine before you set up Spring Framework −" }, { "code": null, "e": 2916, "s": 2520, "text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 3060, "s": 2916, "text": "If you are running Windows and have installed the JDK in C:\\jdk1.6.0_15, you would have to put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 3127, "s": 3060, "text": "set PATH=C:\\jdk1.6.0_15\\bin;%PATH% \nset JAVA_HOME=C:\\jdk1.6.0_15 \n" }, { "code": null, "e": 3334, "s": 3127, "text": "Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button." }, { "code": null, "e": 3499, "s": 3334, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you will have to put the following into your .cshrc file." }, { "code": null, "e": 3587, "s": 3499, "text": "setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH \nsetenv JAVA_HOME /usr/local/jdk1.6.0_15 \n" }, { "code": null, "e": 3924, "s": 3587, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE." }, { "code": null, "e": 4317, "s": 3924, "text": "You can download the latest version of Apache Commons Logging API from https://commons.apache.org/logging/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\commons-logging-1.1.1 on Windows, or /usr/local/commons-logging-1.1.1 on Linux/Unix. This directory will have the following jar files and other supporting documents, etc." }, { "code": null, "e": 4452, "s": 4317, "text": "Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application." }, { "code": null, "e": 4616, "s": 4452, "text": "All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine." }, { "code": null, "e": 4933, "s": 4616, "text": "To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately." }, { "code": null, "e": 5058, "s": 4933, "text": "Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe" }, { "code": null, "e": 5084, "s": 5058, "text": "%C:\\eclipse\\eclipse.exe \n" }, { "code": null, "e": 5184, "s": 5084, "text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 5213, "s": 5184, "text": "$/usr/local/eclipse/eclipse\n" }, { "code": null, "e": 5309, "s": 5213, "text": "After a successful startup, if everything is fine then it should display the following result −" }, { "code": null, "e": 5476, "s": 5309, "text": "Now if everything is fine, then you can proceed to set up your Spring framework. Following are the simple steps to download and install the framework on your machine." }, { "code": null, "e": 5636, "s": 5476, "text": "Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix." }, { "code": null, "e": 5796, "s": 5636, "text": "Make a choice whether you want to install Spring on Windows or Unix, and then proceed to the next step to download .zip file for Windows and .tz file for Unix." }, { "code": null, "e": 5918, "s": 5796, "text": "Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring." }, { "code": null, "e": 6040, "s": 5918, "text": "Download the latest version of Spring framework binaries from https://repo.spring.io/release/org/springframework/spring." }, { "code": null, "e": 6257, "s": 6040, "text": "At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\\spring." }, { "code": null, "e": 6474, "s": 6257, "text": "At the time of developing this tutorial, spring-framework-4.1.6.RELEASE-dist.zip was downloaded on Windows machine. After the downloaded file was unzipped, it gives the following directory structure inside E:\\spring." }, { "code": null, "e": 6802, "s": 6474, "text": "You will find all the Spring libraries in the directory E:\\spring\\libs. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the setting will be done through Eclipse." }, { "code": null, "e": 6916, "s": 6802, "text": "Once you are done with this last step, you are ready to proceed to your first Spring Example in the next chapter." }, { "code": null, "e": 6950, "s": 6916, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 6964, "s": 6950, "text": " Karthikeya T" }, { "code": null, "e": 6997, "s": 6964, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 7012, "s": 6997, "text": " Chaand Sheikh" }, { "code": null, "e": 7047, "s": 7012, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7059, "s": 7047, "text": " Senol Atac" }, { "code": null, "e": 7094, "s": 7059, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7106, "s": 7094, "text": " Senol Atac" }, { "code": null, "e": 7141, "s": 7106, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7153, "s": 7141, "text": " Senol Atac" }, { "code": null, "e": 7186, "s": 7153, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7198, "s": 7186, "text": " Senol Atac" }, { "code": null, "e": 7205, "s": 7198, "text": " Print" }, { "code": null, "e": 7216, "s": 7205, "text": " Add Notes" } ]
How to Use Transformers in TensorFlow | Towards Data Science
Transformers are, without a doubt, one of the biggest advances in NLP in the past decade. They have (quite fittingly) transformed the landscape of language-based ML. Despite this, there are no built-in implementations of transformer models in the core TensorFlow or PyTorch frameworks. To use them, you either need to apply for the relevant Ph.D. program, and we’ll see you in three years — or you pip install transformers. Although this is simplifying the process a little — in reality, it really is incredibly easy to get up and running with some of the most cutting-edge models out there (think BERT and GPT-2). When using Huggingface’s transformers library, we have the option of implementing it via TensorFlow or PyTorch. We will be covering everything you need to know to get started with the TensorFlow flavor in this article. What is HuggingFace? - Finding Models - Visualing AttentionTensorFlow 1. Pre-Processing 2. Tokenizer and Model 3. Encoding Inputs 4. Full Model Architecture 5. Metrics, Loss, and Optimizer 6. TrainingResults If you prefer video, I’ve covered the full build process here too: HuggingFace is a company building and maintaining the hugely popular Transformers library. We can easily hit the ground running with the majority of the big, most cutting-edge transformer models available today through this library. To download and begin working with some of the biggest models out there, including (but not limited to) — BERT, RoBERTa, GPT, GPT-2, XLNet, and HuggingFace’s own DistilBERT and DistilGPT-2 — it takes no more than three lines of code, which look like this: from transformers import TFAutoModel, AutoTokenizermodel = TFAutoModel.from_pretrained("<model-name>")tokenizer = AutoTokenizer.from_pretrained("<model-name>") Not only can we access all of these models with incredible ease, but we can even take advantage of prebuilt transformers for question and answering, sentiment analysis, text summarization, and much more. It’s a hugely popular library, built by an incredibly talented team, democratizing some of the most powerful models at the cutting-edge of NLP. HuggingFace has built an incredible ecosystem that provides an insanely large number of ready-to-use transformers, the full list of which we can find here. Both community-built and HuggingFace-built models are available. We can filter for models via the Tags dropdown. We can search based on the framework they are built with, such as PyTorch/TensorFlow — it’s use-case such as classification, QnA, etc. We will be using TensorFlow, and we can see a list of the most popular models using this filter. Uncased/cased refers to whether the model will identify a difference between lowercase and uppercase characters — which can be important in understanding text sentiment. The bert-base-cased model fits our use-case, and we will be implementing this model (later) using the instructions provided on the model page. As a brief but interesting side-note, HuggingFace, alongside IBM Research and Harvard NLP, have built an incredibly fascinating tool for visualizing the attention in several transformer models with exBERT lite. TensorFlow support in the transformers library came later than that for PyTorch, meaning the majority of articles you read on the topic will show you how to integrate HuggingFace and PyTorch — but not TensorFlow. Of-course, the steps are slightly different — but at a high-level, the process is the same: Pre-process the dataInitialize the HuggingFace tokenizer and modelEncode input data to get input IDs and attention masksBuild the full model architecture (integrating the HuggingFace model)Setup optimizer, metrics, and lossTraining Pre-process the data Initialize the HuggingFace tokenizer and model Encode input data to get input IDs and attention masks Build the full model architecture (integrating the HuggingFace model) Setup optimizer, metrics, and loss Training We will cover each of these steps — but focusing primarily on steps 2–4. First, we need to prepare our data for our transformer model. What is done here will depend very much on the data and use-case. We will be taking some clean data and processing it with BERT as a classifier for sentiment analysis. We can use the IMDB movie review dataset, which provides us with sentiment ratings from 0 (terrible) to 4 (amazing). You can get the dataset here — or via the Kaggle API: Because there are a lot of sentence fragments, these can easily pollute the validation set with near-matches to that in the training set. So, I removed them using drop_duplicates, keeping the first record of each unique SentenceId (the full review, meaning we drop all review segments). All we need to do at this point is one-hot encode our sentiment labels, like so: We will be using the HuggingFace transformers library to source our transformer models. A smaller transformer model available to us is DistilBERT — a smaller version of BERT with ~40% of the parameters while maintaining ~95% of the accuracy. DistilBERT is a good option for anyone working with less compute. Just switch out bert-base-cased for distilbert-base-cased below. We initialize the BERT tokenizer and model like so: It really is as easy as that! We have our input data and tokenizer ready, so now we can encode our input data into two arrays — (1) the input IDs and (2) the attention mask. Input IDs are simply a set of integers that represent a word, “hello” could be 0, “world” might be 1. But, BERT uses a predefined set of mappings — hence why we loaded our tokenizer using the .from_pretrained method. There are several special tokens that are used by BERT. These are: Once we have our sequences, we can encode them withtokenizer.encode_plus: Where SEQ_LEN=50, the output of the input IDs will look like this: Next up is the attention mask. This mask is simply an array of 0s and 1s where each 1 represents a valid word/input ID, and a 0 represents padding. The encode_plus method outputs both input IDs and the attention mask tensors inside a dictionary: BERT's attention layers consume this mask and apply attention operations to word embedding that corresponds to a 1 while ignoring those matching up with a 0. The effect of this is that we only apply attention to real words, while additional padding tokens are ignored. We have our encoded inputs IDs and attention masks, and the initialized BERT model — now, we need to add the additional layers required for inputting the input ID and attention mask arrays and the layers required for classifying the BERT output into sentiment ratings. For every BERT-based transformer model, we need two input layers that match our sequence length. We encoded our inputs to a length of 50 tokens — so we use an input shape of (50,) here: Both our input IDs and attention mask arrays contain integers only, so we specify dtype='int32'. More importantly, the layer names must match the key-value pairs in our data inputs, for which we have two options: (1) We keep input and output arrays as seperate variablesmodel.fit({"input_ids": input_ids, "attention_mask": mask}, labels=labels)(2) We place them into a tf.data.Dataset object beforehandmodel.fit(dataset) We won’t cover option (2) any further than this here — but if you’re working with a lot of data, it’s a much better option (which you can read about here). Next up are our classification layers. These will take the output from our BERT model and produce one of our three sentiment labels — there are a lot of ways to do this, but we will keep it simple: Here we pull the outputs from distilbert and use a MaxPooling layer to convert the tensor from 3D to 2D — alternatively, use a 3D network (like convolutional or recurrent neural nets) followed by MaxPooling. When we put all of this together we get the following: If you are wanting to train the transformer parameters further, the final line is not necessary! We choose not to as BERT is already an incredibly well built and fine-tuned model. It would take a very long time to train, so for the likely minuscule performance increase — there’s little justification. Our model summary shows the two input layers, BERT, and our final classification layers. We have a total of 108M+ parameters, of which just 100K are trainable because we froze the BERT parameters. Here we are returning to the standard TensorFlow build process. First, we use the optimizer we all know and love. Next, we use category cross-entry and categorical accuracy for our loss and single metric. Because we have one-hot encoded our outputs, we use Categorical. Alternatively, we can avoid one-hot encoding our outputs and use losses.SparseCategoricalCrossentropy(from_logits=True) with metrics.SparseCategoricalAccuracy('accuracy'). Finally, we compile our model with the .compile method — we are now ready to begin training! Note: If training BERT layers too, try Adam optimizer with weight decay — which can help reduce overfitting and improve generalization [1]. I would recommend this article for understanding why. import tensorflow_addons as tfa # Adam with weight decayoptimizer = tfa.optimizers.AdamW(0.005, learning_rate=0.01) We train as per usual using the fit method. If not using a tf.data.Dataset object we must explicitly state our multiple inputs using a dictionary. All this requires is: Training will take a long time with most GPUs —for those of you on CPU only, good luck! If you are stuck on CPU, try out Google Colab — it’s a free, cloud-based notebook service provided by Google. Colab includes a GPU as standard — albeit not a particularly powerful one (but it is free). Here is a full version of the code: After several hours training on my measly 940MX we get a validation accuracy of 94.9% — with more training epochs, the model looks like will easily improve on this too: These are pretty great results for such a simple output network. Further fine-tuning, the addition of CNNs, LSTMs, or other more expressive networks may improve our results even further. Alternatively, (although I found this to be detrimental) we can even use BERTs pre-pooled output tensors by swapping out last_hidden_state with pooler_output — but that is for another time. I hope you’ve enjoyed this article on integrating TF2 and HuggingFace’s transformers library. If you’d like more, I post programming/ML tutorials on YouTube here! If you have any questions, let me know via Twitter or in the comments below. Thanks for reading! [1] I. Loshchilov, F. Hutter, Decoupled Weight Decay Regularization (2019), ICLR 🤖 NLP With Transformers Course *All images are by the author except where stated otherwise
[ { "code": null, "e": 338, "s": 172, "text": "Transformers are, without a doubt, one of the biggest advances in NLP in the past decade. They have (quite fittingly) transformed the landscape of language-based ML." }, { "code": null, "e": 596, "s": 338, "text": "Despite this, there are no built-in implementations of transformer models in the core TensorFlow or PyTorch frameworks. To use them, you either need to apply for the relevant Ph.D. program, and we’ll see you in three years — or you pip install transformers." }, { "code": null, "e": 787, "s": 596, "text": "Although this is simplifying the process a little — in reality, it really is incredibly easy to get up and running with some of the most cutting-edge models out there (think BERT and GPT-2)." }, { "code": null, "e": 1006, "s": 787, "text": "When using Huggingface’s transformers library, we have the option of implementing it via TensorFlow or PyTorch. We will be covering everything you need to know to get started with the TensorFlow flavor in this article." }, { "code": null, "e": 1222, "s": 1006, "text": "What is HuggingFace? - Finding Models - Visualing AttentionTensorFlow 1. Pre-Processing 2. Tokenizer and Model 3. Encoding Inputs 4. Full Model Architecture 5. Metrics, Loss, and Optimizer 6. TrainingResults" }, { "code": null, "e": 1289, "s": 1222, "text": "If you prefer video, I’ve covered the full build process here too:" }, { "code": null, "e": 1522, "s": 1289, "text": "HuggingFace is a company building and maintaining the hugely popular Transformers library. We can easily hit the ground running with the majority of the big, most cutting-edge transformer models available today through this library." }, { "code": null, "e": 1778, "s": 1522, "text": "To download and begin working with some of the biggest models out there, including (but not limited to) — BERT, RoBERTa, GPT, GPT-2, XLNet, and HuggingFace’s own DistilBERT and DistilGPT-2 — it takes no more than three lines of code, which look like this:" }, { "code": null, "e": 1938, "s": 1778, "text": "from transformers import TFAutoModel, AutoTokenizermodel = TFAutoModel.from_pretrained(\"<model-name>\")tokenizer = AutoTokenizer.from_pretrained(\"<model-name>\")" }, { "code": null, "e": 2142, "s": 1938, "text": "Not only can we access all of these models with incredible ease, but we can even take advantage of prebuilt transformers for question and answering, sentiment analysis, text summarization, and much more." }, { "code": null, "e": 2286, "s": 2142, "text": "It’s a hugely popular library, built by an incredibly talented team, democratizing some of the most powerful models at the cutting-edge of NLP." }, { "code": null, "e": 2507, "s": 2286, "text": "HuggingFace has built an incredible ecosystem that provides an insanely large number of ready-to-use transformers, the full list of which we can find here. Both community-built and HuggingFace-built models are available." }, { "code": null, "e": 2690, "s": 2507, "text": "We can filter for models via the Tags dropdown. We can search based on the framework they are built with, such as PyTorch/TensorFlow — it’s use-case such as classification, QnA, etc." }, { "code": null, "e": 2957, "s": 2690, "text": "We will be using TensorFlow, and we can see a list of the most popular models using this filter. Uncased/cased refers to whether the model will identify a difference between lowercase and uppercase characters — which can be important in understanding text sentiment." }, { "code": null, "e": 3100, "s": 2957, "text": "The bert-base-cased model fits our use-case, and we will be implementing this model (later) using the instructions provided on the model page." }, { "code": null, "e": 3311, "s": 3100, "text": "As a brief but interesting side-note, HuggingFace, alongside IBM Research and Harvard NLP, have built an incredibly fascinating tool for visualizing the attention in several transformer models with exBERT lite." }, { "code": null, "e": 3524, "s": 3311, "text": "TensorFlow support in the transformers library came later than that for PyTorch, meaning the majority of articles you read on the topic will show you how to integrate HuggingFace and PyTorch — but not TensorFlow." }, { "code": null, "e": 3616, "s": 3524, "text": "Of-course, the steps are slightly different — but at a high-level, the process is the same:" }, { "code": null, "e": 3848, "s": 3616, "text": "Pre-process the dataInitialize the HuggingFace tokenizer and modelEncode input data to get input IDs and attention masksBuild the full model architecture (integrating the HuggingFace model)Setup optimizer, metrics, and lossTraining" }, { "code": null, "e": 3869, "s": 3848, "text": "Pre-process the data" }, { "code": null, "e": 3916, "s": 3869, "text": "Initialize the HuggingFace tokenizer and model" }, { "code": null, "e": 3971, "s": 3916, "text": "Encode input data to get input IDs and attention masks" }, { "code": null, "e": 4041, "s": 3971, "text": "Build the full model architecture (integrating the HuggingFace model)" }, { "code": null, "e": 4076, "s": 4041, "text": "Setup optimizer, metrics, and loss" }, { "code": null, "e": 4085, "s": 4076, "text": "Training" }, { "code": null, "e": 4158, "s": 4085, "text": "We will cover each of these steps — but focusing primarily on steps 2–4." }, { "code": null, "e": 4388, "s": 4158, "text": "First, we need to prepare our data for our transformer model. What is done here will depend very much on the data and use-case. We will be taking some clean data and processing it with BERT as a classifier for sentiment analysis." }, { "code": null, "e": 4505, "s": 4388, "text": "We can use the IMDB movie review dataset, which provides us with sentiment ratings from 0 (terrible) to 4 (amazing)." }, { "code": null, "e": 4559, "s": 4505, "text": "You can get the dataset here — or via the Kaggle API:" }, { "code": null, "e": 4846, "s": 4559, "text": "Because there are a lot of sentence fragments, these can easily pollute the validation set with near-matches to that in the training set. So, I removed them using drop_duplicates, keeping the first record of each unique SentenceId (the full review, meaning we drop all review segments)." }, { "code": null, "e": 4927, "s": 4846, "text": "All we need to do at this point is one-hot encode our sentiment labels, like so:" }, { "code": null, "e": 5169, "s": 4927, "text": "We will be using the HuggingFace transformers library to source our transformer models. A smaller transformer model available to us is DistilBERT — a smaller version of BERT with ~40% of the parameters while maintaining ~95% of the accuracy." }, { "code": null, "e": 5352, "s": 5169, "text": "DistilBERT is a good option for anyone working with less compute. Just switch out bert-base-cased for distilbert-base-cased below. We initialize the BERT tokenizer and model like so:" }, { "code": null, "e": 5382, "s": 5352, "text": "It really is as easy as that!" }, { "code": null, "e": 5526, "s": 5382, "text": "We have our input data and tokenizer ready, so now we can encode our input data into two arrays — (1) the input IDs and (2) the attention mask." }, { "code": null, "e": 5743, "s": 5526, "text": "Input IDs are simply a set of integers that represent a word, “hello” could be 0, “world” might be 1. But, BERT uses a predefined set of mappings — hence why we loaded our tokenizer using the .from_pretrained method." }, { "code": null, "e": 5810, "s": 5743, "text": "There are several special tokens that are used by BERT. These are:" }, { "code": null, "e": 5884, "s": 5810, "text": "Once we have our sequences, we can encode them withtokenizer.encode_plus:" }, { "code": null, "e": 5951, "s": 5884, "text": "Where SEQ_LEN=50, the output of the input IDs will look like this:" }, { "code": null, "e": 6197, "s": 5951, "text": "Next up is the attention mask. This mask is simply an array of 0s and 1s where each 1 represents a valid word/input ID, and a 0 represents padding. The encode_plus method outputs both input IDs and the attention mask tensors inside a dictionary:" }, { "code": null, "e": 6355, "s": 6197, "text": "BERT's attention layers consume this mask and apply attention operations to word embedding that corresponds to a 1 while ignoring those matching up with a 0." }, { "code": null, "e": 6466, "s": 6355, "text": "The effect of this is that we only apply attention to real words, while additional padding tokens are ignored." }, { "code": null, "e": 6735, "s": 6466, "text": "We have our encoded inputs IDs and attention masks, and the initialized BERT model — now, we need to add the additional layers required for inputting the input ID and attention mask arrays and the layers required for classifying the BERT output into sentiment ratings." }, { "code": null, "e": 6921, "s": 6735, "text": "For every BERT-based transformer model, we need two input layers that match our sequence length. We encoded our inputs to a length of 50 tokens — so we use an input shape of (50,) here:" }, { "code": null, "e": 7134, "s": 6921, "text": "Both our input IDs and attention mask arrays contain integers only, so we specify dtype='int32'. More importantly, the layer names must match the key-value pairs in our data inputs, for which we have two options:" }, { "code": null, "e": 7351, "s": 7134, "text": "(1) We keep input and output arrays as seperate variablesmodel.fit({\"input_ids\": input_ids, \"attention_mask\": mask}, labels=labels)(2) We place them into a tf.data.Dataset object beforehandmodel.fit(dataset)" }, { "code": null, "e": 7507, "s": 7351, "text": "We won’t cover option (2) any further than this here — but if you’re working with a lot of data, it’s a much better option (which you can read about here)." }, { "code": null, "e": 7705, "s": 7507, "text": "Next up are our classification layers. These will take the output from our BERT model and produce one of our three sentiment labels — there are a lot of ways to do this, but we will keep it simple:" }, { "code": null, "e": 7913, "s": 7705, "text": "Here we pull the outputs from distilbert and use a MaxPooling layer to convert the tensor from 3D to 2D — alternatively, use a 3D network (like convolutional or recurrent neural nets) followed by MaxPooling." }, { "code": null, "e": 7968, "s": 7913, "text": "When we put all of this together we get the following:" }, { "code": null, "e": 8270, "s": 7968, "text": "If you are wanting to train the transformer parameters further, the final line is not necessary! We choose not to as BERT is already an incredibly well built and fine-tuned model. It would take a very long time to train, so for the likely minuscule performance increase — there’s little justification." }, { "code": null, "e": 8467, "s": 8270, "text": "Our model summary shows the two input layers, BERT, and our final classification layers. We have a total of 108M+ parameters, of which just 100K are trainable because we froze the BERT parameters." }, { "code": null, "e": 8531, "s": 8467, "text": "Here we are returning to the standard TensorFlow build process." }, { "code": null, "e": 8737, "s": 8531, "text": "First, we use the optimizer we all know and love. Next, we use category cross-entry and categorical accuracy for our loss and single metric. Because we have one-hot encoded our outputs, we use Categorical." }, { "code": null, "e": 8909, "s": 8737, "text": "Alternatively, we can avoid one-hot encoding our outputs and use losses.SparseCategoricalCrossentropy(from_logits=True) with metrics.SparseCategoricalAccuracy('accuracy')." }, { "code": null, "e": 9002, "s": 8909, "text": "Finally, we compile our model with the .compile method — we are now ready to begin training!" }, { "code": null, "e": 9196, "s": 9002, "text": "Note: If training BERT layers too, try Adam optimizer with weight decay — which can help reduce overfitting and improve generalization [1]. I would recommend this article for understanding why." }, { "code": null, "e": 9313, "s": 9196, "text": "import tensorflow_addons as tfa # Adam with weight decayoptimizer = tfa.optimizers.AdamW(0.005, learning_rate=0.01)" }, { "code": null, "e": 9482, "s": 9313, "text": "We train as per usual using the fit method. If not using a tf.data.Dataset object we must explicitly state our multiple inputs using a dictionary. All this requires is:" }, { "code": null, "e": 9570, "s": 9482, "text": "Training will take a long time with most GPUs —for those of you on CPU only, good luck!" }, { "code": null, "e": 9772, "s": 9570, "text": "If you are stuck on CPU, try out Google Colab — it’s a free, cloud-based notebook service provided by Google. Colab includes a GPU as standard — albeit not a particularly powerful one (but it is free)." }, { "code": null, "e": 9808, "s": 9772, "text": "Here is a full version of the code:" }, { "code": null, "e": 9977, "s": 9808, "text": "After several hours training on my measly 940MX we get a validation accuracy of 94.9% — with more training epochs, the model looks like will easily improve on this too:" }, { "code": null, "e": 10164, "s": 9977, "text": "These are pretty great results for such a simple output network. Further fine-tuning, the addition of CNNs, LSTMs, or other more expressive networks may improve our results even further." }, { "code": null, "e": 10354, "s": 10164, "text": "Alternatively, (although I found this to be detrimental) we can even use BERTs pre-pooled output tensors by swapping out last_hidden_state with pooler_output — but that is for another time." }, { "code": null, "e": 10517, "s": 10354, "text": "I hope you’ve enjoyed this article on integrating TF2 and HuggingFace’s transformers library. If you’d like more, I post programming/ML tutorials on YouTube here!" }, { "code": null, "e": 10594, "s": 10517, "text": "If you have any questions, let me know via Twitter or in the comments below." }, { "code": null, "e": 10614, "s": 10594, "text": "Thanks for reading!" }, { "code": null, "e": 10695, "s": 10614, "text": "[1] I. Loshchilov, F. Hutter, Decoupled Weight Decay Regularization (2019), ICLR" }, { "code": null, "e": 10726, "s": 10695, "text": "🤖 NLP With Transformers Course" } ]
Find the average of k digits from the beginning and l digits from the end of the given number - GeeksforGeeks
26 Mar, 2021 Given three integers N, K and L. The task is to find the average of the first K digits and the last L digits of the given number N without any digit overlapping.Examples: Input: N = 123456, K = 2, L = 3 Output: 3.0 Sum of first K digits will be 1 + 2 = 3 Sum of last L digits will be 4 + 5 + 6 = 15 Average = (3 + 15) / (2 + 3) = 18 / 5 = 3Input: N = 456966, K = 1, L = 1 Output: 5.0 Approach: If the count of digits in n is less than (K + L) then it isn’t possible to find the average without digits overlapping and print -1 in that case. If that’s not the case, find the sum of the last L digits of N and store it in a variable say sum1 then find the sum of the first K digits of N and store it in sum2. Now, print the average as (sum1 + sum2) / (K + L).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of digits in numint countDigits(int num){ int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt;} // Function to return the sum// of first n digits of numint sumFromStart(int num, int n, int rem){ // Remove the unnecessary digits num /= ((int)pow(10, rem)); int sum = 0; while (num > 0) { sum += (num % 10); num /= 10; } return sum;} // Function to return the sum// of the last n digits of numint sumFromEnd(int num, int n){ int sum = 0; for (int i = 0; i < n; i++) { sum += (num % 10); num /= 10; } return sum;} float getAverage(int n, int k, int l){ // If the average can't be calculated without // using the same digit more than once int totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n int sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning int sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ((float)(sum1 + sum2) / (float)(k + l));} // Driver codeint main(){ int n = 123456, k = 2, l = 3; cout << getAverage(n, k, l); return 0;} // This code is contributed by PrinciRaj1992 // Java implementation of the approachclass GFG { // Function to return the count // of digits in num public static int countDigits(int num) { int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt; } // Function to return the sum // of first n digits of num public static int sumFromStart(int num, int n, int rem) { // Remove the unnecessary digits num /= ((int)Math.pow(10, rem)); int sum = 0; while (num > 0) { sum += (num % 10); num /= 10; } return sum; } // Function to return the sum // of the last n digits of num public static int sumFromEnd(int num, int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += (num % 10); num /= 10; } return sum; } public static float getAverage(int n, int k, int l) { // If the average can't be calculated without // using the same digit more than once int totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n int sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning int sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ((float)(sum1 + sum2) / (float)(k + l)); } // Driver code public static void main(String args[]) { int n = 123456, k = 2, l = 3; System.out.print(getAverage(n, k, l)); }} # implementation of the approachfrom math import pow # Function to return the count# of digits in numdef countDigits(num): cnt = 0 while (num > 0): cnt += 1 num //= 10 return cnt # Function to return the sum# of first n digits of numdef sumFromStart(num, n, rem): # Remove the unnecessary digits num //= pow(10, rem) sum = 0 while (num > 0): sum += (num % 10) num //= 10 return sum # Function to return the sum# of the last n digits of numdef sumFromEnd(num, n): sum = 0 for i in range(n): sum += (num % 10) num //= 10 return sum def getAverage(n, k, l): # If the average can't be calculated without # using the same digit more than once totalDigits = countDigits(n) if (totalDigits < (k + l)): return -1 # Sum of the last l digits of n sum1 = sumFromEnd(n, l) # Sum of the first k digits of n # (totalDigits - k) must be removed from the # end of the number to get the remaining # k digits from the beginning sum2 = sumFromStart(n, k, totalDigits - k) # Return the average return (sum1 + sum2) / (k + l) # Driver codeif __name__ == '__main__': n = 123456 k = 2 l = 3 print(getAverage(n, k, l)) # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function to return the count // of digits in num public static int countDigits(int num) { int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt; } // Function to return the sum // of first n digits of num public static int sumFromStart(int num, int n, int rem) { // Remove the unnecessary digits num /= ((int)Math.Pow(10, rem)); int sum = 0; while (num > 0) { sum += (num % 10); num /= 10; } return sum; } // Function to return the sum // of the last n digits of num public static int sumFromEnd(int num, int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += (num % 10); num /= 10; } return sum; } public static float getAverage(int n, int k, int l) { // If the average can't be calculated without // using the same digit more than once int totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n int sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning int sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ((float)(sum1 + sum2) / (float)(k + l)); } // Driver code public static void Main(String []args) { int n = 123456, k = 2, l = 3; Console.WriteLine(getAverage(n, k, l)); }} // This code is contributed by Princi Singh <script>// javascript implementation of the approach // Function to return the count // of digits in num function countDigits(num) { var cnt = 0; while (num > 0) { cnt++; num = parseInt(num/10); } return cnt; } // Function to return the sum // of first n digits of num function sumFromStart(num, n, rem) { // Remove the unnecessary digits num = (parseInt( num/Math.pow(10, rem))); var sum = 0; while (num > 0) { sum += (num % 10); num = parseInt(num/10); } return sum; } // Function to return the sum // of the last n digits of num function sumFromEnd(num , n) { var sum = 0; for (i = 0; i < n; i++) { sum += (num % 10); num = parseInt(num/10); } return sum; } function getAverage(n , k , l) { // If the average can't be calculated without // using the same digit more than once var totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n var sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning var sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ( (sum1 + sum2) / (k + l)); } // Driver code var n = 123456, k = 2, l = 3; document.write(getAverage(n, k, l)); // This code is contributed by Rajput-Ji</script> 3.6 princi singh princiraj1992 SURENDRA_GANGWAR Rajput-Ji Numbers Mathematical Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Check if a number is Palindrome Find first and last digits of a number Count ways to reach the n'th stair Program to convert a given number to words Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 24692, "s": 24664, "text": "\n26 Mar, 2021" }, { "code": null, "e": 24865, "s": 24692, "text": "Given three integers N, K and L. The task is to find the average of the first K digits and the last L digits of the given number N without any digit overlapping.Examples: " }, { "code": null, "e": 25080, "s": 24865, "text": "Input: N = 123456, K = 2, L = 3 Output: 3.0 Sum of first K digits will be 1 + 2 = 3 Sum of last L digits will be 4 + 5 + 6 = 15 Average = (3 + 15) / (2 + 3) = 18 / 5 = 3Input: N = 456966, K = 1, L = 1 Output: 5.0 " }, { "code": null, "e": 25507, "s": 25082, "text": "Approach: If the count of digits in n is less than (K + L) then it isn’t possible to find the average without digits overlapping and print -1 in that case. If that’s not the case, find the sum of the last L digits of N and store it in a variable say sum1 then find the sum of the first K digits of N and store it in sum2. Now, print the average as (sum1 + sum2) / (K + L).Below is the implementation of the above approach: " }, { "code": null, "e": 25511, "s": 25507, "text": "C++" }, { "code": null, "e": 25516, "s": 25511, "text": "Java" }, { "code": null, "e": 25524, "s": 25516, "text": "Python3" }, { "code": null, "e": 25527, "s": 25524, "text": "C#" }, { "code": null, "e": 25538, "s": 25527, "text": "Javascript" }, { "code": "// implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of digits in numint countDigits(int num){ int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt;} // Function to return the sum// of first n digits of numint sumFromStart(int num, int n, int rem){ // Remove the unnecessary digits num /= ((int)pow(10, rem)); int sum = 0; while (num > 0) { sum += (num % 10); num /= 10; } return sum;} // Function to return the sum// of the last n digits of numint sumFromEnd(int num, int n){ int sum = 0; for (int i = 0; i < n; i++) { sum += (num % 10); num /= 10; } return sum;} float getAverage(int n, int k, int l){ // If the average can't be calculated without // using the same digit more than once int totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n int sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning int sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ((float)(sum1 + sum2) / (float)(k + l));} // Driver codeint main(){ int n = 123456, k = 2, l = 3; cout << getAverage(n, k, l); return 0;} // This code is contributed by PrinciRaj1992", "e": 27009, "s": 25538, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the count // of digits in num public static int countDigits(int num) { int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt; } // Function to return the sum // of first n digits of num public static int sumFromStart(int num, int n, int rem) { // Remove the unnecessary digits num /= ((int)Math.pow(10, rem)); int sum = 0; while (num > 0) { sum += (num % 10); num /= 10; } return sum; } // Function to return the sum // of the last n digits of num public static int sumFromEnd(int num, int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += (num % 10); num /= 10; } return sum; } public static float getAverage(int n, int k, int l) { // If the average can't be calculated without // using the same digit more than once int totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n int sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning int sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ((float)(sum1 + sum2) / (float)(k + l)); } // Driver code public static void main(String args[]) { int n = 123456, k = 2, l = 3; System.out.print(getAverage(n, k, l)); }}", "e": 28704, "s": 27009, "text": null }, { "code": "# implementation of the approachfrom math import pow # Function to return the count# of digits in numdef countDigits(num): cnt = 0 while (num > 0): cnt += 1 num //= 10 return cnt # Function to return the sum# of first n digits of numdef sumFromStart(num, n, rem): # Remove the unnecessary digits num //= pow(10, rem) sum = 0 while (num > 0): sum += (num % 10) num //= 10 return sum # Function to return the sum# of the last n digits of numdef sumFromEnd(num, n): sum = 0 for i in range(n): sum += (num % 10) num //= 10 return sum def getAverage(n, k, l): # If the average can't be calculated without # using the same digit more than once totalDigits = countDigits(n) if (totalDigits < (k + l)): return -1 # Sum of the last l digits of n sum1 = sumFromEnd(n, l) # Sum of the first k digits of n # (totalDigits - k) must be removed from the # end of the number to get the remaining # k digits from the beginning sum2 = sumFromStart(n, k, totalDigits - k) # Return the average return (sum1 + sum2) / (k + l) # Driver codeif __name__ == '__main__': n = 123456 k = 2 l = 3 print(getAverage(n, k, l)) # This code is contributed by# Surendra_Gangwar", "e": 29999, "s": 28704, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count // of digits in num public static int countDigits(int num) { int cnt = 0; while (num > 0) { cnt++; num /= 10; } return cnt; } // Function to return the sum // of first n digits of num public static int sumFromStart(int num, int n, int rem) { // Remove the unnecessary digits num /= ((int)Math.Pow(10, rem)); int sum = 0; while (num > 0) { sum += (num % 10); num /= 10; } return sum; } // Function to return the sum // of the last n digits of num public static int sumFromEnd(int num, int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += (num % 10); num /= 10; } return sum; } public static float getAverage(int n, int k, int l) { // If the average can't be calculated without // using the same digit more than once int totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n int sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning int sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ((float)(sum1 + sum2) / (float)(k + l)); } // Driver code public static void Main(String []args) { int n = 123456, k = 2, l = 3; Console.WriteLine(getAverage(n, k, l)); }} // This code is contributed by Princi Singh", "e": 31820, "s": 29999, "text": null }, { "code": "<script>// javascript implementation of the approach // Function to return the count // of digits in num function countDigits(num) { var cnt = 0; while (num > 0) { cnt++; num = parseInt(num/10); } return cnt; } // Function to return the sum // of first n digits of num function sumFromStart(num, n, rem) { // Remove the unnecessary digits num = (parseInt( num/Math.pow(10, rem))); var sum = 0; while (num > 0) { sum += (num % 10); num = parseInt(num/10); } return sum; } // Function to return the sum // of the last n digits of num function sumFromEnd(num , n) { var sum = 0; for (i = 0; i < n; i++) { sum += (num % 10); num = parseInt(num/10); } return sum; } function getAverage(n , k , l) { // If the average can't be calculated without // using the same digit more than once var totalDigits = countDigits(n); if (totalDigits < (k + l)) return -1; // Sum of the last l digits of n var sum1 = sumFromEnd(n, l); // Sum of the first k digits of n // (totalDigits - k) must be removed from the // end of the number to get the remaining // k digits from the beginning var sum2 = sumFromStart(n, k, totalDigits - k); // Return the average return ( (sum1 + sum2) / (k + l)); } // Driver code var n = 123456, k = 2, l = 3; document.write(getAverage(n, k, l)); // This code is contributed by Rajput-Ji</script>", "e": 33487, "s": 31820, "text": null }, { "code": null, "e": 33491, "s": 33487, "text": "3.6" }, { "code": null, "e": 33506, "s": 33493, "text": "princi singh" }, { "code": null, "e": 33520, "s": 33506, "text": "princiraj1992" }, { "code": null, "e": 33537, "s": 33520, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33547, "s": 33537, "text": "Rajput-Ji" }, { "code": null, "e": 33555, "s": 33547, "text": "Numbers" }, { "code": null, "e": 33568, "s": 33555, "text": "Mathematical" }, { "code": null, "e": 33581, "s": 33568, "text": "Mathematical" }, { "code": null, "e": 33589, "s": 33581, "text": "Numbers" }, { "code": null, "e": 33687, "s": 33589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33719, "s": 33687, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 33763, "s": 33719, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33788, "s": 33763, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33821, "s": 33788, "text": "Program to multiply two matrices" }, { "code": null, "e": 33852, "s": 33821, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33884, "s": 33852, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33923, "s": 33884, "text": "Find first and last digits of a number" }, { "code": null, "e": 33958, "s": 33923, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 34001, "s": 33958, "text": "Program to convert a given number to words" } ]
Python Functions creating iterators for efficient looping
As in most programming languages Python provides while and for statements to form a looping construct. The for statement is especially useful to traverse the iterables like list, tuple or string. More efficient and fast iteration tools are defined in itertools module of Python’s standard library. These iterator building blocks are Pythonic implementations of similar tools in functional programming languages such as Haskell and SML. Functions in itertools module are of three types. Infinite iterators Finite iterators Combinatoric iterators Following functions generate infinite sequences. count() − This function returns an iterator of evenly spaced values from start value. The function can have optional step value to increment successive value by this interval. >>> from itertools import count >>> for x in count(20): print (x) >>> for x in count(100,10): print (x) First statement will generate infinite sequence starting from 20 and second will generate numbers from 100 with stepping frequency 10. Note that the loops are infinite and won’t terminate on their own. They will be terminated on pressing ctrl-C cycle() − This function starts returning each element from given iterable and saves its copy. Once elements are exhausted, elements in saved copy are returned thereby forming infinite loop. >>> from itertools import cycle >>> for x in cycle("hello"): print (x) Characters in the string will be repetitively printed till keyboard interrupt Ctrl-C is issued. repeat() − This function returns the object argument repeatedly. If second argument ‘times’ is provided, repetition takes place that many times. >>> from itertools import repeat >>> for x in repeat(1): print (x) >>> for x in repeat('hello', 10): print (x) First loop will print 1 endlessly. Second one prints 'hello' 10 times. Functions in following category return finite iterators that terminate on shortest input sequence. accumulate() − This function has two parameters. First is an iterable (list, tuple or string). Second parameter by default is operator.add() (function in operator module implementing standard addition operator), but may be any other function receiving two numeric parameters. accumulate(sequence, func) First two elements of input sequence are processed by func. Result of the process is first parameter for next iteration and second parameter to func is third element in input sequence. This process is repeated till the sequence is exhausted. The accumulate function returns an iterator in which each element is accumulated result of processing successive elements. In following example, numbers in the list are cumulatively added. Note that default function argument is add operation. >>> from itertools import accumulate >>> list(accumulate([1,2,3,4,5])) [1, 3, 6, 10, 15] We can have a user defined function as second parameter to accumulate() function >>> def multiply(x,y): return x*y >>> list(accumulate([1,2,3,4,5], multiply)) [1, 2, 6, 24, 120] This behaviour is somewhat similar to built-in reduce() function. The reduce() function returns only the final result of accumulation, whereas accumulate() builds iterator of all intermediate results. chain() − This function can have more than one iterables as parameter. It yields each element of first iterable into resultant iterator and proceeds to next until iterable parameters are exhausted. >>> from itertools import chain >>> list(chain([10,20],'hello',range(4))) [10, 20, 'h', 'e', 'l', 'l', 'o', 0, 1, 2, 3] dropwhile() − This function returns an iterator by dropping elements from terable as long as predicate function argument returns true. The moment the function returns false, all remaining elements are yielded to the iterator. >>> from itertools import dropwhile >>> def iseven(x): if x % 2 == 0: return True else: return False >>> list(dropwhile(iseven, [12,90,61,4,15])) [61, 4, 15] filterfalse() − This function returns an iterator by filtering out elements for whom the predicate function results False. >>> from itertools import filterfalse >>> def iseven(x): if x % 2 == 0: return True else: return False >>> list(filterfalse(iseven, [12,90,61,4,15])) [61, 15] islice() − This function build an iterator by selecting certain elements from iterable. The selection criteria depends on start, stop and step parameters. Selection starts from start value and continues till stop value. If stop is None, it goes upto end of iterable, otherwise selection stops at specified index. Step parameter is 1 by default. Selection of elements increments by step parameter. None of the parameters can be negative. >>> from itertools import islice >>> list(islice(range(10),1,5,2)) [1, 3] >>> list(islice(range(10),0,None,3)) [0, 3, 6, 9] >>> list(islice(range(10),5,None)) [5, 6, 7, 8, 9] >>> list(islice(range(10),5)) [0, 1, 2, 3, 4] Following function generate Combinatoric iterators from iterable objects. product() − This function generates an iterator which is a Cartesian product of elements in input sequences. This is equivalent of constructing nested for loops, one for traversing each iterable sequence. In following example list comprehension technique is used to run two nested loops on two sequences to build Cartesian product. >>> [[x,y] for x in [1,2,3] for y in ['a','b','c']] [[1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, 'b'], [2, 'c'], [3, 'a'], [3, 'b'], [3, 'c']] The product() function produces similar result >>> from itertools import product >>> list(product([1,2,3],['a','b','c'])) [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')] permutations() − This function yields all possible permutations of elements in input iterable. Length of each permutation may be specified as second parameter to this function. If not specified, length is one. >>> list(permutations(range(1,4),2)) [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] combinations() − This function yields all possible combinations of elements in input iterable. Length of each permutation may be specified as second parameter to this function. If not specified, length is one. >>> from itertools import combinations >>> list(combinations(range(1,4),2)) [(1, 2), (1, 3), (2, 3)] This article introduces various iterator tools defined in itertools module of Python library.
[ { "code": null, "e": 1498, "s": 1062, "text": "As in most programming languages Python provides while and for statements to form a looping construct. The for statement is especially useful to traverse the iterables like list, tuple or string. More efficient and fast iteration tools are defined in itertools module of Python’s standard library. These iterator building blocks are Pythonic implementations of similar tools in functional programming languages such as Haskell and SML." }, { "code": null, "e": 1548, "s": 1498, "text": "Functions in itertools module are of three types." }, { "code": null, "e": 1567, "s": 1548, "text": "Infinite iterators" }, { "code": null, "e": 1584, "s": 1567, "text": "Finite iterators" }, { "code": null, "e": 1607, "s": 1584, "text": "Combinatoric iterators" }, { "code": null, "e": 1656, "s": 1607, "text": "Following functions generate infinite sequences." }, { "code": null, "e": 1832, "s": 1656, "text": "count() − This function returns an iterator of evenly spaced values from start value. The function can have optional step value to increment successive value by this interval." }, { "code": null, "e": 1936, "s": 1832, "text": ">>> from itertools import count\n>>> for x in count(20):\nprint (x)\n>>> for x in count(100,10):\nprint (x)" }, { "code": null, "e": 2181, "s": 1936, "text": "First statement will generate infinite sequence starting from 20 and second will generate numbers from 100 with stepping frequency 10. Note that the loops are infinite and won’t terminate on their own. They will be terminated on pressing ctrl-C" }, { "code": null, "e": 2371, "s": 2181, "text": "cycle() − This function starts returning each element from given iterable and saves its copy. Once elements are exhausted, elements in saved copy are returned thereby forming infinite loop." }, { "code": null, "e": 2442, "s": 2371, "text": ">>> from itertools import cycle\n>>> for x in cycle(\"hello\"):\nprint (x)" }, { "code": null, "e": 2538, "s": 2442, "text": "Characters in the string will be repetitively printed till keyboard interrupt Ctrl-C is issued." }, { "code": null, "e": 2683, "s": 2538, "text": "repeat() − This function returns the object argument repeatedly. If second argument ‘times’ is provided, repetition takes place that many times." }, { "code": null, "e": 2794, "s": 2683, "text": ">>> from itertools import repeat\n>>> for x in repeat(1):\nprint (x)\n>>> for x in repeat('hello', 10):\nprint (x)" }, { "code": null, "e": 2865, "s": 2794, "text": "First loop will print 1 endlessly. Second one prints 'hello' 10 times." }, { "code": null, "e": 2964, "s": 2865, "text": "Functions in following category return finite iterators that terminate on shortest input sequence." }, { "code": null, "e": 3240, "s": 2964, "text": "accumulate() − This function has two parameters. First is an iterable (list, tuple or string). Second parameter by default is operator.add() (function in operator module implementing standard addition operator), but may be any other function receiving two numeric parameters." }, { "code": null, "e": 3267, "s": 3240, "text": "accumulate(sequence, func)" }, { "code": null, "e": 3632, "s": 3267, "text": "First two elements of input sequence are processed by func. Result of the process is first parameter for next iteration and second parameter to func is third element in input sequence. This process is repeated till the sequence is exhausted. The accumulate function returns an iterator in which each element is accumulated result of processing successive elements." }, { "code": null, "e": 3752, "s": 3632, "text": "In following example, numbers in the list are cumulatively added. Note that default function argument is add operation." }, { "code": null, "e": 3841, "s": 3752, "text": ">>> from itertools import accumulate\n>>> list(accumulate([1,2,3,4,5]))\n[1, 3, 6, 10, 15]" }, { "code": null, "e": 3922, "s": 3841, "text": "We can have a user defined function as second parameter to accumulate() function" }, { "code": null, "e": 4019, "s": 3922, "text": ">>> def multiply(x,y):\nreturn x*y\n>>> list(accumulate([1,2,3,4,5], multiply))\n[1, 2, 6, 24, 120]" }, { "code": null, "e": 4220, "s": 4019, "text": "This behaviour is somewhat similar to built-in reduce() function. The reduce() function returns only the final result of accumulation, whereas accumulate() builds iterator of all intermediate results." }, { "code": null, "e": 4418, "s": 4220, "text": "chain() − This function can have more than one iterables as parameter. It yields each element of first iterable into resultant iterator and proceeds to next until iterable parameters are exhausted." }, { "code": null, "e": 4538, "s": 4418, "text": ">>> from itertools import chain\n>>> list(chain([10,20],'hello',range(4)))\n[10, 20, 'h', 'e', 'l', 'l', 'o', 0, 1, 2, 3]" }, { "code": null, "e": 4764, "s": 4538, "text": "dropwhile() − This function returns an iterator by dropping elements from terable as long as predicate function argument returns true. The moment the function returns false, all remaining elements are yielded to the iterator." }, { "code": null, "e": 4922, "s": 4764, "text": ">>> from itertools import dropwhile\n>>> def iseven(x):\nif x % 2 == 0:\nreturn True\nelse:\nreturn False\n>>> list(dropwhile(iseven, [12,90,61,4,15]))\n[61, 4, 15]" }, { "code": null, "e": 5045, "s": 4922, "text": "filterfalse() − This function returns an iterator by filtering out elements for whom the predicate function results False." }, { "code": null, "e": 5204, "s": 5045, "text": ">>> from itertools import filterfalse\n>>> def iseven(x):\nif x % 2 == 0:\nreturn True\nelse:\nreturn False\n>>> list(filterfalse(iseven, [12,90,61,4,15]))\n[61, 15]" }, { "code": null, "e": 5641, "s": 5204, "text": "islice() − This function build an iterator by selecting certain elements from iterable. The selection criteria depends on start, stop and step parameters. Selection starts from start value and continues till stop value. If stop is None, it goes upto end of iterable, otherwise selection stops at specified index. Step parameter is 1 by default. Selection of elements increments by step parameter. None of the parameters can be negative." }, { "code": null, "e": 5862, "s": 5641, "text": ">>> from itertools import islice\n>>> list(islice(range(10),1,5,2))\n[1, 3]\n>>> list(islice(range(10),0,None,3))\n[0, 3, 6, 9]\n>>> list(islice(range(10),5,None))\n[5, 6, 7, 8, 9]\n>>> list(islice(range(10),5))\n[0, 1, 2, 3, 4]" }, { "code": null, "e": 5936, "s": 5862, "text": "Following function generate Combinatoric iterators from iterable objects." }, { "code": null, "e": 6141, "s": 5936, "text": "product() − This function generates an iterator which is a Cartesian product of elements in input sequences. This is equivalent of constructing nested for loops, one for traversing each iterable sequence." }, { "code": null, "e": 6268, "s": 6141, "text": "In following example list comprehension technique is used to run two nested loops on two sequences to build Cartesian product." }, { "code": null, "e": 6411, "s": 6268, "text": ">>> [[x,y] for x in [1,2,3] for y in ['a','b','c']]\n[[1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, 'b'], [2, 'c'], [3, 'a'], [3, 'b'], [3, 'c']]" }, { "code": null, "e": 6458, "s": 6411, "text": "The product() function produces similar result" }, { "code": null, "e": 6624, "s": 6458, "text": ">>> from itertools import product\n>>> list(product([1,2,3],['a','b','c']))\n[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]" }, { "code": null, "e": 6834, "s": 6624, "text": "permutations() − This function yields all possible permutations of elements in input iterable. Length of each permutation may be specified as second parameter to this function. If not specified, length is one." }, { "code": null, "e": 6920, "s": 6834, "text": ">>> list(permutations(range(1,4),2))\n[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]" }, { "code": null, "e": 7130, "s": 6920, "text": "combinations() − This function yields all possible combinations of elements in input iterable. Length of each permutation may be specified as second parameter to this function. If not specified, length is one." }, { "code": null, "e": 7231, "s": 7130, "text": ">>> from itertools import combinations\n>>> list(combinations(range(1,4),2))\n[(1, 2), (1, 3), (2, 3)]" }, { "code": null, "e": 7325, "s": 7231, "text": "This article introduces various iterator tools defined in itertools module of Python library." } ]
Elm - Package Manager
A package manager is a command-line tool that automates the process of installing, upgrading, configuring, and removing packages in your application. Just like JavaScript has a package manager called npm, elm has a package manager called elm-package. The package manager performs the following three tasks − Installs all dependencies that an elm application need Publishes custom packages Determines the version of your package when you are ready to publish and update. The following table lists down the various Elm package manager commands − In order to publish your package, you need to host source code on GitHub and have the version properly labeled with a git tag. Following illustration shows how to use elm-package manager to pull an external dependency. In this example, we will see how to integrate Scalable Vector Graphics(SVG) into an elm application. Step 1 − Create a folder elmSvgApp Step 2 − Install svg package using the following command − elm-package install elm-lang/svg Step 3 − Install Create a SvgDemo.elm file and type the content given below. We import Svg module to draw a rectangle of 100x100 dimension and fill the colour red. import Svg exposing (..) import Svg.Attributes exposing (..) main = svg [ width "120" , height "120" , viewBox "0 0 120 120" ] [ rect [ x "10" , y "10" , width "100" , height "100" , rx "15" , ry "15" ,fill "red" ] [] ] Step 4 − Now build the project using elm make .\SvgDemo.elm. This will generate an index.html as shown below − 27 Lectures 2.5 hours Ahmed Elfakharany Print Add Notes Bookmark this page
[ { "code": null, "e": 2030, "s": 1880, "text": "A package manager is a command-line tool that automates the process of installing, upgrading, configuring, and removing packages in your application." }, { "code": null, "e": 2131, "s": 2030, "text": "Just like JavaScript has a package manager called npm, elm has a package manager called elm-package." }, { "code": null, "e": 2188, "s": 2131, "text": "The package manager performs the following three tasks −" }, { "code": null, "e": 2243, "s": 2188, "text": "Installs all dependencies that an elm application need" }, { "code": null, "e": 2269, "s": 2243, "text": "Publishes custom packages" }, { "code": null, "e": 2350, "s": 2269, "text": "Determines the version of your package when you are ready to publish and update." }, { "code": null, "e": 2424, "s": 2350, "text": "The following table lists down the various Elm package manager commands −" }, { "code": null, "e": 2643, "s": 2424, "text": "In order to publish your package, you need to host source code on GitHub and have the version properly labeled with a git tag. Following illustration shows how to use elm-package manager to pull an external dependency." }, { "code": null, "e": 2744, "s": 2643, "text": "In this example, we will see how to integrate Scalable Vector Graphics(SVG) into an elm application." }, { "code": null, "e": 2779, "s": 2744, "text": "Step 1 − Create a folder elmSvgApp" }, { "code": null, "e": 2838, "s": 2779, "text": "Step 2 − Install svg package using the following command −" }, { "code": null, "e": 2872, "s": 2838, "text": "elm-package install elm-lang/svg\n" }, { "code": null, "e": 3036, "s": 2872, "text": "Step 3 − Install Create a SvgDemo.elm file and type the content given below. We import Svg module to draw a rectangle of 100x100 dimension and fill the colour red." }, { "code": null, "e": 3332, "s": 3036, "text": "import Svg exposing (..)\nimport Svg.Attributes exposing (..)\n\nmain =\n svg\n [ width \"120\"\n , height \"120\"\n , viewBox \"0 0 120 120\"\n ]\n [ rect\n [ x \"10\"\n , y \"10\"\n , width \"100\"\n , height \"100\"\n , rx \"15\"\n , ry \"15\"\n ,fill \"red\"\n ]\n []\n ]" }, { "code": null, "e": 3443, "s": 3332, "text": "Step 4 − Now build the project using elm make .\\SvgDemo.elm. This will generate an index.html as shown below −" }, { "code": null, "e": 3478, "s": 3443, "text": "\n 27 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3497, "s": 3478, "text": " Ahmed Elfakharany" }, { "code": null, "e": 3504, "s": 3497, "text": " Print" }, { "code": null, "e": 3515, "s": 3504, "text": " Add Notes" } ]
Dynamic UI in Shiny (incl. demo app) | by Thomas Filaire | Towards Data Science
Shiny has become an extremely popular solution to build interactive web apps straight from R. So popular that most data & analytics teams in companies have adopted this framework as part of their toolkit. However, R Shiny is often said to be a good framework for fast prototyping, but not robust enough for industrialized, scalable solutions running into production. With this series, I share some advanced tips with the ambition to overcome these objections and to help you build robust/ sustainable/ scalable applications, ready for business usage in production! Production being defined as follows: Software environments that are used and relied on by real users, with real consequences if things go wrong — Joe Cheng, CTO@RStudio Note: in order to get the most from this tutorial, interested reader should already be familiar with basic Shiny principles (e.g. reactivity), R programing (e.g. function definition, tidyverse, purrr::map()), web development (e.g. html tags and css), and RStudio projects. In this tutorial, I will focus on describing a reproducible way to dynamically generate UI components based on user inputs. This feature is very useful in countless situations, as users of your applications are likely to display an a-priori unknown number of information on their dashboard. To list just a few situations: Add/ remove stocks from a user portfolio management application Consider/ ignore specific events in a time series forecasting application Include/ exclude stores in a retailer performance analysis application ... In addition, I’ll also describe how to define observers to trigger actions from dynamically generated buttons which is not a trivial task (as it requires a bit of JavaScript). This tutorial comes with a R Shiny demo application which you can access here. In this particular educational example, you (the user) can select as many Stranger Things characters as desired, and display basic information for each of them, through what I’ll call an infocard. Each character’s infocard offers additional capabilities: Access to the detailed Wikipedia page of the actor (clicking on the ‘More’ button) Possibility to remove the infocard (clicking on the ‘Remove’ button) My advice: in order to get the most out of this tutorial, I recommend to try rebuilding the application by combining the various pieces of code provided throughout the article. Main blocks are numbered in a logical way so that you do not get lost along the way. If necessary, the entire code is also available on my bitbucket account here. Please have a look to see where to store images in the project structure. My approach to guide you through the code is the following: Set the scene: description of required R packages, underlying dataset, and application backboneDefine user inputs: description of HTML widgets used in the application to capture user inputsDefine infocard function: a function to generate HTML code which will be very useful to generate infocards ‘on the fly’, in combination with the purrr::map() functionServer side definition: creation of reactive values and observers to make the application ‘shine’ Set the scene: description of required R packages, underlying dataset, and application backbone Define user inputs: description of HTML widgets used in the application to capture user inputs Define infocard function: a function to generate HTML code which will be very useful to generate infocards ‘on the fly’, in combination with the purrr::map() function Server side definition: creation of reactive values and observers to make the application ‘shine’ To build the R Shiny companion app for this tutorial: I used the 4 following packages: shiny, shinythemes, shinyWidgets, and tidyverse # PART 1 - SETTING THE SCENE# section 1.0 - load required packageslibrary(shiny) # web app framework for Rlibrary(shinythemes) # themes for shinylibrary(shinyWidgets) # custom input widgets for shinylibrary(tidyverse) # collection of R packages for data science I built a small dataset with basic information relative to main Stranger Things’ characters (source: Wikipedia): # section 1.1 - build datasetcrm_tbl <- tibble( character = c("Joyce Byers", "Jim Hopper", "Mike Wheeler", "Jane Hopper", "Dustin Henderson", "Lucas Sinclair", "Nancy Wheeler", "Jonathan Byers", "Karen Wheeler", "Will Byers", "Max Mayfield", "Steve Harrington"), actor = c("Winona Ryder", "David Harbour", "Finn Wolfhard", "Millie Bobby Brown", "Gaten Matarazzo", "Caleb McLaughlin", "Natalia Dyer", "Charlie Heaton", "Cara Buono", "Noah Schnapp", "Sadie Sink", "Joe Keery"), image = c("img/winona_ryder.jpg", "img/david_harbour.jpg", "img/finn_wolfhard.jpg", "img/millie_bobby_brown.jpg", "img/gaten_matarazzo.jpg", "img/caleb_mclaughlin.jpg", "img/natalia_dyer.jpg", "img/charlie_heaton.jpg", "img/cara_buono.jpg", "img/noah_schnapp.jpg", "img/sadie_sink.jpg", "img/joe_keery.jpg"), wiki = c("https://en.wikipedia.org/wiki/Winona_Ryder", "https://en.wikipedia.org/wiki/David_Harbour", "https://en.wikipedia.org/wiki/Finn_Wolfhard", "https://en.wikipedia.org/wiki/Millie_Bobby_Brown", "https://en.wikipedia.org/wiki/Gaten_Matarazzo", "https://en.wikipedia.org/wiki/Caleb_McLaughlin", "https://en.wikipedia.org/wiki/Natalia_Dyer", "https://en.wikipedia.org/wiki/Charlie_Heaton", "https://en.wikipedia.org/wiki/Cara_Buono", "https://en.wikipedia.org/wiki/Noah_Schnapp", "https://en.wikipedia.org/wiki/Sadie_Sink", "https://en.wikipedia.org/wiki/Joe_Keery")) I chose to initialise the application with 2 active characters, meaning that 2 infocards will be displayed when the app starts: # section 1.2 - set initial selection current_user_selection <- c("Jim Hopper", "Joyce Byers") Lastly I built a basic backbone for the application, made of: a navbarPage (blank bootstrap 3 page with top level navigation bar) a left sidebar (I used shiny::wellPanel() function) an infocard area # PART 2 - UI PART# app backboneui <- navbarPage( title = "R Shiny advanced tips series", collapsible = TRUE, windowTitle = "R Shiny tips", tabPanel( title = "Demo", # section 2.1 - header # section 2.2 - sidebar panel div( class = "container", column( width = 3, wellPanel( p("PLACEHOLDER - USER INPUTS") ) ), column( width = 9, div( # render thumbnails dynamically (ui) p("PLACEHOLDER - INFOCARDS") ) ) ) ))# PART 3 - SERVER PARTserver <- function(input, output, session) { }# PART 4 - RUN APPLICATIONshinyApp(ui = ui, server = server) The header (backbone’s section 2.1) is a simple container where I display basic information about the application. I took advantage of existing bootstrap classes to make the text eye-catching (see page-header and lead classes) # >> insert in section 2.1div( class = "container", h1(class = "page-header", "Generate dynamic UI components", tags$small("- Thomas Filaire")), p(class = "lead", "Learn how to generate UI components dynamically based on user inputs"), p("Note: this application is the companion of my Medium post; read it to understand its underlying principles!")) 2 — DEFINE USER INPUTS To illustrate the dynamic UI functionality, I built a very simple selector for the user to choose her/his favorite Stranger Things character. Once selected, just click on the ‘Add’ button to show the corresponding infocard. While the basic selectInput() from shiny package is great and I use it most of the time, I made the choice to opt for the shinyWidget::pickerInput() alternative, which presents many benefits, in particular live search capabilities. Test it and I’m sure you’ll adopt it! # >> insert inside wellPaneldiv( shinyWidgets::pickerInput( inputId = "pi_character_selector", label = "Select character(s)", choices = crm_tbl %>% pull(character), multiple = FALSE, selected = "Mike Wheeler", options = pickerOptions( actionsBox = FALSE, liveSearch = TRUE, size = 10 ) )),div( actionButton( class = "btn-primary", inputId = "ab_show_character", label = "Add" ) )) I built a function to generate infocard (thus an HTML piece of code), which I will call later on from the server side in a purrr::map() function to apply it to a list of Stranger Things characters. As an R Shiny programers you should embrace functional programing as it forces you to create functions that can easily be analyzed in isolation, and avoid unnecessary duplication of code, improving readability. The function takes a character’s name as an input, and return the infocard (HTML object). 3 key important things to notice: note how rendering HTML piece of code is as easy as generating numbers, list, chart, etc., which we usually do with functions.note the usage of bootstrap 3's pre-existing classes (img-rounded, caption, btn-default), plus the rm_btn class assigned to the ‘remove button’ on which I will further elaborate in part 4 of this tutorial.note the usage of the immensely helpful stringr::str_glue() function which I used to assign unique ids to each button. This is a key part as ids must be unique and are required to trigger actions when respective buttons are clicked. note how rendering HTML piece of code is as easy as generating numbers, list, chart, etc., which we usually do with functions. note the usage of bootstrap 3's pre-existing classes (img-rounded, caption, btn-default), plus the rm_btn class assigned to the ‘remove button’ on which I will further elaborate in part 4 of this tutorial. note the usage of the immensely helpful stringr::str_glue() function which I used to assign unique ids to each button. This is a key part as ids must be unique and are required to trigger actions when respective buttons are clicked. str_glue() makes is easy to insert the value of a variable within a character string. In order to make each button’s id unique I adopted the following pattern: for ‘more’ buttons: ab_more_character_name (ab stands for actionbutton). for ‘remove’ buttons: ab_remove_character_name. E.g. ab_more_joyce_byers, ab_remove_joyce_byers, etc. I also used functions from the stringr package to lowercase/uppercase selected character’s name and to add/remove “_” so as to make string a valid id. # >> insert infocard definition as section 1.3 in PART 1 - SETTING THE SCENE of your app.R file# section 1.3 - define custom infocardmy_infocard <- function(selected_character) { # selected_character == value from user pickerInput # e.g. "Mike Wheeler" selected_image <- crm_tbl %>% filter(character == selected_character) %>% pull(image) # get image url from dataset selected_actor <- crm_tbl %>% filter(character == selected_character) %>% pull(actor) # get actor's name from dataset selected_wiki <- crm_tbl %>% filter(character == selected_character) %>% pull(wiki) # get wikipedia's link from dataset # piece of UI to render dynamically column( width = 4, div( class = "thumbnail text-center", # picture img( class = "img-rounded", style = "height: 300px;", src = selected_image ), # main information div( class = "caption", h4(selected_character), p(selected_actor) ), # link to wikipedia's page actionButton( class = "btn-default", inputId = str_glue("ab_more_{selected_character %>% tolower() %>% str_replace_all(' ', '_')}"), label = "More", onclick = str_glue("window.open('{selected_wiki}', '_blank')") ), # remove button actionButton( class = "btn-default rm_btn", inputId = str_glue("ab_remove_{selected_character %>% tolower() %>% str_replace_all(' ', '_')}"), label = "Remove" ) ) )} Once we have defined the backbone of the application, and built the function to generate the custom-made infocards, let’s jump on the server side. First, I used an eventReactive() function to capture any new character which the user selects through the pickerInput widget. eventReactive() allows the reactive components to update only when the user confirms her/his choice by clicking on the ‘Add’ button (which id is input$ab_show_character). # >> insert in server part # get user's selected character when 'Add' button is clickedcurrent_character <- eventReactive( eventExpr = input$ab_show_character, { input$pi_character_selector }) Whenever a new character is selected by the user, information must be captured and added to previous list of selected characters. I used a reactiveValues() to store selected characters, initialized with current_user_selection defined as per part 1. An observeEvent updates reactive_values whenever the ‘Add’ button is clicked. I inserted a unique() in the pipeline to make sure infocards are note created multiple times, and thus are displayed only once. # >> insert in server part# store user's selectionreactive_values <- reactiveValues()reactive_values$character_list <- current_user_selection# add character when relevantobserveEvent(input$ab_show_character, { reactive_values$character_list <- c(reactive_values$character_list, current_character()) %>% unique()}) Based on reactive_values$character_list (the list of user’s chosen characters), I generate as many infocards as necessary inside a renderUI block, which is then ‘rendered’ in the UI via a corresponding uiOutput: # >> insert in the main area of ui sectionuiOutput(outputId = "infocards") To build the UI part, I passed the list of characters within the purrr::map() function so as to call the custom my_infocard() function as many times as required. As purrr::map() returns a list, I pipe the result with the tagList() function to bind outputs together and generate a unique (and potentially big) HTML section. See in the screenshot below a visual explanation of how tagList() works: At this stage of development, the application should be working almost as desired. The final touch The last functionality to add is the ability to remove an infocard by clicking on the ‘Remove’ button. I used a bit of JavaScript here. I will not cover JavaScript in details (I’m far from being a expert in this domain), but simply notice here that: JavaScript is inserted in the HTML code of the R Shiny application via tags (head and script) The code is simply storing button id (rm_btn_id) whenever a button with the rm_btn class is clicked # >> insert in the tabPanel, below title# JS function to identify button id when clickedtags$head( tags$script( HTML("$(document).on('click', '.rm_btn', function () { Shiny.onInputChange('rm_btn_id', this.id); });" ) )), As ‘Remove’ buttons have the rm_btn class (see definition in section 1.3), Shiny will get access to their respective id whenever they are clicked. Finally, I take advantage of this in order to remove the corresponding character from the characters’ list, through an observeEvent(). # >> insert in server part# remove infocardobserveEvent(input$rm_btn_id, { reactive_values$character_list <- reactive_values$character_list %>% .[reactive_values$character_list %>% toupper() != input$rm_btn_id %>% str_remove("ab_remove_") %>% toupper() %>% str_replace("_", " ")]}) And we’re done! Congratulations if you’ve been able to made it so far!. shinythemes is a great package to super-easily make your application look professional the sequence : list of user inputs + map( “function that generates HTML code”) + tagList() is extremely powerful and — in my opinion — readable. create function to generate pieces of HTML to avoid duplication of code and easily use the above sequence I hope you found this article useful and that it will help you build better applications. You can find the entire code on my bitbucket repo here. Please do not hesitate to send any feedback or questions! SOURCES R Shiny cheatsheet Communicating with Shiny via JavaScript Business Science 202A — Build scalable applications using R
[ { "code": null, "e": 252, "s": 47, "text": "Shiny has become an extremely popular solution to build interactive web apps straight from R. So popular that most data & analytics teams in companies have adopted this framework as part of their toolkit." }, { "code": null, "e": 414, "s": 252, "text": "However, R Shiny is often said to be a good framework for fast prototyping, but not robust enough for industrialized, scalable solutions running into production." }, { "code": null, "e": 612, "s": 414, "text": "With this series, I share some advanced tips with the ambition to overcome these objections and to help you build robust/ sustainable/ scalable applications, ready for business usage in production!" }, { "code": null, "e": 649, "s": 612, "text": "Production being defined as follows:" }, { "code": null, "e": 781, "s": 649, "text": "Software environments that are used and relied on by real users, with real consequences if things go wrong — Joe Cheng, CTO@RStudio" }, { "code": null, "e": 1054, "s": 781, "text": "Note: in order to get the most from this tutorial, interested reader should already be familiar with basic Shiny principles (e.g. reactivity), R programing (e.g. function definition, tidyverse, purrr::map()), web development (e.g. html tags and css), and RStudio projects." }, { "code": null, "e": 1178, "s": 1054, "text": "In this tutorial, I will focus on describing a reproducible way to dynamically generate UI components based on user inputs." }, { "code": null, "e": 1376, "s": 1178, "text": "This feature is very useful in countless situations, as users of your applications are likely to display an a-priori unknown number of information on their dashboard. To list just a few situations:" }, { "code": null, "e": 1440, "s": 1376, "text": "Add/ remove stocks from a user portfolio management application" }, { "code": null, "e": 1514, "s": 1440, "text": "Consider/ ignore specific events in a time series forecasting application" }, { "code": null, "e": 1585, "s": 1514, "text": "Include/ exclude stores in a retailer performance analysis application" }, { "code": null, "e": 1589, "s": 1585, "text": "..." }, { "code": null, "e": 1765, "s": 1589, "text": "In addition, I’ll also describe how to define observers to trigger actions from dynamically generated buttons which is not a trivial task (as it requires a bit of JavaScript)." }, { "code": null, "e": 1844, "s": 1765, "text": "This tutorial comes with a R Shiny demo application which you can access here." }, { "code": null, "e": 2041, "s": 1844, "text": "In this particular educational example, you (the user) can select as many Stranger Things characters as desired, and display basic information for each of them, through what I’ll call an infocard." }, { "code": null, "e": 2099, "s": 2041, "text": "Each character’s infocard offers additional capabilities:" }, { "code": null, "e": 2182, "s": 2099, "text": "Access to the detailed Wikipedia page of the actor (clicking on the ‘More’ button)" }, { "code": null, "e": 2251, "s": 2182, "text": "Possibility to remove the infocard (clicking on the ‘Remove’ button)" }, { "code": null, "e": 2665, "s": 2251, "text": "My advice: in order to get the most out of this tutorial, I recommend to try rebuilding the application by combining the various pieces of code provided throughout the article. Main blocks are numbered in a logical way so that you do not get lost along the way. If necessary, the entire code is also available on my bitbucket account here. Please have a look to see where to store images in the project structure." }, { "code": null, "e": 2725, "s": 2665, "text": "My approach to guide you through the code is the following:" }, { "code": null, "e": 3178, "s": 2725, "text": "Set the scene: description of required R packages, underlying dataset, and application backboneDefine user inputs: description of HTML widgets used in the application to capture user inputsDefine infocard function: a function to generate HTML code which will be very useful to generate infocards ‘on the fly’, in combination with the purrr::map() functionServer side definition: creation of reactive values and observers to make the application ‘shine’" }, { "code": null, "e": 3274, "s": 3178, "text": "Set the scene: description of required R packages, underlying dataset, and application backbone" }, { "code": null, "e": 3369, "s": 3274, "text": "Define user inputs: description of HTML widgets used in the application to capture user inputs" }, { "code": null, "e": 3536, "s": 3369, "text": "Define infocard function: a function to generate HTML code which will be very useful to generate infocards ‘on the fly’, in combination with the purrr::map() function" }, { "code": null, "e": 3634, "s": 3536, "text": "Server side definition: creation of reactive values and observers to make the application ‘shine’" }, { "code": null, "e": 3688, "s": 3634, "text": "To build the R Shiny companion app for this tutorial:" }, { "code": null, "e": 3769, "s": 3688, "text": "I used the 4 following packages: shiny, shinythemes, shinyWidgets, and tidyverse" }, { "code": null, "e": 4050, "s": 3769, "text": "# PART 1 - SETTING THE SCENE# section 1.0 - load required packageslibrary(shiny) # web app framework for Rlibrary(shinythemes) # themes for shinylibrary(shinyWidgets) # custom input widgets for shinylibrary(tidyverse) # collection of R packages for data science" }, { "code": null, "e": 4163, "s": 4050, "text": "I built a small dataset with basic information relative to main Stranger Things’ characters (source: Wikipedia):" }, { "code": null, "e": 5882, "s": 4163, "text": "# section 1.1 - build datasetcrm_tbl <- tibble( character = c(\"Joyce Byers\", \"Jim Hopper\", \"Mike Wheeler\", \"Jane Hopper\", \"Dustin Henderson\", \"Lucas Sinclair\", \"Nancy Wheeler\", \"Jonathan Byers\", \"Karen Wheeler\", \"Will Byers\", \"Max Mayfield\", \"Steve Harrington\"), actor = c(\"Winona Ryder\", \"David Harbour\", \"Finn Wolfhard\", \"Millie Bobby Brown\", \"Gaten Matarazzo\", \"Caleb McLaughlin\", \"Natalia Dyer\", \"Charlie Heaton\", \"Cara Buono\", \"Noah Schnapp\", \"Sadie Sink\", \"Joe Keery\"), image = c(\"img/winona_ryder.jpg\", \"img/david_harbour.jpg\", \"img/finn_wolfhard.jpg\", \"img/millie_bobby_brown.jpg\", \"img/gaten_matarazzo.jpg\", \"img/caleb_mclaughlin.jpg\", \"img/natalia_dyer.jpg\", \"img/charlie_heaton.jpg\", \"img/cara_buono.jpg\", \"img/noah_schnapp.jpg\", \"img/sadie_sink.jpg\", \"img/joe_keery.jpg\"), wiki = c(\"https://en.wikipedia.org/wiki/Winona_Ryder\", \"https://en.wikipedia.org/wiki/David_Harbour\", \"https://en.wikipedia.org/wiki/Finn_Wolfhard\", \"https://en.wikipedia.org/wiki/Millie_Bobby_Brown\", \"https://en.wikipedia.org/wiki/Gaten_Matarazzo\", \"https://en.wikipedia.org/wiki/Caleb_McLaughlin\", \"https://en.wikipedia.org/wiki/Natalia_Dyer\", \"https://en.wikipedia.org/wiki/Charlie_Heaton\", \"https://en.wikipedia.org/wiki/Cara_Buono\", \"https://en.wikipedia.org/wiki/Noah_Schnapp\", \"https://en.wikipedia.org/wiki/Sadie_Sink\", \"https://en.wikipedia.org/wiki/Joe_Keery\"))" }, { "code": null, "e": 6010, "s": 5882, "text": "I chose to initialise the application with 2 active characters, meaning that 2 infocards will be displayed when the app starts:" }, { "code": null, "e": 6105, "s": 6010, "text": "# section 1.2 - set initial selection current_user_selection <- c(\"Jim Hopper\", \"Joyce Byers\")" }, { "code": null, "e": 6167, "s": 6105, "text": "Lastly I built a basic backbone for the application, made of:" }, { "code": null, "e": 6235, "s": 6167, "text": "a navbarPage (blank bootstrap 3 page with top level navigation bar)" }, { "code": null, "e": 6287, "s": 6235, "text": "a left sidebar (I used shiny::wellPanel() function)" }, { "code": null, "e": 6304, "s": 6287, "text": "an infocard area" }, { "code": null, "e": 7122, "s": 6304, "text": "# PART 2 - UI PART# app backboneui <- navbarPage( title = \"R Shiny advanced tips series\", collapsible = TRUE, windowTitle = \"R Shiny tips\", tabPanel( title = \"Demo\", # section 2.1 - header # section 2.2 - sidebar panel div( class = \"container\", column( width = 3, wellPanel( p(\"PLACEHOLDER - USER INPUTS\") ) ), column( width = 9, div( # render thumbnails dynamically (ui) p(\"PLACEHOLDER - INFOCARDS\") ) ) ) ))# PART 3 - SERVER PARTserver <- function(input, output, session) { }# PART 4 - RUN APPLICATIONshinyApp(ui = ui, server = server)" }, { "code": null, "e": 7349, "s": 7122, "text": "The header (backbone’s section 2.1) is a simple container where I display basic information about the application. I took advantage of existing bootstrap classes to make the text eye-catching (see page-header and lead classes)" }, { "code": null, "e": 7759, "s": 7349, "text": "# >> insert in section 2.1div( class = \"container\", h1(class = \"page-header\", \"Generate dynamic UI components\", tags$small(\"- Thomas Filaire\")), p(class = \"lead\", \"Learn how to generate UI components dynamically based on user inputs\"), p(\"Note: this application is the companion of my Medium post; read it to understand its underlying principles!\"))" }, { "code": null, "e": 7782, "s": 7759, "text": "2 — DEFINE USER INPUTS" }, { "code": null, "e": 8006, "s": 7782, "text": "To illustrate the dynamic UI functionality, I built a very simple selector for the user to choose her/his favorite Stranger Things character. Once selected, just click on the ‘Add’ button to show the corresponding infocard." }, { "code": null, "e": 8276, "s": 8006, "text": "While the basic selectInput() from shiny package is great and I use it most of the time, I made the choice to opt for the shinyWidget::pickerInput() alternative, which presents many benefits, in particular live search capabilities. Test it and I’m sure you’ll adopt it!" }, { "code": null, "e": 8863, "s": 8276, "text": "# >> insert inside wellPaneldiv( shinyWidgets::pickerInput( inputId = \"pi_character_selector\", label = \"Select character(s)\", choices = crm_tbl %>% pull(character), multiple = FALSE, selected = \"Mike Wheeler\", options = pickerOptions( actionsBox = FALSE, liveSearch = TRUE, size = 10 ) )),div( actionButton( class = \"btn-primary\", inputId = \"ab_show_character\", label = \"Add\" ) ))" }, { "code": null, "e": 9061, "s": 8863, "text": "I built a function to generate infocard (thus an HTML piece of code), which I will call later on from the server side in a purrr::map() function to apply it to a list of Stranger Things characters." }, { "code": null, "e": 9272, "s": 9061, "text": "As an R Shiny programers you should embrace functional programing as it forces you to create functions that can easily be analyzed in isolation, and avoid unnecessary duplication of code, improving readability." }, { "code": null, "e": 9396, "s": 9272, "text": "The function takes a character’s name as an input, and return the infocard (HTML object). 3 key important things to notice:" }, { "code": null, "e": 9960, "s": 9396, "text": "note how rendering HTML piece of code is as easy as generating numbers, list, chart, etc., which we usually do with functions.note the usage of bootstrap 3's pre-existing classes (img-rounded, caption, btn-default), plus the rm_btn class assigned to the ‘remove button’ on which I will further elaborate in part 4 of this tutorial.note the usage of the immensely helpful stringr::str_glue() function which I used to assign unique ids to each button. This is a key part as ids must be unique and are required to trigger actions when respective buttons are clicked." }, { "code": null, "e": 10087, "s": 9960, "text": "note how rendering HTML piece of code is as easy as generating numbers, list, chart, etc., which we usually do with functions." }, { "code": null, "e": 10293, "s": 10087, "text": "note the usage of bootstrap 3's pre-existing classes (img-rounded, caption, btn-default), plus the rm_btn class assigned to the ‘remove button’ on which I will further elaborate in part 4 of this tutorial." }, { "code": null, "e": 10526, "s": 10293, "text": "note the usage of the immensely helpful stringr::str_glue() function which I used to assign unique ids to each button. This is a key part as ids must be unique and are required to trigger actions when respective buttons are clicked." }, { "code": null, "e": 10686, "s": 10526, "text": "str_glue() makes is easy to insert the value of a variable within a character string. In order to make each button’s id unique I adopted the following pattern:" }, { "code": null, "e": 10759, "s": 10686, "text": "for ‘more’ buttons: ab_more_character_name (ab stands for actionbutton)." }, { "code": null, "e": 10807, "s": 10759, "text": "for ‘remove’ buttons: ab_remove_character_name." }, { "code": null, "e": 10861, "s": 10807, "text": "E.g. ab_more_joyce_byers, ab_remove_joyce_byers, etc." }, { "code": null, "e": 11012, "s": 10861, "text": "I also used functions from the stringr package to lowercase/uppercase selected character’s name and to add/remove “_” so as to make string a valid id." }, { "code": null, "e": 12906, "s": 11012, "text": "# >> insert infocard definition as section 1.3 in PART 1 - SETTING THE SCENE of your app.R file# section 1.3 - define custom infocardmy_infocard <- function(selected_character) { # selected_character == value from user pickerInput # e.g. \"Mike Wheeler\" selected_image <- crm_tbl %>% filter(character == selected_character) %>% pull(image) # get image url from dataset selected_actor <- crm_tbl %>% filter(character == selected_character) %>% pull(actor) # get actor's name from dataset selected_wiki <- crm_tbl %>% filter(character == selected_character) %>% pull(wiki) # get wikipedia's link from dataset # piece of UI to render dynamically column( width = 4, div( class = \"thumbnail text-center\", # picture img( class = \"img-rounded\", style = \"height: 300px;\", src = selected_image ), # main information div( class = \"caption\", h4(selected_character), p(selected_actor) ), # link to wikipedia's page actionButton( class = \"btn-default\", inputId = str_glue(\"ab_more_{selected_character %>% tolower() %>% str_replace_all(' ', '_')}\"), label = \"More\", onclick = str_glue(\"window.open('{selected_wiki}', '_blank')\") ), # remove button actionButton( class = \"btn-default rm_btn\", inputId = str_glue(\"ab_remove_{selected_character %>% tolower() %>% str_replace_all(' ', '_')}\"), label = \"Remove\" ) ) )}" }, { "code": null, "e": 13053, "s": 12906, "text": "Once we have defined the backbone of the application, and built the function to generate the custom-made infocards, let’s jump on the server side." }, { "code": null, "e": 13350, "s": 13053, "text": "First, I used an eventReactive() function to capture any new character which the user selects through the pickerInput widget. eventReactive() allows the reactive components to update only when the user confirms her/his choice by clicking on the ‘Add’ button (which id is input$ab_show_character)." }, { "code": null, "e": 13568, "s": 13350, "text": "# >> insert in server part # get user's selected character when 'Add' button is clickedcurrent_character <- eventReactive( eventExpr = input$ab_show_character, { input$pi_character_selector })" }, { "code": null, "e": 13817, "s": 13568, "text": "Whenever a new character is selected by the user, information must be captured and added to previous list of selected characters. I used a reactiveValues() to store selected characters, initialized with current_user_selection defined as per part 1." }, { "code": null, "e": 14023, "s": 13817, "text": "An observeEvent updates reactive_values whenever the ‘Add’ button is clicked. I inserted a unique() in the pipeline to make sure infocards are note created multiple times, and thus are displayed only once." }, { "code": null, "e": 14366, "s": 14023, "text": "# >> insert in server part# store user's selectionreactive_values <- reactiveValues()reactive_values$character_list <- current_user_selection# add character when relevantobserveEvent(input$ab_show_character, { reactive_values$character_list <- c(reactive_values$character_list, current_character()) %>% unique()})" }, { "code": null, "e": 14578, "s": 14366, "text": "Based on reactive_values$character_list (the list of user’s chosen characters), I generate as many infocards as necessary inside a renderUI block, which is then ‘rendered’ in the UI via a corresponding uiOutput:" }, { "code": null, "e": 14653, "s": 14578, "text": "# >> insert in the main area of ui sectionuiOutput(outputId = \"infocards\")" }, { "code": null, "e": 14976, "s": 14653, "text": "To build the UI part, I passed the list of characters within the purrr::map() function so as to call the custom my_infocard() function as many times as required. As purrr::map() returns a list, I pipe the result with the tagList() function to bind outputs together and generate a unique (and potentially big) HTML section." }, { "code": null, "e": 15049, "s": 14976, "text": "See in the screenshot below a visual explanation of how tagList() works:" }, { "code": null, "e": 15132, "s": 15049, "text": "At this stage of development, the application should be working almost as desired." }, { "code": null, "e": 15148, "s": 15132, "text": "The final touch" }, { "code": null, "e": 15251, "s": 15148, "text": "The last functionality to add is the ability to remove an infocard by clicking on the ‘Remove’ button." }, { "code": null, "e": 15398, "s": 15251, "text": "I used a bit of JavaScript here. I will not cover JavaScript in details (I’m far from being a expert in this domain), but simply notice here that:" }, { "code": null, "e": 15492, "s": 15398, "text": "JavaScript is inserted in the HTML code of the R Shiny application via tags (head and script)" }, { "code": null, "e": 15592, "s": 15492, "text": "The code is simply storing button id (rm_btn_id) whenever a button with the rm_btn class is clicked" }, { "code": null, "e": 15875, "s": 15592, "text": "# >> insert in the tabPanel, below title# JS function to identify button id when clickedtags$head( tags$script( HTML(\"$(document).on('click', '.rm_btn', function () { Shiny.onInputChange('rm_btn_id', this.id); });\" ) ))," }, { "code": null, "e": 16157, "s": 15875, "text": "As ‘Remove’ buttons have the rm_btn class (see definition in section 1.3), Shiny will get access to their respective id whenever they are clicked. Finally, I take advantage of this in order to remove the corresponding character from the characters’ list, through an observeEvent()." }, { "code": null, "e": 16504, "s": 16157, "text": "# >> insert in server part# remove infocardobserveEvent(input$rm_btn_id, { reactive_values$character_list <- reactive_values$character_list %>% .[reactive_values$character_list %>% toupper() != input$rm_btn_id %>% str_remove(\"ab_remove_\") %>% toupper() %>% str_replace(\"_\", \" \")]})" }, { "code": null, "e": 16576, "s": 16504, "text": "And we’re done! Congratulations if you’ve been able to made it so far!." }, { "code": null, "e": 16663, "s": 16576, "text": "shinythemes is a great package to super-easily make your application look professional" }, { "code": null, "e": 16808, "s": 16663, "text": "the sequence : list of user inputs + map( “function that generates HTML code”) + tagList() is extremely powerful and — in my opinion — readable." }, { "code": null, "e": 16914, "s": 16808, "text": "create function to generate pieces of HTML to avoid duplication of code and easily use the above sequence" }, { "code": null, "e": 17060, "s": 16914, "text": "I hope you found this article useful and that it will help you build better applications. You can find the entire code on my bitbucket repo here." }, { "code": null, "e": 17118, "s": 17060, "text": "Please do not hesitate to send any feedback or questions!" }, { "code": null, "e": 17126, "s": 17118, "text": "SOURCES" }, { "code": null, "e": 17145, "s": 17126, "text": "R Shiny cheatsheet" }, { "code": null, "e": 17185, "s": 17145, "text": "Communicating with Shiny via JavaScript" } ]
C# | Capacity of a List - GeeksforGeeks
01 Feb, 2019 List<T>.Capacity Property is used to gets or sets the total number of elements the internal data structure can hold without resizing. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element. Capacity Vs Count: Count is always less than the Capacity. While adding the elements, if Count exceeds Capacity then the Capacity will increase automatically by reallocating the internal array before copying the old elements and adding the new elements. Capacity is the number of the elements which the List can store before resizing of List needed. But Count is the number of the elements which are actually present in the List. If the Capacity is much larger than the Count the user can decrease capacity by either calling the TrimExcess method or explicitly setting the Capacity to a lower value. If the Capacity is settled explicitly then the internal array is also reallocated to accommodate the specified capacity, and all the elements are copied. Retrieving the value of Capacity property is an O(1) operation while setting the Capacity is an O(n) operation, where n is the new capacity. Syntax: public int Capacity { get; set; } Return Value: This method returns the number of elements that the List<T> can contain before resizing is required of type System.Int32. Exceptions: ArgumentOutOfRangeException : If the capacity is set to a value that is less than Count. OutOfMemoryException : If there is not enough memory available on the system. Below programs illustrate the use of Capacity Property: Example 1: // C# program to illustrate the// Capacity Property of List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers // Here we are not setting // Capacity explicitly List<int> firstlist = new List<int>(); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Printing the Capacity of firstlist Console.WriteLine("Capacity Is: " + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine("Count Is: " + firstlist.Count); // Adding some more // elements in firstlist firstlist.Add(5); firstlist.Add(6); // Printing the Capacity of firstlist // It will give output 8 as internally // List is resized Console.WriteLine("Capacity Is: " + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine("Count Is: " + firstlist.Count); }} Output: Capacity Is: 4 Count Is: 4 Capacity Is: 8 Count Is: 6 Example 2: // C# program to illustrate the// Capacity Property of List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers // Here we are setting Capacity // explicitly i.e. List<int> firstlist = new List<int>(10); // Printing the Capacity of firstlist Console.WriteLine("Capacity Is: " + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine("Count Is: " + firstlist.Count); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Printing the Capacity of firstlist Console.WriteLine("Capacity Is: " + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine("Count Is: " + firstlist.Count); // Adding some more // elements in firstlist firstlist.Add(5); firstlist.Add(6); // Printing the Capacity of firstlist // It will give output 10 as we have // already set the Capacity Console.WriteLine("Capacity Is: " + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine("Count Is: " + firstlist.Count); }} Output: Capacity Is: 10 Count Is: 0 Capacity Is: 10 Count Is: 4 Capacity Is: 10 Count Is: 6 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.capacity?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Generic-List CSharp-Generic-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors Extension Method in C# C# | Class and Object C# | Abstract Classes Common Language Runtime (CLR) in C# Different ways to sort an array in descending order in C#
[ { "code": null, "e": 24090, "s": 24062, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24224, "s": 24090, "text": "List<T>.Capacity Property is used to gets or sets the total number of elements the internal data structure can hold without resizing." }, { "code": null, "e": 24244, "s": 24224, "text": "Properties of List:" }, { "code": null, "e": 24330, "s": 24244, "text": "It is different from the arrays. A list can be resized dynamically but arrays cannot." }, { "code": null, "e": 24433, "s": 24330, "text": "List class can accept null as a valid value for reference types and it also allows duplicate elements." }, { "code": null, "e": 24657, "s": 24433, "text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element." }, { "code": null, "e": 24676, "s": 24657, "text": "Capacity Vs Count:" }, { "code": null, "e": 24911, "s": 24676, "text": "Count is always less than the Capacity. While adding the elements, if Count exceeds Capacity then the Capacity will increase automatically by reallocating the internal array before copying the old elements and adding the new elements." }, { "code": null, "e": 25087, "s": 24911, "text": "Capacity is the number of the elements which the List can store before resizing of List needed. But Count is the number of the elements which are actually present in the List." }, { "code": null, "e": 25257, "s": 25087, "text": "If the Capacity is much larger than the Count the user can decrease capacity by either calling the TrimExcess method or explicitly setting the Capacity to a lower value." }, { "code": null, "e": 25411, "s": 25257, "text": "If the Capacity is settled explicitly then the internal array is also reallocated to accommodate the specified capacity, and all the elements are copied." }, { "code": null, "e": 25552, "s": 25411, "text": "Retrieving the value of Capacity property is an O(1) operation while setting the Capacity is an O(n) operation, where n is the new capacity." }, { "code": null, "e": 25560, "s": 25552, "text": "Syntax:" }, { "code": null, "e": 25595, "s": 25560, "text": "public int Capacity { get; set; }\n" }, { "code": null, "e": 25731, "s": 25595, "text": "Return Value: This method returns the number of elements that the List<T> can contain before resizing is required of type System.Int32." }, { "code": null, "e": 25743, "s": 25731, "text": "Exceptions:" }, { "code": null, "e": 25832, "s": 25743, "text": "ArgumentOutOfRangeException : If the capacity is set to a value that is less than Count." }, { "code": null, "e": 25910, "s": 25832, "text": "OutOfMemoryException : If there is not enough memory available on the system." }, { "code": null, "e": 25966, "s": 25910, "text": "Below programs illustrate the use of Capacity Property:" }, { "code": null, "e": 25977, "s": 25966, "text": "Example 1:" }, { "code": "// C# program to illustrate the// Capacity Property of List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers // Here we are not setting // Capacity explicitly List<int> firstlist = new List<int>(); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Printing the Capacity of firstlist Console.WriteLine(\"Capacity Is: \" + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine(\"Count Is: \" + firstlist.Count); // Adding some more // elements in firstlist firstlist.Add(5); firstlist.Add(6); // Printing the Capacity of firstlist // It will give output 8 as internally // List is resized Console.WriteLine(\"Capacity Is: \" + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine(\"Count Is: \" + firstlist.Count); }}", "e": 27074, "s": 25977, "text": null }, { "code": null, "e": 27082, "s": 27074, "text": "Output:" }, { "code": null, "e": 27137, "s": 27082, "text": "Capacity Is: 4\nCount Is: 4\nCapacity Is: 8\nCount Is: 6\n" }, { "code": null, "e": 27148, "s": 27137, "text": "Example 2:" }, { "code": "// C# program to illustrate the// Capacity Property of List<T>using System;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating a List of integers // Here we are setting Capacity // explicitly i.e. List<int> firstlist = new List<int>(10); // Printing the Capacity of firstlist Console.WriteLine(\"Capacity Is: \" + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine(\"Count Is: \" + firstlist.Count); // adding elements in firstlist firstlist.Add(1); firstlist.Add(2); firstlist.Add(3); firstlist.Add(4); // Printing the Capacity of firstlist Console.WriteLine(\"Capacity Is: \" + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine(\"Count Is: \" + firstlist.Count); // Adding some more // elements in firstlist firstlist.Add(5); firstlist.Add(6); // Printing the Capacity of firstlist // It will give output 10 as we have // already set the Capacity Console.WriteLine(\"Capacity Is: \" + firstlist.Capacity); // Printing the Count of firstlist Console.WriteLine(\"Count Is: \" + firstlist.Count); }}", "e": 28468, "s": 27148, "text": null }, { "code": null, "e": 28476, "s": 28468, "text": "Output:" }, { "code": null, "e": 28561, "s": 28476, "text": "Capacity Is: 10\nCount Is: 0\nCapacity Is: 10\nCount Is: 4\nCapacity Is: 10\nCount Is: 6\n" }, { "code": null, "e": 28572, "s": 28561, "text": "Reference:" }, { "code": null, "e": 28683, "s": 28572, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.capacity?view=netframework-4.7.2" }, { "code": null, "e": 28712, "s": 28683, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 28732, "s": 28712, "text": "CSharp-Generic-List" }, { "code": null, "e": 28757, "s": 28732, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 28760, "s": 28757, "text": "C#" }, { "code": null, "e": 28858, "s": 28760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28867, "s": 28858, "text": "Comments" }, { "code": null, "e": 28880, "s": 28867, "text": "Old Comments" }, { "code": null, "e": 28926, "s": 28880, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28941, "s": 28926, "text": "C# | Delegates" }, { "code": null, "e": 28981, "s": 28941, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29012, "s": 28981, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29030, "s": 29012, "text": "C# | Constructors" }, { "code": null, "e": 29053, "s": 29030, "text": "Extension Method in C#" }, { "code": null, "e": 29075, "s": 29053, "text": "C# | Class and Object" }, { "code": null, "e": 29097, "s": 29075, "text": "C# | Abstract Classes" }, { "code": null, "e": 29133, "s": 29097, "text": "Common Language Runtime (CLR) in C#" } ]
FuelPHP - Complete Working Example
In this chapter, we will learn how to create a complete MVC based BookStore application in FuelPHP. Create a new project named “BookStore” in FuelPHP using the following command. oil create bookstore Create a new layout for our application. Create a file, layout.php at location fuel/app/views/layout.php. The code is as follows, <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8"> <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <title><?php echo $title; ?></title> <!-- Bootstrap core CSS --> <link href = "/assets/css/bootstrap.min.css" rel = "stylesheet"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script src = "/assets/js/bootstrap.min.js"></script> </head> <body> <nav class = "navbar navbar-inverse navbar-fixed-top"> <div class = "container"> <div class = "navbar-header"> <button type = "button" class = "navbar-toggle collapsed" datatoggle = "collapse" data-target = "#navbar" aria-expanded = "false" ariacontrols = "navbar"> <span class= "sr-only">Toggle navigation</span> <span class = "icon-bar"></span> <span class = "icon-bar"></span> <span class = "icon-bar"></span> </button> <a class = "navbar-brand" href = "#">FuelPHP Sample</a> </div> <div id = "navbar" class = "collapse navbar-collapse"> <ul class = "nav navbar-nav"> <li class = "active"><a href = "/book/index">Home</a></li> <li><a href = "/book/add">Add book</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class = "container"> <div class = "starter-template" style = "padding: 50px 0 0 0;"> <?php echo $content; ?> </div> </div><!-- /.container --> </body> </html> Here, we are using bootstrap template. FuelPHP has first class support for bootstrap templates. We have created two variables, title and content. title is used to specify the current page's title and content is used to specify the current page details. Create a new controller, Controller_Book to show, add, edit, and delete the book. Create a new file, fuel/app/classes/controller/book.php and place the following code. <?php class Controller_Book extends Controller_Template { public $template = 'layout'; public function action_index() { // Create the view object $view = View::forge('book/index'); // set the template variables $this->template->title = "Book index page"; $this->template->content = $view; } } Here, we have created the book controller by inheriting template controller and set the default template as fuel/app/views/layout.php. Create a folder, book in views directory under fuel/app/views folder. Then, create a file index.php inside the book folder and add the following code, <h3>index page</h3> As of now, we have created a basic book controller. Update the default route to set the home page of the application to book controller. Open the default routing configuration file, fuel/app/config/routes.php and change it as follows. <?php return array ( '_root_' => 'book/index', // The default route '_404_' => 'welcome/404', // The main 404 route 'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'), ); Now, requesting the URL, http://localhost:8080/ will return the index page of the book controller as follows, Create a new database in MySQL server, using the following command, create database tutorialspoint_bookdb Then, create a table inside the database using the following command, CREATE TABLE book ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(80) NOT NULL, author VARCHAR(80) NOT NULL, price DECIMAL(10, 2) NOT NULL ); Insert some sample record into the table using the following SQL statement. INSERT INTO book(title, author, price) VALUES( 'The C Programming Language', 'Dennie Ritchie', 25.00 ),( 'The C++ Programming Language', 'Bjarne Stroustrup', 80.00 ),( 'C Primer Plus (5th Edition)', 'Stephen Prata', 45.00 ),('Modern PHP', 'Josh Lockhart', 10.00),( 'Learning PHP, MySQL & JavaScript, 4th Edition', 'Robin Nixon', 30.00 ) Configure the database using database configuration file, db.php located at fuel/app/config. <?php return array ( 'development' => array ( 'type' => 'mysqli', 'connection' => array ( 'hostname' => 'localhost', 'port' => '3306', 'database' => 'tutorialspoint_bookdb', 'username' => 'root', 'password' => 'password', 'persistent' => false, 'compress' => false, ), 'identifier' => '`', 'table_prefix' => '', 'charset' => 'utf8', 'enable_cache' => true, 'profiling' => false, 'readonly' => false, ), 'production' => array ( 'type' => 'mysqli', 'connection' => array ( 'hostname' => 'localhost', 'port' => '3306', 'database' => 'tutorialspoint_bookdb', 'username' => 'root', 'password' => 'password', 'persistent' => false, 'compress' => false, ), 'identifier' => '`', 'table_prefix' => '', 'charset' => 'utf8', 'enable_cache' => true, 'profiling' => false, 'readonly' => false, ), ); Update the main configuration file to include ORM package. It is located at “fuel/app/config/”. 'always_load' => array ( 'packages' => array ( 'orm' ), ), Create a book model in book.php located at “fuel/app/classes/model”. It is defined as follows − <?php class Model_Book extends Orm\Model { protected static $_connection = 'production'; protected static $_table_name = 'book'; protected static $_primary_key = array('id'); protected static $_properties = array ( 'id', 'title' => array ( 'data_type' => 'varchar', 'label' => 'Book title', 'validation' => array ( 'required', 'min_length' => array(3), 'max_length' => array(80) ), 'form' => array ( 'type' => 'text' ), ), 'author' => array ( 'data_type' => 'varchar', 'label' => 'Book author', 'validation' => array ( 'required', ), 'form' => array ( 'type' => 'text' ), ), 'price' => array ( 'data_type' => 'decimal', 'label' => 'Book price', 'validation' => array ( 'required', ), 'form' => array ( 'type' => 'text' ), ), ); protected static $_observers = array('Orm\\Observer_Validation' => array ( 'events' => array('before_save') )); } Here, we have specified the database details as properties of the model. It has validation details as well. Update the index action in book controller to list the available books in the database. <?php class Controller_Book extends Controller_Template { public $template = 'layout'; public function action_index() { // Create the view object $view = View::forge('book/index'); // fetch the book from database and set it to the view $books = Model_Book::find('all'); $view->set('books', $books); // set the template variables $this->template->title = "Book index page"; $this->template->content = $view; } } Here, we have used the orm to fetch the book details from the database and then passed the book details to views. Update the view file index.php located at “fuel/app/views/book”. The complete updated code is as follows, <table class = "table"> <thead> <tr> <th>#</th> <th>Title</th> <th>Author</th> <th>Price</th> <th></th> </tr> </thead> <tbody> <?php foreach($books as $book) { ?> <tr> <td><?php echo $book['id']; ?></td> <td><?php echo $book['title']; ?></td> <td><?php echo $book['author']; ?></td> <td><?php echo $book['price']; ?></td> <td> <a href = "/book/edit/<?php echo $book['id']; ?>">Edit</a> <a href = "/book/delete/<?php echo $book['id']; ?>">Delete</a> </td> </tr> <?php } ?> </tbody> </table> <ul> </ul> Now, requesting the URL, http://localhost:8080/ will show the page as follows − Create the functionality to add a new book into the bookstore. Create a new action, action_add in the book controller as follows, public function action_add() { // create a new fieldset and add book model $fieldset = Fieldset::forge('book')->add_model('Model_Book'); // get form from fieldset $form = $fieldset->form(); // add submit button to the form $form->add('Submit', '', array('type' => 'submit', 'value' => 'Submit')); // build the form and set the current page as action $formHtml = $fieldset->build(Uri::create('book/add')); $view = View::forge('book/add'); $view->set('form', $formHtml, false); if (Input::param() != array()) { try { $book = Model_Book::forge(); $book->title = Input::param('title'); $book->author = Input::param('author'); $book->price = Input::param('price'); $book->save(); Response::redirect('book'); } catch (Orm\ValidationFailed $e) { $view->set('errors', $e->getMessage(), false); } } $this->template->title = "Book add page"; $this->template->content = $view; } Here the following two processes are being performed, Building the book form to add book using Fieldset methods and Book model. Building the book form to add book using Fieldset methods and Book model. Processing the book form, when the user enters the book information and submitted back the form. It can be found by checking the Input::param() method for any submitted data. Processing the form involves the following steps − Gather the book information. Validate the book information. We have already set the validation to be called before save method. If the validation fails, it will throw Orm\ValidationFailed exception. Store the book information into the database. Redirect the user to index page on success. Otherwise, show the form again. Processing the book form, when the user enters the book information and submitted back the form. It can be found by checking the Input::param() method for any submitted data. Processing the form involves the following steps − Gather the book information. Gather the book information. Validate the book information. We have already set the validation to be called before save method. If the validation fails, it will throw Orm\ValidationFailed exception. Validate the book information. We have already set the validation to be called before save method. If the validation fails, it will throw Orm\ValidationFailed exception. Store the book information into the database. Store the book information into the database. Redirect the user to index page on success. Otherwise, show the form again. Redirect the user to index page on success. Otherwise, show the form again. We are doing both, showing the form as well as processing the form in the same action. When the user calls the action for the first time, it will show the form. When the user enters the book information and submits the data, then it will process the form. Create the view for add book action. Create a new file, fuel/app/views/book/add.php and enter the following code, <style> #form table { width: 90%; } #form table tr { width: 90% } #form table tr td { width: 50% } #form input[type = text], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } #form input[type = submit] { width: 100%; background-color: #3c3c3c; color: white; padding: 14px 20px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; } #form div { border-radius: 5px; background-color: #f2f2f2; padding: 20px; } </style> <div id = "form"> <h2>Book form</h2> <?php if(isset($errors)) { echo $errors; } echo $form; ?> </div> Here, we are just showing the form created in the action method. In addition, we are showing the errors, if any. Requesting the url, http://localhost:8080/book/add or clicking the Add book navigation link, will show the form as follows, After entering the book information and submitting the page, the book information will be stored into the database and the page gets redirected to index page as follows. Create the functionality to edit and update the existing book information. Create a new action, action_edit in the book controller as follows. public function action_edit($id = false) { if(!($book = Model_Book::find($id))) { throw new HttpNotFoundException(); } // create a new fieldset and add book model $fieldset = Fieldset::forge('book')->add_model('Model_Book'); $fieldset->populate($book); // get form from fieldset $form = $fieldset->form(); // add submit button to the form $form->add('Submit', '', array('type' => 'submit', 'value' => 'Submit')); // build the form and set the current page as action $formHtml = $fieldset->build(Uri::create('book/edit/' . $id)); $view = View::forge('book/add'); $view->set('form', $formHtml, false); if (Input::param() != array()) { try { $book->title = Input::param('title'); $book->author = Input::param('author'); $book->price = Input::param('price'); $book->save(); Response::redirect('book'); } catch (Orm\ValidationFailed $e) { $view->set('errors', $e->getMessage(), false); } } $this->template->title = "Book edit page"; $this->template->content = $view; } It is similar to add action, except it searches the requested book by id before processing the page. If any book information is found in the database, it will proceed and show the book information in the form. Otherwise, it will throw file not found exception and exit. Create the view for edit book action. Here, we are using the same view used for add action. Click the edit link of any book in the book listing page, it will show the corresponding book form as follows − Create the functionality to delete book from the bookstore. Create a new action, action_delete in the book controller as follows, public function action_delete($id = null) { if ( ! ($book = Model_Book::find($id))) { throw new HttpNotFoundException(); } else { $book->delete(); } Response::redirect('book'); } Here, we are checking for the existence of book in the database using the supplied book id. If the book is found, then it is deleted and redirected to index page. Otherwise, a page not found information will be shown. Check the delete action by clicking the delete link in the book listing page. It will delete the requested book and then again be redirected to the index page. Finally, all the functionalities to add, edit, delete, and list the book information is created. FuelPHP is simple, flexible, scalable, and easily configurable compared to other MVC based PHP frameworks. It provides all the features of the modern MVC framework. It can be used as is or can be changed completely to suit our needs. Above all, it is a great choice for web development. Print Add Notes Bookmark this page
[ { "code": null, "e": 2309, "s": 2209, "text": "In this chapter, we will learn how to create a complete MVC based BookStore application in FuelPHP." }, { "code": null, "e": 2388, "s": 2309, "text": "Create a new project named “BookStore” in FuelPHP using the following command." }, { "code": null, "e": 2410, "s": 2388, "text": "oil create bookstore\n" }, { "code": null, "e": 2540, "s": 2410, "text": "Create a new layout for our application. Create a file, layout.php at location fuel/app/views/layout.php. The code is as follows," }, { "code": null, "e": 4429, "s": 2540, "text": "<!DOCTYPE html> \n<html lang = \"en\"> \n <head> \n <meta charset = \"utf-8\"> \n <meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\"> \n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\"> \n <title><?php echo $title; ?></title> \n \n <!-- Bootstrap core CSS --> \n <link href = \"/assets/css/bootstrap.min.css\" rel = \"stylesheet\"> \n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n </script> \n <script src = \"/assets/js/bootstrap.min.js\"></script> \n </head> \n \n <body> \n <nav class = \"navbar navbar-inverse navbar-fixed-top\"> \n <div class = \"container\"> \n <div class = \"navbar-header\">\n \n <button type = \"button\" class = \"navbar-toggle collapsed\" \n datatoggle = \"collapse\" data-target = \"#navbar\" \n aria-expanded = \"false\" ariacontrols = \"navbar\"> \n <span class= \"sr-only\">Toggle navigation</span> \n <span class = \"icon-bar\"></span> \n <span class = \"icon-bar\"></span> \n <span class = \"icon-bar\"></span> \n </button> \n <a class = \"navbar-brand\" href = \"#\">FuelPHP Sample</a> \n </div> \n \n <div id = \"navbar\" class = \"collapse navbar-collapse\"> \n <ul class = \"nav navbar-nav\"> \n <li class = \"active\"><a href = \"/book/index\">Home</a></li> \n <li><a href = \"/book/add\">Add book</a></li> \n </ul> \n </div><!--/.nav-collapse --> \n </div> \n </nav> \n \n <div class = \"container\"> \n <div class = \"starter-template\" style = \"padding: 50px 0 0 0;\"> \n <?php echo $content; ?> \n </div> \n \n </div><!-- /.container --> \n </body>\n \n</html>" }, { "code": null, "e": 4682, "s": 4429, "text": "Here, we are using bootstrap template. FuelPHP has first class support for bootstrap templates. We have created two variables, title and content. title is used to specify the current page's title and content is used to specify the current page details." }, { "code": null, "e": 4850, "s": 4682, "text": "Create a new controller, Controller_Book to show, add, edit, and delete the book. Create a new file, fuel/app/classes/controller/book.php and place the following code." }, { "code": null, "e": 5244, "s": 4850, "text": "<?php \n class Controller_Book extends Controller_Template {\n public $template = 'layout'; \n public function action_index() { \n \n // Create the view object \n $view = View::forge('book/index'); \n \n // set the template variables \n $this->template->title = \"Book index page\"; \n $this->template->content = $view; \n } \n } " }, { "code": null, "e": 5379, "s": 5244, "text": "Here, we have created the book controller by inheriting template controller and set the default template as fuel/app/views/layout.php." }, { "code": null, "e": 5530, "s": 5379, "text": "Create a folder, book in views directory under fuel/app/views folder. Then, create a file index.php inside the book folder and add the following code," }, { "code": null, "e": 5550, "s": 5530, "text": "<h3>index page</h3>" }, { "code": null, "e": 5602, "s": 5550, "text": "As of now, we have created a basic book controller." }, { "code": null, "e": 5785, "s": 5602, "text": "Update the default route to set the home page of the application to book controller. Open the default routing configuration file, fuel/app/config/routes.php and change it as follows." }, { "code": null, "e": 6002, "s": 5785, "text": "<?php \n return array ( \n '_root_' => 'book/index', // The default route \n '_404_' => 'welcome/404', // The main 404 route \n\n 'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'), \n ); " }, { "code": null, "e": 6112, "s": 6002, "text": "Now, requesting the URL, http://localhost:8080/ will return the index page of the book controller as follows," }, { "code": null, "e": 6180, "s": 6112, "text": "Create a new database in MySQL server, using the following command," }, { "code": null, "e": 6220, "s": 6180, "text": "create database tutorialspoint_bookdb \n" }, { "code": null, "e": 6290, "s": 6220, "text": "Then, create a table inside the database using the following command," }, { "code": null, "e": 6452, "s": 6290, "text": "CREATE TABLE book ( \n id INT PRIMARY KEY AUTO_INCREMENT, \n title VARCHAR(80) NOT NULL, \n author VARCHAR(80) NOT NULL, \n price DECIMAL(10, 2) NOT NULL \n);" }, { "code": null, "e": 6528, "s": 6452, "text": "Insert some sample record into the table using the following SQL statement." }, { "code": null, "e": 6930, "s": 6528, "text": "INSERT \nINTO \n book(title, \n author, \n price) \nVALUES( \n 'The C Programming Language', \n 'Dennie Ritchie', \n 25.00 \n),( \n 'The C++ Programming Language', \n 'Bjarne Stroustrup', \n 80.00\n),( \n 'C Primer Plus (5th Edition)', \n 'Stephen Prata', \n 45.00 \n),('Modern PHP', 'Josh Lockhart', 10.00),( \n 'Learning PHP, MySQL & JavaScript, 4th Edition', \n 'Robin Nixon', \n 30.00 \n)" }, { "code": null, "e": 7023, "s": 6930, "text": "Configure the database using database configuration file, db.php located at fuel/app/config." }, { "code": null, "e": 8376, "s": 7023, "text": "<?php \n return array ( \n 'development' => array ( \n 'type' => 'mysqli', \n 'connection' => array ( \n 'hostname' => 'localhost', \n 'port' => '3306', \n 'database' => 'tutorialspoint_bookdb', \n 'username' => 'root', \n 'password' => 'password', \n 'persistent' => false, \n 'compress' => false, \n ), \n 'identifier' => '`', \n 'table_prefix' => '', \n 'charset' => 'utf8', \n 'enable_cache' => true, \n 'profiling' => false, \n 'readonly' => false, \n ),\n 'production' => array ( \n 'type' => 'mysqli', \n 'connection' => array ( \n 'hostname' => 'localhost', \n 'port' => '3306', \n 'database' => 'tutorialspoint_bookdb', \n 'username' => 'root', \n 'password' => 'password', \n 'persistent' => false, \n 'compress' => false, \n ), \n 'identifier' => '`', \n 'table_prefix' => '', \n 'charset' => 'utf8', \n 'enable_cache' => true, \n 'profiling' => false, \n 'readonly' => false, \n ), \n );" }, { "code": null, "e": 8472, "s": 8376, "text": "Update the main configuration file to include ORM package. It is located at “fuel/app/config/”." }, { "code": null, "e": 8548, "s": 8472, "text": "'always_load' => array ( \n 'packages' => array ( \n 'orm' \n ), \n), " }, { "code": null, "e": 8644, "s": 8548, "text": "Create a book model in book.php located at “fuel/app/classes/model”. It is defined as follows −" }, { "code": null, "e": 10013, "s": 8644, "text": "<?php \n class Model_Book extends Orm\\Model { \n protected static $_connection = 'production'; \n protected static $_table_name = 'book'; \n protected static $_primary_key = array('id'); \n \n protected static $_properties = array ( \n 'id', \n 'title' => array ( \n 'data_type' => 'varchar', \n 'label' => 'Book title', \n 'validation' => array ( \n 'required', \n 'min_length' => array(3), \n 'max_length' => array(80) \n ), \n \n 'form' => array ( \n 'type' => 'text' \n ), \n ), \n 'author' => array ( \n 'data_type' => 'varchar', \n 'label' => 'Book author', \n 'validation' => array ( \n 'required', \n ), \n 'form' => array ( \n 'type' => 'text' \n ), \n ), \n 'price' => array ( \n 'data_type' => 'decimal', \n 'label' => 'Book price', \n 'validation' => array ( \n 'required', \n ), \n 'form' => array ( \n 'type' => 'text' \n ), \n ), \n ); \n protected static $_observers = array('Orm\\\\Observer_Validation' => array ( \n 'events' => array('before_save') \n )); \n }" }, { "code": null, "e": 10121, "s": 10013, "text": "Here, we have specified the database details as properties of the model. It has validation details as well." }, { "code": null, "e": 10209, "s": 10121, "text": "Update the index action in book controller to list the available books in the database." }, { "code": null, "e": 10761, "s": 10209, "text": "<?php \n class Controller_Book extends Controller_Template { \n public $template = 'layout'; \n public function action_index() { \n \n // Create the view object \n $view = View::forge('book/index'); \n \n // fetch the book from database and set it to the view \n $books = Model_Book::find('all'); \n $view->set('books', $books); \n \n // set the template variables\n $this->template->title = \"Book index page\"; \n $this->template->content = $view; \n } \n }" }, { "code": null, "e": 10875, "s": 10761, "text": "Here, we have used the orm to fetch the book details from the database and then passed the book details to views." }, { "code": null, "e": 10981, "s": 10875, "text": "Update the view file index.php located at “fuel/app/views/book”. The complete updated code is as follows," }, { "code": null, "e": 11728, "s": 10981, "text": "<table class = \"table\"> \n <thead> \n <tr> \n <th>#</th> \n <th>Title</th> \n <th>Author</th> \n <th>Price</th> \n <th></th> \n </tr> \n </thead> \n \n <tbody> \n <?php \n foreach($books as $book) { \n ?> \n \n <tr> \n <td><?php echo $book['id']; ?></td> \n <td><?php echo $book['title']; ?></td> \n <td><?php echo $book['author']; ?></td> \n <td><?php echo $book['price']; ?></td> \n <td> \n <a href = \"/book/edit/<?php echo $book['id']; ?>\">Edit</a> \n <a href = \"/book/delete/<?php echo $book['id']; ?>\">Delete</a> \n </td>\n </tr> \n \n <?php \n } \n ?> \n </tbody> \n</table> \n<ul>\n</ul> " }, { "code": null, "e": 11808, "s": 11728, "text": "Now, requesting the URL, http://localhost:8080/ will show the page as follows −" }, { "code": null, "e": 11938, "s": 11808, "text": "Create the functionality to add a new book into the bookstore. Create a new action, action_add in the book controller as follows," }, { "code": null, "e": 12982, "s": 11938, "text": "public function action_add() { \n \n // create a new fieldset and add book model \n $fieldset = Fieldset::forge('book')->add_model('Model_Book'); \n \n // get form from fieldset \n $form = $fieldset->form(); \n \n // add submit button to the form \n $form->add('Submit', '', array('type' => 'submit', 'value' => 'Submit'));\n \n // build the form and set the current page as action \n $formHtml = $fieldset->build(Uri::create('book/add')); \n $view = View::forge('book/add'); \n $view->set('form', $formHtml, false); \n \n if (Input::param() != array()) { \n try { \n $book = Model_Book::forge(); \n $book->title = Input::param('title'); \n $book->author = Input::param('author'); \n $book->price = Input::param('price'); \n $book->save(); \n Response::redirect('book'); \n } catch (Orm\\ValidationFailed $e) { \n $view->set('errors', $e->getMessage(), false); \n } \n } \n $this->template->title = \"Book add page\"; \n $this->template->content = $view; } " }, { "code": null, "e": 13036, "s": 12982, "text": "Here the following two processes are being performed," }, { "code": null, "e": 13110, "s": 13036, "text": "Building the book form to add book using Fieldset methods and Book model." }, { "code": null, "e": 13184, "s": 13110, "text": "Building the book form to add book using Fieldset methods and Book model." }, { "code": null, "e": 13734, "s": 13184, "text": "Processing the book form, when the user enters the book information and submitted back the form. It can be found by checking the Input::param() method for any submitted data. Processing the form involves the following steps −\n\nGather the book information.\nValidate the book information. We have already set the validation to be called before save method. If the validation fails, it will throw Orm\\ValidationFailed exception.\nStore the book information into the database.\nRedirect the user to index page on success. Otherwise, show the form again.\n\n" }, { "code": null, "e": 13960, "s": 13734, "text": "Processing the book form, when the user enters the book information and submitted back the form. It can be found by checking the Input::param() method for any submitted data. Processing the form involves the following steps −" }, { "code": null, "e": 13989, "s": 13960, "text": "Gather the book information." }, { "code": null, "e": 14018, "s": 13989, "text": "Gather the book information." }, { "code": null, "e": 14188, "s": 14018, "text": "Validate the book information. We have already set the validation to be called before save method. If the validation fails, it will throw Orm\\ValidationFailed exception." }, { "code": null, "e": 14358, "s": 14188, "text": "Validate the book information. We have already set the validation to be called before save method. If the validation fails, it will throw Orm\\ValidationFailed exception." }, { "code": null, "e": 14404, "s": 14358, "text": "Store the book information into the database." }, { "code": null, "e": 14450, "s": 14404, "text": "Store the book information into the database." }, { "code": null, "e": 14526, "s": 14450, "text": "Redirect the user to index page on success. Otherwise, show the form again." }, { "code": null, "e": 14602, "s": 14526, "text": "Redirect the user to index page on success. Otherwise, show the form again." }, { "code": null, "e": 14858, "s": 14602, "text": "We are doing both, showing the form as well as processing the form in the same action. When the user calls the action for the first time, it will show the form. When the user enters the book information and submits the data, then it will process the form." }, { "code": null, "e": 14972, "s": 14858, "text": "Create the view for add book action. Create a new file, fuel/app/views/book/add.php and enter the following code," }, { "code": null, "e": 15863, "s": 14972, "text": "<style> \n #form table { \n width: 90%; \n } \n #form table tr { \n width: 90% \n } \n #form table tr td { \n width: 50% \n } \n #form input[type = text], select { \n width: 100%; \n padding: 12px 20px; \n margin: 8px 0; \n display: inline-block; \n border: 1px solid #ccc; \n border-radius: 4px; \n box-sizing: border-box; \n } \n #form input[type = submit] { \n width: 100%;\n background-color: #3c3c3c; \n color: white; \n padding: 14px 20px; \n margin: 8px 0; \n border: none; \n border-radius: 4px; \n cursor: pointer; \n } \n #form div { \n border-radius: 5px; \n background-color: #f2f2f2; \n padding: 20px; \n } \n</style> \n\n<div id = \"form\"> \n <h2>Book form</h2> \n \n <?php \n if(isset($errors)) { \n echo $errors; \n } \n echo $form; \n ?> \n</div> " }, { "code": null, "e": 15976, "s": 15863, "text": "Here, we are just showing the form created in the action method. In addition, we are showing the errors, if any." }, { "code": null, "e": 16100, "s": 15976, "text": "Requesting the url, http://localhost:8080/book/add or clicking the Add book navigation link, will show the form as follows," }, { "code": null, "e": 16270, "s": 16100, "text": "After entering the book information and submitting the page, the book information will be stored into the database and the page gets redirected to index page as follows." }, { "code": null, "e": 16413, "s": 16270, "text": "Create the functionality to edit and update the existing book information. Create a new action, action_edit in the book controller as follows." }, { "code": null, "e": 17562, "s": 16413, "text": "public function action_edit($id = false) { \n if(!($book = Model_Book::find($id))) { \n throw new HttpNotFoundException(); \n } \n \n // create a new fieldset and add book model \n $fieldset = Fieldset::forge('book')->add_model('Model_Book'); \n $fieldset->populate($book); \n \n // get form from fieldset \n $form = $fieldset->form(); \n \n // add submit button to the form\n $form->add('Submit', '', array('type' => 'submit', 'value' => 'Submit')); \n \n // build the form and set the current page as action \n $formHtml = $fieldset->build(Uri::create('book/edit/' . $id)); \n $view = View::forge('book/add'); \n $view->set('form', $formHtml, false); \n \n if (Input::param() != array()) { \n try { \n $book->title = Input::param('title'); \n $book->author = Input::param('author'); \n $book->price = Input::param('price'); \n $book->save(); \n Response::redirect('book'); \n } catch (Orm\\ValidationFailed $e) { \n $view->set('errors', $e->getMessage(), false); \n } \n } \n $this->template->title = \"Book edit page\"; \n $this->template->content = $view; \n}" }, { "code": null, "e": 17832, "s": 17562, "text": "It is similar to add action, except it searches the requested book by id before processing the page. If any book information is found in the database, it will proceed and show the book information in the form. Otherwise, it will throw file not found exception and exit." }, { "code": null, "e": 17924, "s": 17832, "text": "Create the view for edit book action. Here, we are using the same view used for add action." }, { "code": null, "e": 18036, "s": 17924, "text": "Click the edit link of any book in the book listing page, it will show the corresponding book form as follows −" }, { "code": null, "e": 18166, "s": 18036, "text": "Create the functionality to delete book from the bookstore. Create a new action, action_delete in the book controller as follows," }, { "code": null, "e": 18378, "s": 18166, "text": "public function action_delete($id = null) { \n if ( ! ($book = Model_Book::find($id))) { \n throw new HttpNotFoundException(); \n\n } else { \n $book->delete(); \n } \n Response::redirect('book'); \n} " }, { "code": null, "e": 18596, "s": 18378, "text": "Here, we are checking for the existence of book in the database using the supplied book id. If the book is found, then it is deleted and redirected to index page. Otherwise, a page not found information will be shown." }, { "code": null, "e": 18756, "s": 18596, "text": "Check the delete action by clicking the delete link in the book listing page. It will delete the requested book and then again be redirected to the index page." }, { "code": null, "e": 18853, "s": 18756, "text": "Finally, all the functionalities to add, edit, delete, and list the book information is created." }, { "code": null, "e": 19140, "s": 18853, "text": "FuelPHP is simple, flexible, scalable, and easily configurable compared to other MVC based PHP frameworks. It provides all the features of the modern MVC framework. It can be used as is or can be changed completely to suit our needs. Above all, it is a great choice for web development." }, { "code": null, "e": 19147, "s": 19140, "text": " Print" }, { "code": null, "e": 19158, "s": 19147, "text": " Add Notes" } ]
C++ Program to find whether a number is the power of two?
Check if a given number is a power of 2. First check below which numbers are the power of two or not. This code checks whether the number is odd and then divide it concurrently until it becomes 0 or odd. If it becomes 0 then it is a power 2 else it is not. A better choice is to take the log of the number. If it is an integer, then n is a power of 2 else not. Numbers that are powers of 2: 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ... 22 = 4 25 = 32 210 = 1024 Input: 8 Output: Number is power of 2 A simple method for this is to simply take the log of the number on base 2 and if you get an integer then the number is the power of 2. By simply repeatedly dividing N by 2 if N is an even number. If it end up at 1 then N is a power of 2 #include <iostream> using namespace std; int main() { int n=8; if(n>0) { while(n%2 == 0) { n/=2; } if(n == 1) { cout<<"Number is power of 2"<<endl; } } if(n == 0 || n != 1) { cout<<"Number is not power of 2"<<endl; } return 0; }
[ { "code": null, "e": 1319, "s": 1062, "text": "Check if a given number is a power of 2. First check below which numbers are the power of two or not. This code checks whether the number is odd and then divide it concurrently until it becomes 0 or odd. If it becomes 0 then it is a power 2 else it is not." }, { "code": null, "e": 1453, "s": 1319, "text": "A better choice is to take the log of the number. If it is an integer, then n is a power of 2 else not. Numbers that are powers of 2:" }, { "code": null, "e": 1530, "s": 1453, "text": "2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ...\n22 = 4\n25 = 32\n210 = 1024" }, { "code": null, "e": 1568, "s": 1530, "text": "Input: 8\nOutput: Number is power of 2" }, { "code": null, "e": 1704, "s": 1568, "text": "A simple method for this is to simply take the log of the number on base 2 and if you get an integer then the number is the power of 2." }, { "code": null, "e": 1806, "s": 1704, "text": "By simply repeatedly dividing N by 2 if N is an even number. If it end up at 1 then N is a power of 2" }, { "code": null, "e": 2101, "s": 1806, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int n=8;\n if(n>0) {\n while(n%2 == 0) {\n n/=2;\n }\n if(n == 1) {\n cout<<\"Number is power of 2\"<<endl;\n }\n }\n if(n == 0 || n != 1) {\n cout<<\"Number is not power of 2\"<<endl;\n }\n return 0;\n}" } ]
Access objects from the nested objects structure in MongoDB
Access objects using dot notation. Let us first create a collection with documents > db.nestedObjectDemo.insertOne({"Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], ... "StudentCountryName" : [ "US" ], ... "StudentCoreSubject" : [ "C", "Java" ], ... "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }); { "acknowledged" : true, "insertedId" : ObjectId("5c99dfc2863d6ffd454bb650") } Following is the query to display all documents from a collection with the help of find() method > db.nestedObjectDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c99dfc2863d6ffd454bb650"), "Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], "StudentCountryName" : [ "US" ], "StudentCoreSubject" : [ "C", "Java" ], "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } } Following is the query to access nested objects using dot notation >db.nestedObjectDemo.find({"Student.StudentDetails.StudentPersonalDetails.StudentName":"John"}).pretty(); This will produce the following output { "_id" : ObjectId("5c99dfc2863d6ffd454bb650"), "Student" : { "StudentDetails" : { "StudentPersonalDetails" : { "StudentName" : [ "John" ], "StudentCountryName" : [ "US" ], "StudentCoreSubject" : [ "C", "Java" ], "StudentProject" : [ "Online Book Store", "Pig Dice Game" ] } } } }
[ { "code": null, "e": 1145, "s": 1062, "text": "Access objects using dot notation. Let us first create a collection with documents" }, { "code": null, "e": 1510, "s": 1145, "text": "> db.nestedObjectDemo.insertOne({\"Student\" : { \"StudentDetails\" : { \"StudentPersonalDetails\" : { \"StudentName\" : [ \"John\" ],\n... \"StudentCountryName\" : [ \"US\" ],\n... \"StudentCoreSubject\" : [ \"C\", \"Java\" ],\n... \"StudentProject\" : [ \"Online Book Store\", \"Pig Dice Game\" ] } } } });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c99dfc2863d6ffd454bb650\")\n}" }, { "code": null, "e": 1607, "s": 1510, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1646, "s": 1607, "text": "> db.nestedObjectDemo.find().pretty();" }, { "code": null, "e": 1685, "s": 1646, "text": "This will produce the following output" }, { "code": null, "e": 2191, "s": 1685, "text": "{\n \"_id\" : ObjectId(\"5c99dfc2863d6ffd454bb650\"),\n \"Student\" : {\n \"StudentDetails\" : {\n \"StudentPersonalDetails\" : {\n \"StudentName\" : [\n \"John\"\n ],\n \"StudentCountryName\" : [\n \"US\"\n ],\n \"StudentCoreSubject\" : [\n \"C\",\n \"Java\"\n ],\n \"StudentProject\" : [\n \"Online Book Store\",\n \"Pig Dice Game\"\n ]\n }\n }\n }\n}" }, { "code": null, "e": 2258, "s": 2191, "text": "Following is the query to access nested objects using dot notation" }, { "code": null, "e": 2364, "s": 2258, "text": ">db.nestedObjectDemo.find({\"Student.StudentDetails.StudentPersonalDetails.StudentName\":\"John\"}).pretty();" }, { "code": null, "e": 2403, "s": 2364, "text": "This will produce the following output" }, { "code": null, "e": 2909, "s": 2403, "text": "{\n \"_id\" : ObjectId(\"5c99dfc2863d6ffd454bb650\"),\n \"Student\" : {\n \"StudentDetails\" : {\n \"StudentPersonalDetails\" : {\n \"StudentName\" : [\n \"John\"\n ],\n \"StudentCountryName\" : [\n \"US\"\n ],\n \"StudentCoreSubject\" : [\n \"C\",\n \"Java\"\n ],\n \"StudentProject\" : [\n \"Online Book Store\",\n \"Pig Dice Game\"\n ]\n }\n }\n }\n}" } ]