title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Implementing next_permutation() in Java with Examples - GeeksforGeeks
28 Mar, 2022 Given an array or string, the task is to find the next lexicographically greater permutation of it in Java.Examples: Input: string = "gfg" Output: ggf Input: arr[] = {1, 2, 3} Output: {1, 3, 2} In C++, there is a specific function that saves us from a lot of code. It’s in the header file #include<algorithm>. The function is next_permutation(a.begin(), a.end()). It is used to rearrange the elements in the range [first, last) into the next lexicographically greater permutation. A permutation is each one of the N! possible arrangements the elements can take (where N is the number of elements in the range). Different permutations can be ordered according to how they compare lexicographically to each other.Apparently, Java does not provide any such inbuilt method. Therefore, this article discusses how to implement the next permutation function in Java along with its algorithm. Naïve Approach: Generate all the possible permutations of the given number/string, store them in a list and then traverse it to find the just greater permutation of the given number. Time Complexity= O(n!*n) : n! to generate all the permutations and an extra n to traverse and find the just greater permutation. Space Complexity = O(n!) : to store all the permutations. This approach is very naive and complex to implement. suppose we have array size as 100, which is not very big, but, it will generate 100! permutations. which is a huge number. Moreover, we will have to need 100! space to store all of them and then traverse it to find the next greater permutation.Algorithm: INTUITION BEHIND THIS APPROACH: Suppose we have 13542 as our question and we have to find its next permutation, on on observing it is clear that when we traverse from the last we see that the numbers are increasing up till and 5 and 3 is the first index which breaks the increasing order, hence, the first step: Find the longest non-increasing suffix and find the pivot (3 i.e., index 1 is the pivot).If the suffix is the whole array, then there is no higher order permutation for the data (In this case do as the question asks, either return -1 or the sorted array).Find the rightmost successor to the pivot : to find the rightmost successor again start traversing from the back, the moment we encounter an element greater than the pivot we stop as it is the required element (here it is 4 index=3). This works because as we are traversing from the back, the elements are linearly increasing up till 3(this is the first time array starts decreasing) so, the moment we encounter an element greater than 3 it is indeed the just greater element or successor of 3 and all the elements to the left of 4 (till 3) are greater than 3 and all the elements to the right of 4 are smaller than 3.Swap the successor and the pivot.Reverse the suffix: once we swap the successor and pivot, a higher place value is modified and updated with a greater value, so it must be clear that we will obtain the next greater permutation only if the elements after the pivot are arranged in increasing order . Find the longest non-increasing suffix and find the pivot (3 i.e., index 1 is the pivot). If the suffix is the whole array, then there is no higher order permutation for the data (In this case do as the question asks, either return -1 or the sorted array). Find the rightmost successor to the pivot : to find the rightmost successor again start traversing from the back, the moment we encounter an element greater than the pivot we stop as it is the required element (here it is 4 index=3). This works because as we are traversing from the back, the elements are linearly increasing up till 3(this is the first time array starts decreasing) so, the moment we encounter an element greater than 3 it is indeed the just greater element or successor of 3 and all the elements to the left of 4 (till 3) are greater than 3 and all the elements to the right of 4 are smaller than 3. Swap the successor and the pivot. Reverse the suffix: once we swap the successor and pivot, a higher place value is modified and updated with a greater value, so it must be clear that we will obtain the next greater permutation only if the elements after the pivot are arranged in increasing order . Below is the implementation of the above approach: Java // Java program to implement// the next_permutation method import java.util.Arrays; public class nextPermutation { // Function to swap the data // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) return false; int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) return false; int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } // Driver Code public static void main(String args[]) { int data[] = { 1, 2, 3 }; if (!findNextPermutation(data)) System.out.println("There is no higher" + " order permutation " + "for the given data."); else { System.out.println(Arrays.toString(data)); } }} [1, 3, 2] perveenneha3 Arrays lexicographic-ordering Permutation and Combination Picked Java Arrays Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23583, "s": 23555, "text": "\n28 Mar, 2022" }, { "code": null, "e": 23702, "s": 23583, "text": "Given an array or string, the task is to find the next lexicographically greater permutation of it in Java.Examples: " }, { "code": null, "e": 23780, "s": 23702, "text": "Input: string = \"gfg\"\nOutput: ggf\n\nInput: arr[] = {1, 2, 3}\nOutput: {1, 3, 2}" }, { "code": null, "e": 24471, "s": 23780, "text": "In C++, there is a specific function that saves us from a lot of code. It’s in the header file #include<algorithm>. The function is next_permutation(a.begin(), a.end()). It is used to rearrange the elements in the range [first, last) into the next lexicographically greater permutation. A permutation is each one of the N! possible arrangements the elements can take (where N is the number of elements in the range). Different permutations can be ordered according to how they compare lexicographically to each other.Apparently, Java does not provide any such inbuilt method. Therefore, this article discusses how to implement the next permutation function in Java along with its algorithm." }, { "code": null, "e": 24655, "s": 24471, "text": "Naïve Approach: Generate all the possible permutations of the given number/string, store them in a list and then traverse it to find the just greater permutation of the given number." }, { "code": null, "e": 24784, "s": 24655, "text": "Time Complexity= O(n!*n) : n! to generate all the permutations and an extra n to traverse and find the just greater permutation." }, { "code": null, "e": 24842, "s": 24784, "text": "Space Complexity = O(n!) : to store all the permutations." }, { "code": null, "e": 25153, "s": 24842, "text": "This approach is very naive and complex to implement. suppose we have array size as 100, which is not very big, but, it will generate 100! permutations. which is a huge number. Moreover, we will have to need 100! space to store all of them and then traverse it to find the next greater permutation.Algorithm: " }, { "code": null, "e": 25466, "s": 25153, "text": "INTUITION BEHIND THIS APPROACH: Suppose we have 13542 as our question and we have to find its next permutation, on on observing it is clear that when we traverse from the last we see that the numbers are increasing up till and 5 and 3 is the first index which breaks the increasing order, hence, the first step:" }, { "code": null, "e": 26638, "s": 25466, "text": "Find the longest non-increasing suffix and find the pivot (3 i.e., index 1 is the pivot).If the suffix is the whole array, then there is no higher order permutation for the data (In this case do as the question asks, either return -1 or the sorted array).Find the rightmost successor to the pivot : to find the rightmost successor again start traversing from the back, the moment we encounter an element greater than the pivot we stop as it is the required element (here it is 4 index=3). This works because as we are traversing from the back, the elements are linearly increasing up till 3(this is the first time array starts decreasing) so, the moment we encounter an element greater than 3 it is indeed the just greater element or successor of 3 and all the elements to the left of 4 (till 3) are greater than 3 and all the elements to the right of 4 are smaller than 3.Swap the successor and the pivot.Reverse the suffix: once we swap the successor and pivot, a higher place value is modified and updated with a greater value, so it must be clear that we will obtain the next greater permutation only if the elements after the pivot are arranged in increasing order ." }, { "code": null, "e": 26728, "s": 26638, "text": "Find the longest non-increasing suffix and find the pivot (3 i.e., index 1 is the pivot)." }, { "code": null, "e": 26895, "s": 26728, "text": "If the suffix is the whole array, then there is no higher order permutation for the data (In this case do as the question asks, either return -1 or the sorted array)." }, { "code": null, "e": 27514, "s": 26895, "text": "Find the rightmost successor to the pivot : to find the rightmost successor again start traversing from the back, the moment we encounter an element greater than the pivot we stop as it is the required element (here it is 4 index=3). This works because as we are traversing from the back, the elements are linearly increasing up till 3(this is the first time array starts decreasing) so, the moment we encounter an element greater than 3 it is indeed the just greater element or successor of 3 and all the elements to the left of 4 (till 3) are greater than 3 and all the elements to the right of 4 are smaller than 3." }, { "code": null, "e": 27548, "s": 27514, "text": "Swap the successor and the pivot." }, { "code": null, "e": 27814, "s": 27548, "text": "Reverse the suffix: once we swap the successor and pivot, a higher place value is modified and updated with a greater value, so it must be clear that we will obtain the next greater permutation only if the elements after the pivot are arranged in increasing order ." }, { "code": null, "e": 27866, "s": 27814, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27871, "s": 27866, "text": "Java" }, { "code": "// Java program to implement// the next_permutation method import java.util.Arrays; public class nextPermutation { // Function to swap the data // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) return false; int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) return false; int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } // Driver Code public static void main(String args[]) { int data[] = { 1, 2, 3 }; if (!findNextPermutation(data)) System.out.println(\"There is no higher\" + \" order permutation \" + \"for the given data.\"); else { System.out.println(Arrays.toString(data)); } }}", "e": 30318, "s": 27871, "text": null }, { "code": null, "e": 30328, "s": 30318, "text": "[1, 3, 2]" }, { "code": null, "e": 30343, "s": 30330, "text": "perveenneha3" }, { "code": null, "e": 30350, "s": 30343, "text": "Arrays" }, { "code": null, "e": 30373, "s": 30350, "text": "lexicographic-ordering" }, { "code": null, "e": 30401, "s": 30373, "text": "Permutation and Combination" }, { "code": null, "e": 30408, "s": 30401, "text": "Picked" }, { "code": null, "e": 30413, "s": 30408, "text": "Java" }, { "code": null, "e": 30420, "s": 30413, "text": "Arrays" }, { "code": null, "e": 30425, "s": 30420, "text": "Java" }, { "code": null, "e": 30523, "s": 30425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30532, "s": 30523, "text": "Comments" }, { "code": null, "e": 30545, "s": 30532, "text": "Old Comments" }, { "code": null, "e": 30575, "s": 30545, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30590, "s": 30575, "text": "Stream In Java" }, { "code": null, "e": 30611, "s": 30590, "text": "Constructors in Java" }, { "code": null, "e": 30657, "s": 30611, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30676, "s": 30657, "text": "Exceptions in Java" }, { "code": null, "e": 30693, "s": 30676, "text": "Generics in Java" }, { "code": null, "e": 30736, "s": 30693, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30752, "s": 30736, "text": "Strings in Java" }, { "code": null, "e": 30801, "s": 30752, "text": "How to remove an element from ArrayList in Java?" } ]
How to open URL in a new window using JavaScript ? - GeeksforGeeks
31 Dec, 2019 In HTML, the anchor tag is used to open new windows and tabs in a very straightforward manner. However, there is a need to do the same using JavaScript. In JavaScript, window.open() proves to be helpful. The window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values. Syntax: window.open(URL, name, specs, replace); Note: All the parameters are optional. Approach: To open a URL in new window, make sure that the second parameter is not _blank. The other parameters can be varied accordingly as per the need of the new window. Example 1: <!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <p> Click the button to open a new window. </p> <button onclick="NewTab()"> Open Geeksforgeeks </button> <script> function NewTab() { window.open("https://www.geeksforgeeks.org", "", "width=300, height=300"); } </script></body> </html> Output: Before Clicking on Button: After Clicking on Button: Example 2: Use Anchor tag to open URL in a new window. <!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <p> Click the button to open GeeksforGeeks in a new window. </p> <a onclick= 'window.open("https://www.geeksforgeeks.org/", "_blank", "width=300, height=300");'> GeeksforGeeks </a></body> </html> Output: Before Clicking on GeeksforGeeks: After Clicking on GeeksforGeeks: Example 3: Use Input tag to open URL in a new window. <!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <p> Click the button to open GeeksforGeeks in a new window. </p> <input type="button" onclick="window.open( 'https://www.geeksforgeeks.org/','geeks', 'toolbars=0,width=300,height=300,left=200, top=200,scrollbars=1,resizable=1');" value="Open the window"></body> </html> Output: Before Clicking on Button: After Clicking on Button: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Set the value of an input field in JavaScript Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24529, "s": 24501, "text": "\n31 Dec, 2019" }, { "code": null, "e": 24867, "s": 24529, "text": "In HTML, the anchor tag is used to open new windows and tabs in a very straightforward manner. However, there is a need to do the same using JavaScript. In JavaScript, window.open() proves to be helpful. The window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values." }, { "code": null, "e": 24875, "s": 24867, "text": "Syntax:" }, { "code": null, "e": 24915, "s": 24875, "text": "window.open(URL, name, specs, replace);" }, { "code": null, "e": 24954, "s": 24915, "text": "Note: All the parameters are optional." }, { "code": null, "e": 24964, "s": 24954, "text": "Approach:" }, { "code": null, "e": 25044, "s": 24964, "text": "To open a URL in new window, make sure that the second parameter is not _blank." }, { "code": null, "e": 25126, "s": 25044, "text": "The other parameters can be varied accordingly as per the need of the new window." }, { "code": null, "e": 25137, "s": 25126, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p> Click the button to open a new window. </p> <button onclick=\"NewTab()\"> Open Geeksforgeeks </button> <script> function NewTab() { window.open(\"https://www.geeksforgeeks.org\", \"\", \"width=300, height=300\"); } </script></body> </html>", "e": 25580, "s": 25137, "text": null }, { "code": null, "e": 25588, "s": 25580, "text": "Output:" }, { "code": null, "e": 25615, "s": 25588, "text": "Before Clicking on Button:" }, { "code": null, "e": 25641, "s": 25615, "text": "After Clicking on Button:" }, { "code": null, "e": 25696, "s": 25641, "text": "Example 2: Use Anchor tag to open URL in a new window." }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p> Click the button to open GeeksforGeeks in a new window. </p> <a onclick= 'window.open(\"https://www.geeksforgeeks.org/\", \"_blank\", \"width=300, height=300\");'> GeeksforGeeks </a></body> </html>", "e": 26069, "s": 25696, "text": null }, { "code": null, "e": 26077, "s": 26069, "text": "Output:" }, { "code": null, "e": 26111, "s": 26077, "text": "Before Clicking on GeeksforGeeks:" }, { "code": null, "e": 26144, "s": 26111, "text": "After Clicking on GeeksforGeeks:" }, { "code": null, "e": 26198, "s": 26144, "text": "Example 3: Use Input tag to open URL in a new window." }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p> Click the button to open GeeksforGeeks in a new window. </p> <input type=\"button\" onclick=\"window.open( 'https://www.geeksforgeeks.org/','geeks', 'toolbars=0,width=300,height=300,left=200, top=200,scrollbars=1,resizable=1');\" value=\"Open the window\"></body> </html> ", "e": 26677, "s": 26198, "text": null }, { "code": null, "e": 26685, "s": 26677, "text": "Output:" }, { "code": null, "e": 26712, "s": 26685, "text": "Before Clicking on Button:" }, { "code": null, "e": 26738, "s": 26712, "text": "After Clicking on Button:" }, { "code": null, "e": 26754, "s": 26738, "text": "JavaScript-Misc" }, { "code": null, "e": 26761, "s": 26754, "text": "Picked" }, { "code": null, "e": 26772, "s": 26761, "text": "JavaScript" }, { "code": null, "e": 26789, "s": 26772, "text": "Web Technologies" }, { "code": null, "e": 26816, "s": 26789, "text": "Web technologies Questions" }, { "code": null, "e": 26914, "s": 26816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26923, "s": 26914, "text": "Comments" }, { "code": null, "e": 26936, "s": 26923, "text": "Old Comments" }, { "code": null, "e": 26997, "s": 26936, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27042, "s": 26997, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27114, "s": 27042, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27155, "s": 27114, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27201, "s": 27155, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 27257, "s": 27201, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27290, "s": 27257, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27352, "s": 27290, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27395, "s": 27352, "text": "How to fetch data from an API in ReactJS ?" } ]
ggplot2 - Background Colors
There are ways to change the entire look of your plot with one function as mentioned below. But if you want to simply change the background color of the panel you can, use the following − We can change the background color using following command which helps in changing the panel (panel.background) − > ggplot(iris, aes(Sepal.Length, Species))+geom_point(color="firebrick")+ + theme(panel.background = element_rect(fill = 'grey75')) The change in color is clearly depicted in picture below − We can change the grid lines using property “panel.grid.major” as mentioned in command below − > ggplot(iris, aes(Sepal.Length, Species))+geom_point(color="firebrick")+ + theme(panel.background = element_rect(fill = 'grey75'), + panel.grid.major = element_line(colour = "orange", size=2), + panel.grid.minor = element_line(colour = "blue")) We can even change the plot background especially excluding the panel using “plot.background” property as mentioned below − ggplot(iris, aes(Sepal.Length, Species))+geom_point(color="firebrick")+ + theme(plot.background = element_rect(fill = 'pink')) Print Add Notes Bookmark this page
[ { "code": null, "e": 2210, "s": 2022, "text": "There are ways to change the entire look of your plot with one function as mentioned below. But if you want to simply change the background color of the panel you can, use the following −" }, { "code": null, "e": 2324, "s": 2210, "text": "We can change the background color using following command which helps in changing the panel (panel.background) −" }, { "code": null, "e": 2457, "s": 2324, "text": "> ggplot(iris, aes(Sepal.Length, Species))+geom_point(color=\"firebrick\")+\n+ theme(panel.background = element_rect(fill = 'grey75'))\n" }, { "code": null, "e": 2516, "s": 2457, "text": "The change in color is clearly depicted in picture below −" }, { "code": null, "e": 2611, "s": 2516, "text": "We can change the grid lines using property “panel.grid.major” as mentioned in command below −" }, { "code": null, "e": 2867, "s": 2611, "text": "> ggplot(iris, aes(Sepal.Length, Species))+geom_point(color=\"firebrick\")+\n+ theme(panel.background = element_rect(fill = 'grey75'),\n+ panel.grid.major = element_line(colour = \"orange\", size=2),\n+ panel.grid.minor = element_line(colour = \"blue\"))\n" }, { "code": null, "e": 2991, "s": 2867, "text": "We can even change the plot background especially excluding the panel using “plot.background” property as mentioned below −" }, { "code": null, "e": 3121, "s": 2991, "text": "ggplot(iris, aes(Sepal.Length, Species))+geom_point(color=\"firebrick\")+\n+ theme(plot.background = element_rect(fill = 'pink'))\n" }, { "code": null, "e": 3128, "s": 3121, "text": " Print" }, { "code": null, "e": 3139, "s": 3128, "text": " Add Notes" } ]
WPF - Dialog Box
All standalone applications have a main window that exposes some functionality and displays some data over which the application operates through a GUI. An application may also display additional windows to do the following − Display some specific information to users Gather useful information from users Both display and gather important information Let’s take an example to understand the concept of Dialog Box. First of all, create a new WPF project with the name WPFDialog. Drag one button and one textbox from the Toolbox. Drag one button and one textbox from the Toolbox. When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message “click any button” on it. When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message “click any button” on it. When a user clicks any of them, this dialog box gets closed and shows a textbox with the information of the button that was clicked. When a user clicks any of them, this dialog box gets closed and shows a textbox with the information of the button that was clicked. Here is the XAML code to initialize a button and a textbox with some properties. Here is the XAML code to initialize a button and a textbox with some properties. <Window x:Class = "WPFDialog.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Height = "23" Margin = "100" Name = "ShowMessageBox" VerticalAlignment = "Top" lick = "ShowMessageBox_Click"> Show Message Box </Button> <TextBox Height = "23" HorizontalAlignment = "Left" Margin = "181,167,0,0" Name = "textBox1" VerticalAlignment = "Top" Width = "120" /> </Grid> </Window> Here is the C# code in which the button click event is implemented. using System; using System.Windows; using System.Windows.Controls; namespace WPFDialog { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ShowMessageBox_Click(object sender, RoutedEventArgs e) { string msgtext = "Click any button"; string txt = "My Title"; MessageBoxButton button = MessageBoxButton.YesNoCancel; MessageBoxResult result = MessageBox.Show(msgtext, txt, button); switch (result) { case MessageBoxResult.Yes:textBox1.Text = "Yes"; break; case MessageBoxResult.No:textBox1.Text = "No"; break; case MessageBoxResult.Cancel:textBox1.Text = "Cancel"; break; } } } } When you compile and execute the above code, it will produce the following window. When you click on the button, it displays another dialog box (as shown below) that prompts the user to click a button. In case the user clicks the Yes button, it updates the textbox with the button content. 31 Lectures 2.5 hours Anadi Sharma 30 Lectures 2.5 hours Taurius Litvinavicius Print Add Notes Bookmark this page
[ { "code": null, "e": 2246, "s": 2020, "text": "All standalone applications have a main window that exposes some functionality and displays some data over which the application operates through a GUI. An application may also display additional windows to do the following −" }, { "code": null, "e": 2289, "s": 2246, "text": "Display some specific information to users" }, { "code": null, "e": 2326, "s": 2289, "text": "Gather useful information from users" }, { "code": null, "e": 2372, "s": 2326, "text": "Both display and gather important information" }, { "code": null, "e": 2499, "s": 2372, "text": "Let’s take an example to understand the concept of Dialog Box. First of all, create a new WPF project with the name WPFDialog." }, { "code": null, "e": 2549, "s": 2499, "text": "Drag one button and one textbox from the Toolbox." }, { "code": null, "e": 2599, "s": 2549, "text": "Drag one button and one textbox from the Toolbox." }, { "code": null, "e": 2743, "s": 2599, "text": "When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message “click any button” on it." }, { "code": null, "e": 2887, "s": 2743, "text": "When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message “click any button” on it." }, { "code": null, "e": 3020, "s": 2887, "text": "When a user clicks any of them, this dialog box gets closed and shows a textbox with the information of the button that was clicked." }, { "code": null, "e": 3153, "s": 3020, "text": "When a user clicks any of them, this dialog box gets closed and shows a textbox with the information of the button that was clicked." }, { "code": null, "e": 3234, "s": 3153, "text": "Here is the XAML code to initialize a button and a textbox with some properties." }, { "code": null, "e": 3315, "s": 3234, "text": "Here is the XAML code to initialize a button and a textbox with some properties." }, { "code": null, "e": 3918, "s": 3315, "text": "<Window x:Class = \"WPFDialog.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Button Height = \"23\" Margin = \"100\" Name = \"ShowMessageBox\" \n VerticalAlignment = \"Top\" lick = \"ShowMessageBox_Click\">\n Show Message Box\n </Button> \n\t\t\n <TextBox Height = \"23\" HorizontalAlignment = \"Left\" Margin = \"181,167,0,0\" \n Name = \"textBox1\" VerticalAlignment = \"Top\" Width = \"120\" />\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 3986, "s": 3918, "text": "Here is the C# code in which the button click event is implemented." }, { "code": null, "e": 4901, "s": 3986, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls; \n\nnamespace WPFDialog { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void ShowMessageBox_Click(object sender, RoutedEventArgs e) { \n string msgtext = \"Click any button\"; \n string txt = \"My Title\"; \n MessageBoxButton button = MessageBoxButton.YesNoCancel; \n MessageBoxResult result = MessageBox.Show(msgtext, txt, button); \n\t\t\t\n switch (result) { \n case MessageBoxResult.Yes:textBox1.Text = \"Yes\"; \n break; \n case MessageBoxResult.No:textBox1.Text = \"No\"; \n break; \n case MessageBoxResult.Cancel:textBox1.Text = \"Cancel\"; \n break;\n } \n } \n } \n}" }, { "code": null, "e": 4984, "s": 4901, "text": "When you compile and execute the above code, it will produce the following window." }, { "code": null, "e": 5103, "s": 4984, "text": "When you click on the button, it displays another dialog box (as shown below) that prompts the user to click a button." }, { "code": null, "e": 5191, "s": 5103, "text": "In case the user clicks the Yes button, it updates the textbox with the button content." }, { "code": null, "e": 5226, "s": 5191, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5240, "s": 5226, "text": " Anadi Sharma" }, { "code": null, "e": 5275, "s": 5240, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5298, "s": 5275, "text": " Taurius Litvinavicius" }, { "code": null, "e": 5305, "s": 5298, "text": " Print" }, { "code": null, "e": 5316, "s": 5305, "text": " Add Notes" } ]
How to remove disabled attribute using jQuery?
To remove disabled attribute using jQuery, use the removeAttr() method. You need to first remove the property using the prop() method. It will set the underlying Boolean value to false. You can try to run the following code to learn how to remove disabled attribute using jQuery: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('.disabledCheckboxes').prop("disabled", true); $('.disabledCheckboxes').removeAttr("disabled"); $(document).ready(function(){ $('button').on('click', function() { if (this.hasAttribute("disabled")) { alert('The disabled attribute exists') } else { alert('The disabled attribute does not exist') } }) }); }); </script> </head> <body> <input type="checkbox" class="disabledCheckboxes" disabled> <input type="checkbox" class="disabledCheckboxes" disabled="disabled"> <button class='button'>Result</button> </body> </html>
[ { "code": null, "e": 1248, "s": 1062, "text": "To remove disabled attribute using jQuery, use the removeAttr() method. You need to first remove the property using the prop() method. It will set the underlying Boolean value to false." }, { "code": null, "e": 1342, "s": 1248, "text": "You can try to run the following code to learn how to remove disabled attribute using jQuery:" }, { "code": null, "e": 1352, "s": 1342, "text": "Live Demo" }, { "code": null, "e": 2125, "s": 1352, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n\n $('.disabledCheckboxes').prop(\"disabled\", true);\n $('.disabledCheckboxes').removeAttr(\"disabled\");\n\n $(document).ready(function(){\n $('button').on('click', function() {\n if (this.hasAttribute(\"disabled\")) {\n alert('The disabled attribute exists')\n } else {\n alert('The disabled attribute does not exist')\n }\n })\n });\n });\n</script>\n</head>\n<body>\n<input type=\"checkbox\" class=\"disabledCheckboxes\" disabled>\n<input type=\"checkbox\" class=\"disabledCheckboxes\" disabled=\"disabled\">\n <button class='button'>Result</button>\n</body>\n</html>" } ]
GATE | GATE-CS-2003 | Question 90 - GeeksforGeeks
28 Jun, 2021 Let G = ({S}, {a, b} R, S) be a context free grammar where the rule set R isS → a S b | SS | εWhich of the following statements is true?(A) G is not ambiguous(B) There exist x, y, ∈ L (G) such that xy ∉ L(G)(C) There is a deterministic pushdown automaton that accepts L(G)(D) We can find a deterministic finite state automaton that accepts L(G)Answer: (C)Explanation: An ambiguous grammar can be converted to unambiguous one. Here we can get grammar in partial GNF form as S -> ab | abS | aSb | aSbS We can convert this into GNF too but no need for PDA reasoning so, above grammar is not a ambiguous thus a definite PDA possible Trick for this is but just deriving 3-4 strings from grammar, we can easily understand its (anbn)* above expression anbn is in CFL thus closure of DCFG is a DCFG i.e., you can get L = {ε, ab, abab, aabb, aabbab, abaabb, ababab,......} PDA will push "a" until "b" is read, start popping "a" for the "b" read. If "a" is read again from the tape then push only when stack is empty else terminate. Repeat this until string is read. Remember fastest way to get answer is by elimination other options. Quiz of this Question GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2019 | Question 27 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE-CS-2017 (Set 2) | Question 42
[ { "code": null, "e": 24472, "s": 24444, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24841, "s": 24472, "text": "Let G = ({S}, {a, b} R, S) be a context free grammar where the rule set R isS → a S b | SS | εWhich of the following statements is true?(A) G is not ambiguous(B) There exist x, y, ∈ L (G) such that xy ∉ L(G)(C) There is a deterministic pushdown automaton that accepts L(G)(D) We can find a deterministic finite state automaton that accepts L(G)Answer: (C)Explanation:" }, { "code": null, "e": 25608, "s": 24841, "text": "An ambiguous grammar can be converted to unambiguous one.\n\nHere we can get grammar in partial GNF form as\nS -> ab | abS | aSb | aSbS\n\nWe can convert this into GNF too but no need for PDA reasoning\nso, above grammar is not a ambiguous thus a definite PDA possible\n\nTrick for this is but just deriving 3-4 strings from grammar, we \ncan easily understand its (anbn)* above \nexpression anbn is in CFL thus closure of DCFG is a DCFG\ni.e., you can get L = {ε, ab, abab, aabb, aabbab, abaabb, \nababab,......}\nPDA will push \"a\" until \"b\" is read, start popping \"a\" for the \"b\" read.\n\nIf \"a\" is read again from the tape then push only when stack is empty \nelse terminate.\n\nRepeat this until string is read.\n\nRemember fastest way to get answer is by elimination other options." }, { "code": null, "e": 25630, "s": 25608, "text": "Quiz of this Question" }, { "code": null, "e": 25643, "s": 25630, "text": "GATE-CS-2003" }, { "code": null, "e": 25661, "s": 25643, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 25666, "s": 25661, "text": "GATE" }, { "code": null, "e": 25764, "s": 25666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25798, "s": 25764, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25840, "s": 25798, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25874, "s": 25840, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 25916, "s": 25874, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25950, "s": 25916, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 25983, "s": 25950, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26017, "s": 25983, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 26051, "s": 26017, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 26093, "s": 26051, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" } ]
How to deal with warning message `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. in R while creating a histogram?
The default value for bins is 30 but if we don’t pass that in geom_histogram then the warning message is shown by R in most of the cases. To avoid that, we can simply put bins=30 inside the geom_histogram() function. This will stop showing the warning message. Consider the below data frame − x<-rnorm(50000,5,1) df<-data.frame(x) Loading ggplot2 package and creating histogram of x − library(ggplot2) ggplot(df,aes(x))+geom_histogram() `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. Creating the histogram by specifying the bins − ggplot(df,aes(x))+geom_histogram(bins=30)
[ { "code": null, "e": 1323, "s": 1062, "text": "The default value for bins is 30 but if we don’t pass that in geom_histogram then the warning message is shown by R in most of the cases. To avoid that, we can simply put bins=30 inside the geom_histogram() function. This will stop showing the warning message." }, { "code": null, "e": 1355, "s": 1323, "text": "Consider the below data frame −" }, { "code": null, "e": 1393, "s": 1355, "text": "x<-rnorm(50000,5,1)\ndf<-data.frame(x)" }, { "code": null, "e": 1447, "s": 1393, "text": "Loading ggplot2 package and creating histogram of x −" }, { "code": null, "e": 1566, "s": 1447, "text": "library(ggplot2) ggplot(df,aes(x))+geom_histogram() `stat_bin()` using `bins = 30`. Pick better value with `binwidth`." }, { "code": null, "e": 1614, "s": 1566, "text": "Creating the histogram by specifying the bins −" }, { "code": null, "e": 1656, "s": 1614, "text": "ggplot(df,aes(x))+geom_histogram(bins=30)" } ]
Simple Edge Detection Model using Python | by Behic Guven | Towards Data Science
In this post, I will show you how to detect the edges in an image. Writing an edge detection program will give you some understanding of computer vision and self-driving cars. Edge detection is commonly used to understand objects in an image. It also helps the machines to make better predictions. Writing an edge detection program is a great way to understand how machines see the outside world. This will give us a better perspective when it comes to computer vision. I covered a couple of computer vision concepts in my previous articles: face detection, face recognition, and text recognition. And today, we will work on edge detection using python. Getting Started Import Libraries Edge Detection Function Choose an image Run the program We will use two main modules for this project: Numpy, Matplotlib, and OpenCV. Matplotlib is a complete library for generating static, animated, and interactive visualizations in Python. OpenCV is a highly optimized library with a focus on real-time applications. OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code. Refrence: https://opencv.org Let’s start by installing the libraries. We have to install the libraries so that our program works properly. As mentioned earlier, we will need only two libraries. We can install them in one line using PIP library manager: pip install numpy matplotlib opencv-python After the installation process is completed, we can import them to our code. You can work on a Jupiter notebook or a regular text editor like Atom. I will use Atom text editor for this project. import cv2 import numpy as np import matplotlib.pyplot as plt Now, we can move to the fun part, where we will write the edge detection function. You will be amazed at how simple it is using the OpenCV package. This OpenCV detection model is also known as the Canny edge detection model. Our function is consisting of three parts: edge detection, visualization, and lastly, saving the result. def simple_edge_detection(image): edges_detected = cv2.Canny(image , 100, 200) images = [image , edges_detected] Understanding the code: Canny is the method we are calling to do edge detection using OpenCV. Image is a parameter of the function, which means we will pass the image when calling the function. This way, you can test your program with different images easily. 100 and 200 are the minimum and maximum values in hysteresis thresholding. If you want to learn more about Canny edge detection: (Official Documentation). location = [121, 122] for loc, edge_image in zip(location, images): plt.subplot(loc) plt.imshow(edge_image, cmap='gray') Understanding the code: Location array is needed for the plotting part. And then, we are visualization both the original image and the edge detected image. The cmap parameter is used to change the color of the images. In our case, we are converting them to gray. This final part of the function will save the edge detected image and the comparison plot. Thanks to OpenCv and Matplotlib packages; imwrite and savefig functions do the saving for us. And in the last line, the show function is going to show us the plot that was created. cv2.imwrite('edge_detected.png', edges_detected) plt.savefig('edge_plot.png') plt.show() This will be an easy image. We will find an image that we want to test our canny edge detection program. I am going to use the free stock photography page to find a couple of good images. Here is the link for their website. After downloading the images, make sure to put them inside the same folder as your project. This will help to import them into the program easily. Let’s define an image variable and import the image. Here is how to read an image using OpenCV: img = cv2.imread('test_image.jpg', 0) The best and the last step, it’s time to run the program. So far, there is nothing that triggers the function. We have to call the function so that the magic happens. Oh, also don’t forget to pass your image as a parameter. Let’s call the function: simple_edge_detection(img) Well done! You have created an edge detection model using Python. Python is a very compelling language, and things you can create with python is limitless. Now, you also have an idea of how to use computer vision in a real project. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. I am so glad if you learned something new today. Feel free to contact me if you have any questions while implementing the code. 😊 Follow my blog and youtube channel to stay inspired. Thank you,
[ { "code": null, "e": 642, "s": 172, "text": "In this post, I will show you how to detect the edges in an image. Writing an edge detection program will give you some understanding of computer vision and self-driving cars. Edge detection is commonly used to understand objects in an image. It also helps the machines to make better predictions. Writing an edge detection program is a great way to understand how machines see the outside world. This will give us a better perspective when it comes to computer vision." }, { "code": null, "e": 826, "s": 642, "text": "I covered a couple of computer vision concepts in my previous articles: face detection, face recognition, and text recognition. And today, we will work on edge detection using python." }, { "code": null, "e": 842, "s": 826, "text": "Getting Started" }, { "code": null, "e": 859, "s": 842, "text": "Import Libraries" }, { "code": null, "e": 883, "s": 859, "text": "Edge Detection Function" }, { "code": null, "e": 899, "s": 883, "text": "Choose an image" }, { "code": null, "e": 915, "s": 899, "text": "Run the program" }, { "code": null, "e": 1178, "s": 915, "text": "We will use two main modules for this project: Numpy, Matplotlib, and OpenCV. Matplotlib is a complete library for generating static, animated, and interactive visualizations in Python. OpenCV is a highly optimized library with a focus on real-time applications." }, { "code": null, "e": 1544, "s": 1178, "text": "OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code." }, { "code": null, "e": 1573, "s": 1544, "text": "Refrence: https://opencv.org" }, { "code": null, "e": 1614, "s": 1573, "text": "Let’s start by installing the libraries." }, { "code": null, "e": 1738, "s": 1614, "text": "We have to install the libraries so that our program works properly. As mentioned earlier, we will need only two libraries." }, { "code": null, "e": 1797, "s": 1738, "text": "We can install them in one line using PIP library manager:" }, { "code": null, "e": 1840, "s": 1797, "text": "pip install numpy matplotlib opencv-python" }, { "code": null, "e": 2034, "s": 1840, "text": "After the installation process is completed, we can import them to our code. You can work on a Jupiter notebook or a regular text editor like Atom. I will use Atom text editor for this project." }, { "code": null, "e": 2096, "s": 2034, "text": "import cv2 import numpy as np import matplotlib.pyplot as plt" }, { "code": null, "e": 2426, "s": 2096, "text": "Now, we can move to the fun part, where we will write the edge detection function. You will be amazed at how simple it is using the OpenCV package. This OpenCV detection model is also known as the Canny edge detection model. Our function is consisting of three parts: edge detection, visualization, and lastly, saving the result." }, { "code": null, "e": 2545, "s": 2426, "text": "def simple_edge_detection(image): edges_detected = cv2.Canny(image , 100, 200) images = [image , edges_detected]" }, { "code": null, "e": 2569, "s": 2545, "text": "Understanding the code:" }, { "code": null, "e": 2639, "s": 2569, "text": "Canny is the method we are calling to do edge detection using OpenCV." }, { "code": null, "e": 2805, "s": 2639, "text": "Image is a parameter of the function, which means we will pass the image when calling the function. This way, you can test your program with different images easily." }, { "code": null, "e": 2880, "s": 2805, "text": "100 and 200 are the minimum and maximum values in hysteresis thresholding." }, { "code": null, "e": 2960, "s": 2880, "text": "If you want to learn more about Canny edge detection: (Official Documentation)." }, { "code": null, "e": 3087, "s": 2960, "text": "location = [121, 122] for loc, edge_image in zip(location, images): plt.subplot(loc) plt.imshow(edge_image, cmap='gray')" }, { "code": null, "e": 3111, "s": 3087, "text": "Understanding the code:" }, { "code": null, "e": 3159, "s": 3111, "text": "Location array is needed for the plotting part." }, { "code": null, "e": 3243, "s": 3159, "text": "And then, we are visualization both the original image and the edge detected image." }, { "code": null, "e": 3350, "s": 3243, "text": "The cmap parameter is used to change the color of the images. In our case, we are converting them to gray." }, { "code": null, "e": 3622, "s": 3350, "text": "This final part of the function will save the edge detected image and the comparison plot. Thanks to OpenCv and Matplotlib packages; imwrite and savefig functions do the saving for us. And in the last line, the show function is going to show us the plot that was created." }, { "code": null, "e": 3711, "s": 3622, "text": "cv2.imwrite('edge_detected.png', edges_detected) plt.savefig('edge_plot.png') plt.show()" }, { "code": null, "e": 3935, "s": 3711, "text": "This will be an easy image. We will find an image that we want to test our canny edge detection program. I am going to use the free stock photography page to find a couple of good images. Here is the link for their website." }, { "code": null, "e": 4178, "s": 3935, "text": "After downloading the images, make sure to put them inside the same folder as your project. This will help to import them into the program easily. Let’s define an image variable and import the image. Here is how to read an image using OpenCV:" }, { "code": null, "e": 4216, "s": 4178, "text": "img = cv2.imread('test_image.jpg', 0)" }, { "code": null, "e": 4465, "s": 4216, "text": "The best and the last step, it’s time to run the program. So far, there is nothing that triggers the function. We have to call the function so that the magic happens. Oh, also don’t forget to pass your image as a parameter. Let’s call the function:" }, { "code": null, "e": 4492, "s": 4465, "text": "simple_edge_detection(img)" }, { "code": null, "e": 4826, "s": 4492, "text": "Well done! You have created an edge detection model using Python. Python is a very compelling language, and things you can create with python is limitless. Now, you also have an idea of how to use computer vision in a real project. Working on hands-on programming projects like this one is the best way to sharpen your coding skills." }, { "code": null, "e": 4956, "s": 4826, "text": "I am so glad if you learned something new today. Feel free to contact me if you have any questions while implementing the code. 😊" } ]
What is Motion UI? - GeeksforGeeks
15 Sep, 2020 A good design is an essential aspect of a website or app. These are important as it helps to build a good user interface. Transitions and animations are great tools and can help bring a much-needed elegance to the web. In the early days, the static design was used, but now the motion design is very popular. One way to introduce these transitions and animations to the web is by ZURB Studios. ZURB has been in the business of making cool web design software for quite a while now, and one of their most common ones is called Motion UI. Motion UI is ZURB’s own Sass library that provides nothing but dynamic transitions and animations for your platform. Both of these effects are specifically incorporated into the Motion UI, and this helps make the animation process incredibly quick and time-efficient. Motion UI is a Sass library for quickly creating flexible UI transitions and animations. It is a stand-alone library that controls the transformation effects included in a variety of Foundation components, including Toggler, Reveal and Orbit. You can use npm or bower to install the Motion UI library in your project. Where the package includes a CSS file with a collection of pre-made transitions and animations, along with the Sass source files that allow you to build your own. npm install motion-ui --save-dev bower install motion-ui --save-dev Motion UI provides a set of pre-made effects as a CSS package. This includes transition effects to slide, scale, fade, hinge, and spin, as well as several built-in animations. You can add a path to the Motion UI library in the Compass by using config.rb as given below: add_import_path 'node_modules/motion-ui/src' You can use the following lines of code to include the path in the gulp-sass: gulp.src('./src/scss/app.scss') .pipe(sass({ includePaths: ['node_modules/motion-ui/src'] })); Finally, you can import the Motion UI library in the SASS file using the code given below: @import 'motion-ui' @include motion-ui-transitions; @include motion-ui-animations; Just like transitions that you would use in a slide show or video, those here are meant to help the transition process of components that come in and out of your site. The Motion UI package includes a small JavaScript library designed to trigger these transitions. Foundation provides transition effects through the use of transition classes that are created by the Motion UI library which includes more than two dozen built-in transition classes. They can be enabled by adding the following code to your Sass file after you have imported the library: @include motion-ui-transitions; You can set the custom transition classes using Motion UI’s mixin library. For example, mui-fade() use to creates a fade transition by adjusting the opacity of the element. @include mui-fade( $state: in, $from: in, $to: out, $duration: 0.5s, $timing: easeInOut ); You can also use the Motion UI transition effects to create CSS animations. The library also allows creating series effects, with animations on multiple elements occurring in a queue. All of these animations are created with the mixin’s mui-animation(), where it is used to create CSS keyframe animations. Along with standard, one-time animations, Motion UI also allows you the ability to animate multiple items in a specified series. You can begin your series with the mui-series() and inside this mixin, you can attach animations to classes with the mui-queue() mixin. It is essential that you properly apply the Motion UI on your website and on your apps. In a variety of cases this can be achieved as described below: Welcoming users: In some cases, the applications and websites will welcome the users with a pleasant message of greeting. A good message of welcome has a positive impact on the customers. Who can skip the Nokia mobiles logo of two hands meeting? A pleasant welcome screen on the applications and websites improves the user’s experiences. You only need to apply motion when necessary and have a specific intention for the same reason. If possible, this must only be implemented when the loading of apps and website is delayed for a period.Inform about actions: The users need to be aware of and how they will perform on your website. This guidance will enhance the UX and contribute to the improvement of the website and apps. It must also be borne in mind that the motions implemented must complement and add to the user experience of the app and must also help to retain the attention of users and by using elements such as bounce and velocity.Confirm the activities: In a majority of cases, various activities such as deleting mail, sending mail, uninstalling applications, clicking on some links, deleting data, etc. and other such elements need confirmation. It is used in a variety of irreversible activities. In a lot of cases, the confirmation process will be animated to attract more attention to users and to ensure that they do not make any errors in doing so.Add fun elements: There are a lot of apps and websites that introduce fun elements and have become really popular. This makes it easy to navigate the apps and the website, which makes it easier for users to visit again and again. Therefore, the fun elements must be added properly to the website. Various fun elements such as zooming in, zooming out, sliding, etc can be introduced to make the display and content simpler and more enjoyable.Feedback loop: In a majority of cases, users interact with applications and websites. In such situations, the feedback helps to provide a better user experience. Suppose you try to build a response when the user wants to log in to the app or website and enter the wrong password. In this case, the feedback loop turns out to be very useful and helps the users to log in to notify in such cases. It can also be used to view some animations on the websites. These are available in a wide range of applications and can be viewed on the lock screen of the websites.Refresh content: The content of social media websites and applications is updated very frequently. In such cases, the content can quickly be refreshed so that the users can get the best user experience and also get the content when they arrive. In this case, You can either slide the screen down and leave it to update the content on Twitter, Instagram, Facebook, and other such apps. Apart from these, you can also click on the available button to view the new updates. Welcoming users: In some cases, the applications and websites will welcome the users with a pleasant message of greeting. A good message of welcome has a positive impact on the customers. Who can skip the Nokia mobiles logo of two hands meeting? A pleasant welcome screen on the applications and websites improves the user’s experiences. You only need to apply motion when necessary and have a specific intention for the same reason. If possible, this must only be implemented when the loading of apps and website is delayed for a period. Inform about actions: The users need to be aware of and how they will perform on your website. This guidance will enhance the UX and contribute to the improvement of the website and apps. It must also be borne in mind that the motions implemented must complement and add to the user experience of the app and must also help to retain the attention of users and by using elements such as bounce and velocity. Confirm the activities: In a majority of cases, various activities such as deleting mail, sending mail, uninstalling applications, clicking on some links, deleting data, etc. and other such elements need confirmation. It is used in a variety of irreversible activities. In a lot of cases, the confirmation process will be animated to attract more attention to users and to ensure that they do not make any errors in doing so. Add fun elements: There are a lot of apps and websites that introduce fun elements and have become really popular. This makes it easy to navigate the apps and the website, which makes it easier for users to visit again and again. Therefore, the fun elements must be added properly to the website. Various fun elements such as zooming in, zooming out, sliding, etc can be introduced to make the display and content simpler and more enjoyable. Feedback loop: In a majority of cases, users interact with applications and websites. In such situations, the feedback helps to provide a better user experience. Suppose you try to build a response when the user wants to log in to the app or website and enter the wrong password. In this case, the feedback loop turns out to be very useful and helps the users to log in to notify in such cases. It can also be used to view some animations on the websites. These are available in a wide range of applications and can be viewed on the lock screen of the websites. Refresh content: The content of social media websites and applications is updated very frequently. In such cases, the content can quickly be refreshed so that the users can get the best user experience and also get the content when they arrive. In this case, You can either slide the screen down and leave it to update the content on Twitter, Instagram, Facebook, and other such apps. Apart from these, you can also click on the available button to view the new updates. Motion UI is quite necessary and must be adopted and implemented on your website. This guarantees that you are able to provide the best user experience and helps to make a positive impact on the minds of your consumer. This can be done with the help of transitions along with initial wireframing. What motions to implement need to be decided in advance, since then you will have a clear understanding of how the final result should be. Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Copying Files to and from Docker Containers Principal Component Analysis with Python OpenCV - Overview Fuzzy Logic | Introduction Classifying data using Support Vector Machines(SVMs) in Python Mounting a Volume Inside Docker Container Getting Started with System Design How to create a REST API using Java Spring Boot Basics of API Testing Using Postman Q-Learning in Python
[ { "code": null, "e": 23837, "s": 23809, "text": "\n15 Sep, 2020" }, { "code": null, "e": 24147, "s": 23837, "text": "A good design is an essential aspect of a website or app. These are important as it helps to build a good user interface. Transitions and animations are great tools and can help bring a much-needed elegance to the web. In the early days, the static design was used, but now the motion design is very popular. " }, { "code": null, "e": 24645, "s": 24147, "text": "One way to introduce these transitions and animations to the web is by ZURB Studios. ZURB has been in the business of making cool web design software for quite a while now, and one of their most common ones is called Motion UI. Motion UI is ZURB’s own Sass library that provides nothing but dynamic transitions and animations for your platform. Both of these effects are specifically incorporated into the Motion UI, and this helps make the animation process incredibly quick and time-efficient. " }, { "code": null, "e": 24888, "s": 24645, "text": "Motion UI is a Sass library for quickly creating flexible UI transitions and animations. It is a stand-alone library that controls the transformation effects included in a variety of Foundation components, including Toggler, Reveal and Orbit." }, { "code": null, "e": 25127, "s": 24888, "text": "You can use npm or bower to install the Motion UI library in your project. Where the package includes a CSS file with a collection of pre-made transitions and animations, along with the Sass source files that allow you to build your own. " }, { "code": null, "e": 25201, "s": 25127, "text": " npm install motion-ui --save-dev\n bower install motion-ui --save-dev\n\n" }, { "code": null, "e": 25378, "s": 25201, "text": "Motion UI provides a set of pre-made effects as a CSS package. This includes transition effects to slide, scale, fade, hinge, and spin, as well as several built-in animations. " }, { "code": null, "e": 25472, "s": 25378, "text": "You can add a path to the Motion UI library in the Compass by using config.rb as given below:" }, { "code": null, "e": 25519, "s": 25472, "text": "add_import_path 'node_modules/motion-ui/src'\n\n" }, { "code": null, "e": 25597, "s": 25519, "text": "You can use the following lines of code to include the path in the gulp-sass:" }, { "code": null, "e": 25702, "s": 25597, "text": "gulp.src('./src/scss/app.scss')\n .pipe(sass({\n includePaths: ['node_modules/motion-ui/src']\n }));\n\n" }, { "code": null, "e": 25793, "s": 25702, "text": "Finally, you can import the Motion UI library in the SASS file using the code given below:" }, { "code": null, "e": 25878, "s": 25793, "text": "@import 'motion-ui'\n@include motion-ui-transitions;\n@include motion-ui-animations;\n\n" }, { "code": null, "e": 26145, "s": 25878, "text": "Just like transitions that you would use in a slide show or video, those here are meant to help the transition process of components that come in and out of your site. The Motion UI package includes a small JavaScript library designed to trigger these transitions. " }, { "code": null, "e": 26329, "s": 26145, "text": " Foundation provides transition effects through the use of transition classes that are created by the Motion UI library which includes more than two dozen built-in transition classes." }, { "code": null, "e": 26433, "s": 26329, "text": "They can be enabled by adding the following code to your Sass file after you have imported the library:" }, { "code": null, "e": 26467, "s": 26433, "text": "@include motion-ui-transitions;\n\n" }, { "code": null, "e": 26543, "s": 26467, "text": "You can set the custom transition classes using Motion UI’s mixin library. " }, { "code": null, "e": 26641, "s": 26543, "text": "For example, mui-fade() use to creates a fade transition by adjusting the opacity of the element." }, { "code": null, "e": 26744, "s": 26641, "text": "@include mui-fade(\n $state: in,\n $from: in,\n $to: out,\n $duration: 0.5s,\n $timing: easeInOut\n);\n\n" }, { "code": null, "e": 27050, "s": 26744, "text": "You can also use the Motion UI transition effects to create CSS animations. The library also allows creating series effects, with animations on multiple elements occurring in a queue. All of these animations are created with the mixin’s mui-animation(), where it is used to create CSS keyframe animations." }, { "code": null, "e": 27315, "s": 27050, "text": "Along with standard, one-time animations, Motion UI also allows you the ability to animate multiple items in a specified series. You can begin your series with the mui-series() and inside this mixin, you can attach animations to classes with the mui-queue() mixin." }, { "code": null, "e": 27467, "s": 27315, "text": "It is essential that you properly apply the Motion UI on your website and on your apps. In a variety of cases this can be achieved as described below: " }, { "code": null, "e": 30310, "s": 27467, "text": "Welcoming users: In some cases, the applications and websites will welcome the users with a pleasant message of greeting. A good message of welcome has a positive impact on the customers. Who can skip the Nokia mobiles logo of two hands meeting? A pleasant welcome screen on the applications and websites improves the user’s experiences. You only need to apply motion when necessary and have a specific intention for the same reason. If possible, this must only be implemented when the loading of apps and website is delayed for a period.Inform about actions: The users need to be aware of and how they will perform on your website. This guidance will enhance the UX and contribute to the improvement of the website and apps. It must also be borne in mind that the motions implemented must complement and add to the user experience of the app and must also help to retain the attention of users and by using elements such as bounce and velocity.Confirm the activities: In a majority of cases, various activities such as deleting mail, sending mail, uninstalling applications, clicking on some links, deleting data, etc. and other such elements need confirmation. It is used in a variety of irreversible activities. In a lot of cases, the confirmation process will be animated to attract more attention to users and to ensure that they do not make any errors in doing so.Add fun elements: There are a lot of apps and websites that introduce fun elements and have become really popular. This makes it easy to navigate the apps and the website, which makes it easier for users to visit again and again. Therefore, the fun elements must be added properly to the website. Various fun elements such as zooming in, zooming out, sliding, etc can be introduced to make the display and content simpler and more enjoyable.Feedback loop: In a majority of cases, users interact with applications and websites. In such situations, the feedback helps to provide a better user experience. Suppose you try to build a response when the user wants to log in to the app or website and enter the wrong password. In this case, the feedback loop turns out to be very useful and helps the users to log in to notify in such cases. It can also be used to view some animations on the websites. These are available in a wide range of applications and can be viewed on the lock screen of the websites.Refresh content: The content of social media websites and applications is updated very frequently. In such cases, the content can quickly be refreshed so that the users can get the best user experience and also get the content when they arrive. In this case, You can either slide the screen down and leave it to update the content on Twitter, Instagram, Facebook, and other such apps. Apart from these, you can also click on the available button to view the new updates." }, { "code": null, "e": 30849, "s": 30310, "text": "Welcoming users: In some cases, the applications and websites will welcome the users with a pleasant message of greeting. A good message of welcome has a positive impact on the customers. Who can skip the Nokia mobiles logo of two hands meeting? A pleasant welcome screen on the applications and websites improves the user’s experiences. You only need to apply motion when necessary and have a specific intention for the same reason. If possible, this must only be implemented when the loading of apps and website is delayed for a period." }, { "code": null, "e": 31257, "s": 30849, "text": "Inform about actions: The users need to be aware of and how they will perform on your website. This guidance will enhance the UX and contribute to the improvement of the website and apps. It must also be borne in mind that the motions implemented must complement and add to the user experience of the app and must also help to retain the attention of users and by using elements such as bounce and velocity." }, { "code": null, "e": 31683, "s": 31257, "text": "Confirm the activities: In a majority of cases, various activities such as deleting mail, sending mail, uninstalling applications, clicking on some links, deleting data, etc. and other such elements need confirmation. It is used in a variety of irreversible activities. In a lot of cases, the confirmation process will be animated to attract more attention to users and to ensure that they do not make any errors in doing so." }, { "code": null, "e": 32125, "s": 31683, "text": "Add fun elements: There are a lot of apps and websites that introduce fun elements and have become really popular. This makes it easy to navigate the apps and the website, which makes it easier for users to visit again and again. Therefore, the fun elements must be added properly to the website. Various fun elements such as zooming in, zooming out, sliding, etc can be introduced to make the display and content simpler and more enjoyable." }, { "code": null, "e": 32687, "s": 32125, "text": "Feedback loop: In a majority of cases, users interact with applications and websites. In such situations, the feedback helps to provide a better user experience. Suppose you try to build a response when the user wants to log in to the app or website and enter the wrong password. In this case, the feedback loop turns out to be very useful and helps the users to log in to notify in such cases. It can also be used to view some animations on the websites. These are available in a wide range of applications and can be viewed on the lock screen of the websites." }, { "code": null, "e": 33158, "s": 32687, "text": "Refresh content: The content of social media websites and applications is updated very frequently. In such cases, the content can quickly be refreshed so that the users can get the best user experience and also get the content when they arrive. In this case, You can either slide the screen down and leave it to update the content on Twitter, Instagram, Facebook, and other such apps. Apart from these, you can also click on the available button to view the new updates." }, { "code": null, "e": 33595, "s": 33158, "text": "Motion UI is quite necessary and must be adopted and implemented on your website. This guarantees that you are able to provide the best user experience and helps to make a positive impact on the minds of your consumer. This can be done with the help of transitions along with initial wireframing. What motions to implement need to be decided in advance, since then you will have a clear understanding of how the final result should be. " }, { "code": null, "e": 33621, "s": 33595, "text": "Advanced Computer Subject" }, { "code": null, "e": 33719, "s": 33621, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33728, "s": 33719, "text": "Comments" }, { "code": null, "e": 33741, "s": 33728, "text": "Old Comments" }, { "code": null, "e": 33785, "s": 33741, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 33826, "s": 33785, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 33844, "s": 33826, "text": "OpenCV - Overview" }, { "code": null, "e": 33871, "s": 33844, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 33934, "s": 33871, "text": "Classifying data using Support Vector Machines(SVMs) in Python" }, { "code": null, "e": 33976, "s": 33934, "text": "Mounting a Volume Inside Docker Container" }, { "code": null, "e": 34011, "s": 33976, "text": "Getting Started with System Design" }, { "code": null, "e": 34059, "s": 34011, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 34095, "s": 34059, "text": "Basics of API Testing Using Postman" } ]
How to take user input using HTML forms?
Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc. Let’s learn about the <input> tag, which helps you to take user input using the type attribute. The attribute is used with the form elements such as text input, checkbox, radio, etc. You can try to run the following code to take user input using HTML Forms: Live Demo <!DOCTYPE html> <html> <body> <head> <title>HTML Forms</title> </head> <p>Add your details:</p> <form> Student Name:<br> <input type="text" name="name"> <br> Student Subject:<br> <input type="text" name="subject"> <br> Rank:<br> <input type="text" name="rank"> </form> </body> </html> Above, you can see the following two attributes: typeIndicates the type of input control and for text input control it will be set to text nameUsed to give a name to the control which is sent to the server to be recognized and get the value.
[ { "code": null, "e": 1276, "s": 1062, "text": "Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc." }, { "code": null, "e": 1459, "s": 1276, "text": "Let’s learn about the <input> tag, which helps you to take user input using the type attribute. The attribute is used with the form elements such as text input, checkbox, radio, etc." }, { "code": null, "e": 1534, "s": 1459, "text": "You can try to run the following code to take user input using HTML Forms:" }, { "code": null, "e": 1544, "s": 1534, "text": "Live Demo" }, { "code": null, "e": 1919, "s": 1544, "text": "<!DOCTYPE html>\n<html>\n <body>\n <head>\n <title>HTML Forms</title>\n </head>\n <p>Add your details:</p>\n <form>\n Student Name:<br> <input type=\"text\" name=\"name\">\n <br>\n Student Subject:<br> <input type=\"text\" name=\"subject\">\n <br>\n Rank:<br> <input type=\"text\" name=\"rank\">\n </form>\n </body>\n</html>" }, { "code": null, "e": 1968, "s": 1919, "text": "Above, you can see the following two attributes:" }, { "code": null, "e": 2058, "s": 1968, "text": "typeIndicates the type of input control and for text input control it will be set to text" }, { "code": null, "e": 2161, "s": 2058, "text": "nameUsed to give a name to the control which is sent to the server to be recognized and get the value." } ]
Refining margins over the years. How have crude processing and refined... | by Ranganath Venkataraman | Towards Data Science
In my last post, we saw that the Gulf Coast is largely responsible for refinery processing in the United States. So, why do refineries process crude into refined products? To recognize profits between products and crude. As always, note that all data used in visualizations below is publicly available from the U.S. Energy Information Administration. A refinery’s gross profit tracks the ‘crack spread’, which is the difference between the price of refined products and the price of crude oil. Let’s define the oft-used 3–2–1 spread as ( (2*price of gasoline) + (1*price of diesel) — (3*price of crude)) / 3 The code below calculates the crack spread and then creates a scatterplot over time, along with a calculated average — see graph after code # Calculate 3-2-1 spread, using Conventional Gas, ULSD, and West Texas Intermediate crude pricesPost2006['3-2-1, WTI-base'] = (2*Post2006['Conv Gas, $/gal']*42 + Post2006['ULSD, $/gal']*42 - (3*Post2006['WTI mo. avg, $/bbl'])) / 3# Plot spread and average over timeplt.figure(figsize=(10,10))plt.scatter(Post2006['Date'],Post2006['3-2-1, WTI-base'], c='b', marker='x', label='3-2-1 spread, $/bbl')y_mean = [np.mean(Post2006['3-2-1, WTI-base'])]*len(Post2006['Date'])plt.plot(Post2006['Date'],y_mean, c='black, marker='x', label='Avg')plt.legend(loc='upper left', fontsize=12)plt.xticks(np.arange(0, 100, step=12), rotation=80, fontsize=12)plt.yticks(fontsize=12)plt.show() What does the chart above tell us? Refining 3 barrels of crude oil to produce and sell 2 barrels of gasoline and 1 barrel of diesel nets profit averaging $17.50 per barrel of crude oil. What is it about crude oil that allows refineries to make fuel? Crude can be thought of as a mixture of light and heavy chemical components — at the extremes, light components end up as LPG that fires up our BBQ and heavy components end up as asphalt in road tar. In the middle between extremes, heavy and light components are blended to make motor fuels such as gasoline, diesel, and jet fuel. The more that the crude oil mixture is made up of light components, the ‘lighter’ the crude is. The lighter the crude, the higher its API gravity. Likewise: the more that the crude oil is composed of heavy components, the lower the API gravity. How has API gravity of crude feeding U.S. refineries changed over the years? Code below was used to produce the following graph # 1st, create two separate scatter plots on two separate axesAPI = pg.Scatter(x=crudesulfurandAPI['Date'], y=crudesulfurandAPI['Crude sulfur, %'], name = 'Sulfur, %')Sulfur = pg.Scatter(x=crudesulfurandAPI['Date'], y=crudesulfurandAPI['API'], # Specify axis yaxis='y2', name = 'API, deg F')# 2nd, define layout with axis titles, figure title, and image dimensions.layout = pg.Layout(height=500, width=900, title='Crude sulfur and API since 1985', # Same x and first y xaxis=dict(title='Date'), yaxis=dict(title='Sulfur, %', color='blue'), # Add a second yaxis to the right of the plot yaxis2=dict(title='API, deg F', color='red', overlaying='y', side='right'), )# Last, attribute layout to figure and add annotationfig = pg.Figure(data=[API, Sulfur], layout=layout)fig.add_annotation( x=200, y=1.45, font=dict( family="Courier New, monospace", size=18, color="black", ), text="29.78 API, 1.48% Sulfur")# Finally, update location of legendfig.update_layout(legend=dict(x=0.15, y=0.9), title=dict(x=0.15, y=0.9)) The red API gravity of crude feeding U.S. refineries has declined from the mid-80s through mid-2008, when it troughed at 29.8. At that point, U.S. refineries start seeing an influx of high API gravity, light crude from the Bakken shale oil fields in North Dakota. You’ll observe the blue trend of sulfur. We’ll focus on this in a separate post, but for now — high sulfur in crude means more sulfur to be removed in an oil refinery in order to minimize the harmful release of toxins. Generally, heavier and sour crudes are cheaper than light and sweet crudes. The 3–2–1 crack spread depends on crude prices and refined product prices. For our purposes, let’s consider the refined products: gasoline, jet fuel, and ultra low sulfur diesel (ULSD). Trending these prices going back to 2006 against the price of crude oil yields the following pair plot. That’s quite an eyeful! Bottom-lines: Gasoline, jet fuel, and ULSD prices all demonstrate a strong linear correlation with crude oil prices. They also linearly correlate with each other i.e. all fuel prices generally trend together. The histograms of gasoline, ULSD, and jet fuel all indicate two peaks — suggesting two commonly observed peaks of occurrence. These are the price points of summer (mid-April through August) and winter (every other month). One note before continuing: WTI, or West Texas Intermediate, is one of two major price markers of crude — the other is Brent. A little more on this, at the end of this article. From everything that we’ve learnt above, could the API of processed crude be predicted by gasoline prices? After all, lighter crude — i.e. higher API — helps make more gasoline. Therefore, wouldn’t higher gas prices lead refiners to process more high-API crude? If we trend data going back to 2006, what do we find? Woah... no correlation there. This suggests that refineries are capable of handling diverse types of crude feed to maintain their target gas, diesel, and jet production. In the next post, let’s further evaluate refinery configurations using data visualizations. Before I leave you, here’s a plot of WTI crude prices vs. Brent crude prices, going back to the mid-80s. Key point for your understanding now: these have historically read close to each other, so I’m currently not preoccupied with which marker to use in analysis. Here’s a point of interest; you’ll notice prices diverging above, as marked, starting in 2011. What’s going on here? As shale crude flooded the market — remember how crude API started trending upwards in the trends above — the U.S. price marker for crude dipped below the international benchmark, Brent. Why didn’t Brent dip as well? Shouldn’t all crude prices fall in response to oversupply? No, because markets other than the U.S. were initially not allowed to access U.S. crude until the exports embargo was repealed in 2014. Here is the link to the full repo. See you in the next post! Any feedback is welcome, as always.
[ { "code": null, "e": 392, "s": 171, "text": "In my last post, we saw that the Gulf Coast is largely responsible for refinery processing in the United States. So, why do refineries process crude into refined products? To recognize profits between products and crude." }, { "code": null, "e": 522, "s": 392, "text": "As always, note that all data used in visualizations below is publicly available from the U.S. Energy Information Administration." }, { "code": null, "e": 779, "s": 522, "text": "A refinery’s gross profit tracks the ‘crack spread’, which is the difference between the price of refined products and the price of crude oil. Let’s define the oft-used 3–2–1 spread as ( (2*price of gasoline) + (1*price of diesel) — (3*price of crude)) / 3" }, { "code": null, "e": 919, "s": 779, "text": "The code below calculates the crack spread and then creates a scatterplot over time, along with a calculated average — see graph after code" }, { "code": null, "e": 1592, "s": 919, "text": "# Calculate 3-2-1 spread, using Conventional Gas, ULSD, and West Texas Intermediate crude pricesPost2006['3-2-1, WTI-base'] = (2*Post2006['Conv Gas, $/gal']*42 + Post2006['ULSD, $/gal']*42 - (3*Post2006['WTI mo. avg, $/bbl'])) / 3# Plot spread and average over timeplt.figure(figsize=(10,10))plt.scatter(Post2006['Date'],Post2006['3-2-1, WTI-base'], c='b', marker='x', label='3-2-1 spread, $/bbl')y_mean = [np.mean(Post2006['3-2-1, WTI-base'])]*len(Post2006['Date'])plt.plot(Post2006['Date'],y_mean, c='black, marker='x', label='Avg')plt.legend(loc='upper left', fontsize=12)plt.xticks(np.arange(0, 100, step=12), rotation=80, fontsize=12)plt.yticks(fontsize=12)plt.show()" }, { "code": null, "e": 1778, "s": 1592, "text": "What does the chart above tell us? Refining 3 barrels of crude oil to produce and sell 2 barrels of gasoline and 1 barrel of diesel nets profit averaging $17.50 per barrel of crude oil." }, { "code": null, "e": 2042, "s": 1778, "text": "What is it about crude oil that allows refineries to make fuel? Crude can be thought of as a mixture of light and heavy chemical components — at the extremes, light components end up as LPG that fires up our BBQ and heavy components end up as asphalt in road tar." }, { "code": null, "e": 2173, "s": 2042, "text": "In the middle between extremes, heavy and light components are blended to make motor fuels such as gasoline, diesel, and jet fuel." }, { "code": null, "e": 2418, "s": 2173, "text": "The more that the crude oil mixture is made up of light components, the ‘lighter’ the crude is. The lighter the crude, the higher its API gravity. Likewise: the more that the crude oil is composed of heavy components, the lower the API gravity." }, { "code": null, "e": 2546, "s": 2418, "text": "How has API gravity of crude feeding U.S. refineries changed over the years? Code below was used to produce the following graph" }, { "code": null, "e": 3839, "s": 2546, "text": "# 1st, create two separate scatter plots on two separate axesAPI = pg.Scatter(x=crudesulfurandAPI['Date'], y=crudesulfurandAPI['Crude sulfur, %'], name = 'Sulfur, %')Sulfur = pg.Scatter(x=crudesulfurandAPI['Date'], y=crudesulfurandAPI['API'], # Specify axis yaxis='y2', name = 'API, deg F')# 2nd, define layout with axis titles, figure title, and image dimensions.layout = pg.Layout(height=500, width=900, title='Crude sulfur and API since 1985', # Same x and first y xaxis=dict(title='Date'), yaxis=dict(title='Sulfur, %', color='blue'), # Add a second yaxis to the right of the plot yaxis2=dict(title='API, deg F', color='red', overlaying='y', side='right'), )# Last, attribute layout to figure and add annotationfig = pg.Figure(data=[API, Sulfur], layout=layout)fig.add_annotation( x=200, y=1.45, font=dict( family=\"Courier New, monospace\", size=18, color=\"black\", ), text=\"29.78 API, 1.48% Sulfur\")# Finally, update location of legendfig.update_layout(legend=dict(x=0.15, y=0.9), title=dict(x=0.15, y=0.9))" }, { "code": null, "e": 4103, "s": 3839, "text": "The red API gravity of crude feeding U.S. refineries has declined from the mid-80s through mid-2008, when it troughed at 29.8. At that point, U.S. refineries start seeing an influx of high API gravity, light crude from the Bakken shale oil fields in North Dakota." }, { "code": null, "e": 4398, "s": 4103, "text": "You’ll observe the blue trend of sulfur. We’ll focus on this in a separate post, but for now — high sulfur in crude means more sulfur to be removed in an oil refinery in order to minimize the harmful release of toxins. Generally, heavier and sour crudes are cheaper than light and sweet crudes." }, { "code": null, "e": 4688, "s": 4398, "text": "The 3–2–1 crack spread depends on crude prices and refined product prices. For our purposes, let’s consider the refined products: gasoline, jet fuel, and ultra low sulfur diesel (ULSD). Trending these prices going back to 2006 against the price of crude oil yields the following pair plot." }, { "code": null, "e": 4726, "s": 4688, "text": "That’s quite an eyeful! Bottom-lines:" }, { "code": null, "e": 4921, "s": 4726, "text": "Gasoline, jet fuel, and ULSD prices all demonstrate a strong linear correlation with crude oil prices. They also linearly correlate with each other i.e. all fuel prices generally trend together." }, { "code": null, "e": 5143, "s": 4921, "text": "The histograms of gasoline, ULSD, and jet fuel all indicate two peaks — suggesting two commonly observed peaks of occurrence. These are the price points of summer (mid-April through August) and winter (every other month)." }, { "code": null, "e": 5320, "s": 5143, "text": "One note before continuing: WTI, or West Texas Intermediate, is one of two major price markers of crude — the other is Brent. A little more on this, at the end of this article." }, { "code": null, "e": 5636, "s": 5320, "text": "From everything that we’ve learnt above, could the API of processed crude be predicted by gasoline prices? After all, lighter crude — i.e. higher API — helps make more gasoline. Therefore, wouldn’t higher gas prices lead refiners to process more high-API crude? If we trend data going back to 2006, what do we find?" }, { "code": null, "e": 5898, "s": 5636, "text": "Woah... no correlation there. This suggests that refineries are capable of handling diverse types of crude feed to maintain their target gas, diesel, and jet production. In the next post, let’s further evaluate refinery configurations using data visualizations." }, { "code": null, "e": 6162, "s": 5898, "text": "Before I leave you, here’s a plot of WTI crude prices vs. Brent crude prices, going back to the mid-80s. Key point for your understanding now: these have historically read close to each other, so I’m currently not preoccupied with which marker to use in analysis." }, { "code": null, "e": 6466, "s": 6162, "text": "Here’s a point of interest; you’ll notice prices diverging above, as marked, starting in 2011. What’s going on here? As shale crude flooded the market — remember how crude API started trending upwards in the trends above — the U.S. price marker for crude dipped below the international benchmark, Brent." }, { "code": null, "e": 6691, "s": 6466, "text": "Why didn’t Brent dip as well? Shouldn’t all crude prices fall in response to oversupply? No, because markets other than the U.S. were initially not allowed to access U.S. crude until the exports embargo was repealed in 2014." }, { "code": null, "e": 6726, "s": 6691, "text": "Here is the link to the full repo." } ]
Read NetCDF Data with Python. Access a slightly confusing, yet... | by Konrad Hafen | Towards Data Science
Network common data form (NetCDF) is commonly used to store multidimensional geographic data. Some examples of these data are temperature, precipitation, and wind speed. Variables stored in NetCDF are often measured multiple times per day over large (continental) areas. With multiple measurements per day, data values accumulate quickly and become unwieldy to work with. When each value is also assigned to a geographic location, data management is further complicated. NetCDF provides a solution for these challenges. This article will get you started with reading data from NetCDF files using Python. NetCDF files can be read with a few different Python modules. The most popular are netCDF4 and gdal. For this article we’ll focus strictly on netCDF4 as it is my personal preference. For information on how to read and plot NetCDF data in Python with xarray and rioxarray check out this article. Installation is simple. I generally recommend using the anaconda Python distribution to eliminate the confusion that can come with dependencies and versioning. To install with anaconda (conda) simply type conda install netCDF4. Alternatively, you can install with pip. To be sure your netCDF4 module is properly installed start an interactive session in the terminal (type python and press ‘Enter’). Then import netCDF4 as nc. Loading a dataset is simple, just pass a NetCDF file path to netCDF4.Dataset(). For this article, I’m using a file containing climate data from Daymet. import netCDF4 as ncfn = '/path/to/file.nc4'ds = nc.Dataset(fn) A NetCDF file has three basic parts: metadata, dimensions and variables. Variables contain both metadata and data. netCDF4 allows us to access the metadata and data associated with a NetCDF file. Printing the dataset, ds, gives us information about the variables contained in the file and their dimensions. print(ds) And the output . . . <class 'netCDF4._netCDF4.Dataset'>root group (NETCDF4_CLASSIC data model, file format HDF5):start_year: 1980source: Daymet Software Version 3.0Version_software: Daymet Software Version 3.0Version_data: Daymet Data Version 3.0Conventions: CF-1.6citation: Please see http://daymet.ornl.gov/ for current Daymet data citation informationreferences: Please see http://daymet.ornl.gov/ for current information on Daymet referencesdimensions(sizes): time(1), nv(2), y(8075), x(7814)variables(dimensions): float32 time_bnds(time,nv), int16 lambert_conformal_conic(), float32 lat(y,x), float32 lon(y,x), float32 prcp(time,y,x), float32 time(time), float32 x(x), float32 y(y)groups: Above you can see information for the file format, data source, data version, citation, dimensions, and variables. The variables we’re interested in are lat, lon, time, and prcp (precipitation). With these variables we can find the precipitation at a given location for a given time. This file only contains one time step (time dimension is 1). Metadata can also be accessed as a Python dictionary, which (in my opinion) is more useful. print(ds.__dict__)OrderedDict([('start_year', 1980), ('source', 'Daymet Software Version 3.0'), ('Version_software', 'Daymet Software Version 3.0'), ('Version_data', 'Daymet Data Version 3.0'), ('Conventions', 'CF-1.6'), ('citation', 'Please see http://daymet.ornl.gov/ for current Daymet data citation information'), ('references', 'Please see http://daymet.ornl.gov/ for current information on Daymet references')]) Then any metadata item can be accessed with its key. For example: print(ds.__dict__['start_year']1980 Access to dimensions is similar to file metadata. Each dimension is stored as a dimension class which contains pertinent information. Metadata for all dimensions can be access by looping through all available dimensions, like so. for dim in ds.dimensions.values(): print(dim)<class 'netCDF4._netCDF4.Dimension'> (unlimited): name = 'time', size = 1<class 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2<class 'netCDF4._netCDF4.Dimension'>: name = 'y', size = 8075<class 'netCDF4._netCDF4.Dimension'>: name = 'x', size = 7814 Individual dimensions are accessed like so: ds.dimensions['x']. Access variable metadata in the same manner as dimensions. The code below shows how this is done. I’ve forgone the output because it is quite lengthy. for var in ds.variables.values(): print(var) The procedure to access information for a specific variable is demonstrated below for prcp (precipitation). print(ds['prcp']) And the output . . . <class 'netCDF4._netCDF4.Variable'>float32 prcp(time, y, x)_FillValue: -9999.0coordinates: lat longrid_mapping: lambert_conformal_conicmissing_value: -9999.0cell_methods: area: mean time: sum within days time: sum over daysunits: mmlong_name: annual total precipitationunlimited dimensions: timecurrent shape = (1, 8075, 7814) The actual precipitation data values are accessed by array indexing, and a numpy array is returned. All variable data is returned as follows: prcp = ds['prcp'][:] Or a subset can be returned. The following code returns a 2D subset. prcp = ds['prcp'][0, 4000:4005, 4000:4005] Here’s the 2D subset result. [[341.0 347.0 336.0 329.0 353.0][336.0 339.0 341.0 332.0 349.0][337.0 340.0 334.0 336.0 348.0][342.0 344.0 332.0 338.0 350.0][350.0 351.0 342.0 346.0 348.0]] NetCDF files are commonly used for geographic time-series data. Initially, they can be a bit intimidating to work with because of the large amounts of data contained, and the different format from the csv and raster files that are most commonly used. NetCDF is a great way to document geographic data because of the built in documentation and metadata. This makes it easy for end users to understand exactly what the data represent with little ambiguity. NetCDF data are accessed as numpy arrays, which present many possibilities for analysis and incorporation to existing tools and workflows.
[ { "code": null, "e": 775, "s": 171, "text": "Network common data form (NetCDF) is commonly used to store multidimensional geographic data. Some examples of these data are temperature, precipitation, and wind speed. Variables stored in NetCDF are often measured multiple times per day over large (continental) areas. With multiple measurements per day, data values accumulate quickly and become unwieldy to work with. When each value is also assigned to a geographic location, data management is further complicated. NetCDF provides a solution for these challenges. This article will get you started with reading data from NetCDF files using Python." }, { "code": null, "e": 958, "s": 775, "text": "NetCDF files can be read with a few different Python modules. The most popular are netCDF4 and gdal. For this article we’ll focus strictly on netCDF4 as it is my personal preference." }, { "code": null, "e": 1070, "s": 958, "text": "For information on how to read and plot NetCDF data in Python with xarray and rioxarray check out this article." }, { "code": null, "e": 1339, "s": 1070, "text": "Installation is simple. I generally recommend using the anaconda Python distribution to eliminate the confusion that can come with dependencies and versioning. To install with anaconda (conda) simply type conda install netCDF4. Alternatively, you can install with pip." }, { "code": null, "e": 1497, "s": 1339, "text": "To be sure your netCDF4 module is properly installed start an interactive session in the terminal (type python and press ‘Enter’). Then import netCDF4 as nc." }, { "code": null, "e": 1649, "s": 1497, "text": "Loading a dataset is simple, just pass a NetCDF file path to netCDF4.Dataset(). For this article, I’m using a file containing climate data from Daymet." }, { "code": null, "e": 1713, "s": 1649, "text": "import netCDF4 as ncfn = '/path/to/file.nc4'ds = nc.Dataset(fn)" }, { "code": null, "e": 1909, "s": 1713, "text": "A NetCDF file has three basic parts: metadata, dimensions and variables. Variables contain both metadata and data. netCDF4 allows us to access the metadata and data associated with a NetCDF file." }, { "code": null, "e": 2020, "s": 1909, "text": "Printing the dataset, ds, gives us information about the variables contained in the file and their dimensions." }, { "code": null, "e": 2030, "s": 2020, "text": "print(ds)" }, { "code": null, "e": 2051, "s": 2030, "text": "And the output . . ." }, { "code": null, "e": 2724, "s": 2051, "text": "<class 'netCDF4._netCDF4.Dataset'>root group (NETCDF4_CLASSIC data model, file format HDF5):start_year: 1980source: Daymet Software Version 3.0Version_software: Daymet Software Version 3.0Version_data: Daymet Data Version 3.0Conventions: CF-1.6citation: Please see http://daymet.ornl.gov/ for current Daymet data citation informationreferences: Please see http://daymet.ornl.gov/ for current information on Daymet referencesdimensions(sizes): time(1), nv(2), y(8075), x(7814)variables(dimensions): float32 time_bnds(time,nv), int16 lambert_conformal_conic(), float32 lat(y,x), float32 lon(y,x), float32 prcp(time,y,x), float32 time(time), float32 x(x), float32 y(y)groups:" }, { "code": null, "e": 3069, "s": 2724, "text": "Above you can see information for the file format, data source, data version, citation, dimensions, and variables. The variables we’re interested in are lat, lon, time, and prcp (precipitation). With these variables we can find the precipitation at a given location for a given time. This file only contains one time step (time dimension is 1)." }, { "code": null, "e": 3161, "s": 3069, "text": "Metadata can also be accessed as a Python dictionary, which (in my opinion) is more useful." }, { "code": null, "e": 3579, "s": 3161, "text": "print(ds.__dict__)OrderedDict([('start_year', 1980), ('source', 'Daymet Software Version 3.0'), ('Version_software', 'Daymet Software Version 3.0'), ('Version_data', 'Daymet Data Version 3.0'), ('Conventions', 'CF-1.6'), ('citation', 'Please see http://daymet.ornl.gov/ for current Daymet data citation information'), ('references', 'Please see http://daymet.ornl.gov/ for current information on Daymet references')])" }, { "code": null, "e": 3645, "s": 3579, "text": "Then any metadata item can be accessed with its key. For example:" }, { "code": null, "e": 3681, "s": 3645, "text": "print(ds.__dict__['start_year']1980" }, { "code": null, "e": 3911, "s": 3681, "text": "Access to dimensions is similar to file metadata. Each dimension is stored as a dimension class which contains pertinent information. Metadata for all dimensions can be access by looping through all available dimensions, like so." }, { "code": null, "e": 4214, "s": 3911, "text": "for dim in ds.dimensions.values(): print(dim)<class 'netCDF4._netCDF4.Dimension'> (unlimited): name = 'time', size = 1<class 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2<class 'netCDF4._netCDF4.Dimension'>: name = 'y', size = 8075<class 'netCDF4._netCDF4.Dimension'>: name = 'x', size = 7814" }, { "code": null, "e": 4278, "s": 4214, "text": "Individual dimensions are accessed like so: ds.dimensions['x']." }, { "code": null, "e": 4429, "s": 4278, "text": "Access variable metadata in the same manner as dimensions. The code below shows how this is done. I’ve forgone the output because it is quite lengthy." }, { "code": null, "e": 4477, "s": 4429, "text": "for var in ds.variables.values(): print(var)" }, { "code": null, "e": 4585, "s": 4477, "text": "The procedure to access information for a specific variable is demonstrated below for prcp (precipitation)." }, { "code": null, "e": 4603, "s": 4585, "text": "print(ds['prcp'])" }, { "code": null, "e": 4624, "s": 4603, "text": "And the output . . ." }, { "code": null, "e": 4951, "s": 4624, "text": "<class 'netCDF4._netCDF4.Variable'>float32 prcp(time, y, x)_FillValue: -9999.0coordinates: lat longrid_mapping: lambert_conformal_conicmissing_value: -9999.0cell_methods: area: mean time: sum within days time: sum over daysunits: mmlong_name: annual total precipitationunlimited dimensions: timecurrent shape = (1, 8075, 7814)" }, { "code": null, "e": 5093, "s": 4951, "text": "The actual precipitation data values are accessed by array indexing, and a numpy array is returned. All variable data is returned as follows:" }, { "code": null, "e": 5114, "s": 5093, "text": "prcp = ds['prcp'][:]" }, { "code": null, "e": 5183, "s": 5114, "text": "Or a subset can be returned. The following code returns a 2D subset." }, { "code": null, "e": 5226, "s": 5183, "text": "prcp = ds['prcp'][0, 4000:4005, 4000:4005]" }, { "code": null, "e": 5255, "s": 5226, "text": "Here’s the 2D subset result." }, { "code": null, "e": 5413, "s": 5255, "text": "[[341.0 347.0 336.0 329.0 353.0][336.0 339.0 341.0 332.0 349.0][337.0 340.0 334.0 336.0 348.0][342.0 344.0 332.0 338.0 350.0][350.0 351.0 342.0 346.0 348.0]]" } ]
Maximize the total profit of all the persons - GeeksforGeeks
26 Aug, 2021 There is a hierarchical structure in an organization. A party is to be organized. No two immediate subordinates can come to the party. A profit is associated with every person. You have to maximize the total profit of all the persons who come to the party.Hierarchical Structure In a hierarchical organization, all employees(except the one at the head) are subordinates of some other employee. Employees only directly report to their immediate superior. This allows for a flexible and efficient structure. For purposes of this problem, this structure may be imagined as a tree, with each employee as its node.Examples: Input: 15 / \ 10 12 / \ / \ 26 4 7 9 Output: The Maximum Profit would be 15+12+26+9 = 62 The Parent 15 chooses sub-ordinate 12, 10 chooses 26 and 12 chooses 9. Input: 12 / | \ 9 25 16 / / \ 13 13 9 Output: 12+25+13+13 = 63 Approach: Given the profit from each employee, we have to find the maximum sum such that no two employees(Nodes) with the same superior(Parent) are invited. This can be achieved if each employee selects the subordinate with the maximum contribution to go. In the program, the hierarchy of the company is implemented in the form of a dictionary, with the key being a unique employee ID, and data being an array of the form [Profit associated with this employ, [List of immediate Sub-ordinates]]. For each Employee, the subordinate with the highest profit associated is added to the total profit. Further, the Employee at the head is always invited. C++ Java Python3 // C++ program for above approach#include <bits/stdc++.h>using namespace std; int getMaxProfit(vector<vector<int> > hier){ // The head has no competition and therefore invited int totSum = hier[0][0]; for (vector<int> i : hier) { vector<int> currentSuperior = i; int selectedSub = 0; // Select the subordinate with maximum // value of each superior for (int j = 1; j < currentSuperior.size(); j++) { int e = currentSuperior[j]; if (hier[e - 1][0] > selectedSub) { selectedSub = hier[e - 1][0]; } } totSum += selectedSub; } return totSum;} // Driver Codeint main(){ // Define the Organization as a 2 - D array // Index : [Profit, List of Employees] /* Same as example 1 given above 1:15 / \ 2:10 3:12 / \ / \ 4:26 5:4 6:7 7:9 */ // Given input vector<vector<int> > organization = { { 15, 2, 3 }, { 10, 4, 5 }, { 12, 6, 7 }, { 26 }, { 4 }, { 7 }, { 9 } }; // Function call int maxProfit = getMaxProfit(organization); cout << maxProfit << "\n"; return 0;} // Java program for above approachclass GFG { static int getMaxProfit(int[][] hier) { // The head has no competition and therefore invited int totSum = hier[0][0]; for (int i = 0; i < hier.length; i++) { int selectedSub = 0; for (int j = 1; j < hier[i].length; j++) { int e = hier[i][j]; if (hier[e - 1][0] > selectedSub) { selectedSub = hier[e - 1][0]; } } totSum += selectedSub; } return totSum; } public static void main(String[] args) { // Define the Organization as a 2 - D array // Index : [Profit, List of Employees] /* Same as example 1 given above 1:15 / \ 2:10 3:12 / \ / \ 4:26 5:4 6:7 7:9 */ // Given input int[][] organization = { { 15, 2, 3 }, { 10, 4, 5 }, { 12, 6, 7 }, { 26 }, { 4 }, { 7 }, { 9 } }; // Function call int maxProfit = getMaxProfit(organization); System.out.println(maxProfit); }} // This code is contributed by rajsanghavi9. # Python program for above approach def getMaxProfit(hier): # The head has no competition and therefore invited totSum = hier[1][0] for i in hier: currentSuperior = hier[i] selectedSub = 0 # select the subordinate with maximum # value of each superior for j in currentSuperior[1]: if(hier[j][0] > selectedSub): selectedSub = hier[j][0] totSum += selectedSub return totSum # driver function def main(): # Define the Organization as a Dictionary # Index : [Profit, List of Employees] # Same as example 1 given above # 1:15 # / \ # 2:10 3:12 # / \ / \ # 4:26 5:4 6:7 7:9 organization = {1: [15, [2, 3]], 2: [10, [4, 5]], 3: [12, [6, 7]], 4: [26, []], 5: [4, []], 6: [7, []], 7: [9, []]} maxProfit = getMaxProfit(organization) print(maxProfit) main() 62 Time Complexity : O(N)Auxiliary Space: O(N) pankajsharmagfg rajsanghavi9 Flipkart Picked Algorithms Competitive Programming Data Structures Flipkart Data Structures Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms How to write a Pseudo Code? Difference between Informed and Uninformed Search in AI Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Competitive Programming - A Complete Guide Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24567, "s": 24539, "text": "\n26 Aug, 2021" }, { "code": null, "e": 25074, "s": 24567, "text": "There is a hierarchical structure in an organization. A party is to be organized. No two immediate subordinates can come to the party. A profit is associated with every person. You have to maximize the total profit of all the persons who come to the party.Hierarchical Structure In a hierarchical organization, all employees(except the one at the head) are subordinates of some other employee. Employees only directly report to their immediate superior. This allows for a flexible and efficient structure. " }, { "code": null, "e": 25189, "s": 25074, "text": "For purposes of this problem, this structure may be imagined as a tree, with each employee as its node.Examples: " }, { "code": null, "e": 25496, "s": 25189, "text": "Input: \n 15\n / \\\n 10 12\n / \\ / \\\n 26 4 7 9\nOutput: The Maximum Profit would be 15+12+26+9 = 62\nThe Parent 15 chooses sub-ordinate 12, 10 chooses 26 and 12 chooses 9.\n\nInput:\n 12\n / | \\\n 9 25 16\n / / \\\n 13 13 9\nOutput: 12+25+13+13 = 63" }, { "code": null, "e": 26147, "s": 25498, "text": "Approach: Given the profit from each employee, we have to find the maximum sum such that no two employees(Nodes) with the same superior(Parent) are invited. This can be achieved if each employee selects the subordinate with the maximum contribution to go. In the program, the hierarchy of the company is implemented in the form of a dictionary, with the key being a unique employee ID, and data being an array of the form [Profit associated with this employ, [List of immediate Sub-ordinates]]. For each Employee, the subordinate with the highest profit associated is added to the total profit. Further, the Employee at the head is always invited. " }, { "code": null, "e": 26151, "s": 26147, "text": "C++" }, { "code": null, "e": 26156, "s": 26151, "text": "Java" }, { "code": null, "e": 26164, "s": 26156, "text": "Python3" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; int getMaxProfit(vector<vector<int> > hier){ // The head has no competition and therefore invited int totSum = hier[0][0]; for (vector<int> i : hier) { vector<int> currentSuperior = i; int selectedSub = 0; // Select the subordinate with maximum // value of each superior for (int j = 1; j < currentSuperior.size(); j++) { int e = currentSuperior[j]; if (hier[e - 1][0] > selectedSub) { selectedSub = hier[e - 1][0]; } } totSum += selectedSub; } return totSum;} // Driver Codeint main(){ // Define the Organization as a 2 - D array // Index : [Profit, List of Employees] /* Same as example 1 given above 1:15 / \\ 2:10 3:12 / \\ / \\ 4:26 5:4 6:7 7:9 */ // Given input vector<vector<int> > organization = { { 15, 2, 3 }, { 10, 4, 5 }, { 12, 6, 7 }, { 26 }, { 4 }, { 7 }, { 9 } }; // Function call int maxProfit = getMaxProfit(organization); cout << maxProfit << \"\\n\"; return 0;}", "e": 27375, "s": 26164, "text": null }, { "code": "// Java program for above approachclass GFG { static int getMaxProfit(int[][] hier) { // The head has no competition and therefore invited int totSum = hier[0][0]; for (int i = 0; i < hier.length; i++) { int selectedSub = 0; for (int j = 1; j < hier[i].length; j++) { int e = hier[i][j]; if (hier[e - 1][0] > selectedSub) { selectedSub = hier[e - 1][0]; } } totSum += selectedSub; } return totSum; } public static void main(String[] args) { // Define the Organization as a 2 - D array // Index : [Profit, List of Employees] /* Same as example 1 given above 1:15 / \\ 2:10 3:12 / \\ / \\ 4:26 5:4 6:7 7:9 */ // Given input int[][] organization = { { 15, 2, 3 }, { 10, 4, 5 }, { 12, 6, 7 }, { 26 }, { 4 }, { 7 }, { 9 } }; // Function call int maxProfit = getMaxProfit(organization); System.out.println(maxProfit); }} // This code is contributed by rajsanghavi9.", "e": 28605, "s": 27375, "text": null }, { "code": "# Python program for above approach def getMaxProfit(hier): # The head has no competition and therefore invited totSum = hier[1][0] for i in hier: currentSuperior = hier[i] selectedSub = 0 # select the subordinate with maximum # value of each superior for j in currentSuperior[1]: if(hier[j][0] > selectedSub): selectedSub = hier[j][0] totSum += selectedSub return totSum # driver function def main(): # Define the Organization as a Dictionary # Index : [Profit, List of Employees] # Same as example 1 given above # 1:15 # / \\ # 2:10 3:12 # / \\ / \\ # 4:26 5:4 6:7 7:9 organization = {1: [15, [2, 3]], 2: [10, [4, 5]], 3: [12, [6, 7]], 4: [26, []], 5: [4, []], 6: [7, []], 7: [9, []]} maxProfit = getMaxProfit(organization) print(maxProfit) main()", "e": 29535, "s": 28605, "text": null }, { "code": null, "e": 29538, "s": 29535, "text": "62" }, { "code": null, "e": 29585, "s": 29540, "text": "Time Complexity : O(N)Auxiliary Space: O(N) " }, { "code": null, "e": 29601, "s": 29585, "text": "pankajsharmagfg" }, { "code": null, "e": 29614, "s": 29601, "text": "rajsanghavi9" }, { "code": null, "e": 29623, "s": 29614, "text": "Flipkart" }, { "code": null, "e": 29630, "s": 29623, "text": "Picked" }, { "code": null, "e": 29641, "s": 29630, "text": "Algorithms" }, { "code": null, "e": 29665, "s": 29641, "text": "Competitive Programming" }, { "code": null, "e": 29681, "s": 29665, "text": "Data Structures" }, { "code": null, "e": 29690, "s": 29681, "text": "Flipkart" }, { "code": null, "e": 29706, "s": 29690, "text": "Data Structures" }, { "code": null, "e": 29717, "s": 29706, "text": "Algorithms" }, { "code": null, "e": 29815, "s": 29717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29824, "s": 29815, "text": "Comments" }, { "code": null, "e": 29837, "s": 29824, "text": "Old Comments" }, { "code": null, "e": 29886, "s": 29837, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 29911, "s": 29886, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 29938, "s": 29911, "text": "Introduction to Algorithms" }, { "code": null, "e": 29966, "s": 29938, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 30022, "s": 29966, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 30065, "s": 30022, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 30106, "s": 30065, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30133, "s": 30106, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 30176, "s": 30133, "text": "Competitive Programming - A Complete Guide" } ]
File Searching using C#
To search files from the list of files in a directory, try to run the following code − using System; using System.IO; namespace Demo { class Program { static void Main(string[] args) { //creating a DirectoryInfo object DirectoryInfo mydir = new DirectoryInfo(@"d:\amit"); // getting the files in the directory, their names and size FileInfo [] f = mydir.GetFiles(); foreach (FileInfo file in f) { Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length); } Console.ReadKey(); } } } Above, we have firstly added the directory wherein we want to find the files − DirectoryInfo mydir = new DirectoryInfo(@"d:\amit"); Then read the file − FileInfo [] f = mydir.GetFiles(); foreach (FileInfo file in f) { C onsole.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length); } The following is the output − FileName: Info.txt: Size: 2kb File Name: New.html: Size: 10kb
[ { "code": null, "e": 1149, "s": 1062, "text": "To search files from the list of files in a directory, try to run the following code −" }, { "code": null, "e": 1653, "s": 1149, "text": "using System;\nusing System.IO;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n //creating a DirectoryInfo object\n DirectoryInfo mydir = new DirectoryInfo(@\"d:\\amit\");\n\n // getting the files in the directory, their names and size\n FileInfo [] f = mydir.GetFiles();\n\n foreach (FileInfo file in f) {\n Console.WriteLine(\"File Name: {0} Size: {1}\", file.Name, file.Length);\n }\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 1732, "s": 1653, "text": "Above, we have firstly added the directory wherein we want to find the files −" }, { "code": null, "e": 1785, "s": 1732, "text": "DirectoryInfo mydir = new DirectoryInfo(@\"d:\\amit\");" }, { "code": null, "e": 1806, "s": 1785, "text": "Then read the file −" }, { "code": null, "e": 1948, "s": 1806, "text": "FileInfo [] f = mydir.GetFiles();\n\nforeach (FileInfo file in f) {\nC onsole.WriteLine(\"File Name: {0} Size: {1}\", file.Name, file.Length);\n}" }, { "code": null, "e": 1978, "s": 1948, "text": "The following is the output −" }, { "code": null, "e": 2040, "s": 1978, "text": "FileName: Info.txt: Size: 2kb\nFile Name: New.html: Size: 10kb" } ]
Breaking the Enigma Code in Python with MCMC (Marvel themed) | by Jack J | Towards Data Science
Knowledge is Power. This rule can be applied to almost any domain, yet it is arguably never more relevant than during times of war. The ability to predict your enemies next move is equally difficult as it is rewarding, a task which is made considerably easier if one could read their plans ahead of time. This is something all sides knew during World War II, and Nazi Germany put great effort into ensuring the privacy and security of their communication. A primary tool for this was the “Engima”, a machine which allowed their correspondents to be safely encrypted and decrypted through a simple process of letter switching (all ‘a’s become ‘z’s, for instance). Although the encryption process was simple (by today’s standards, at least), it was a tremendous task for the Allies to find the correct keys to decrypt the intercepted messages. This was compounded by the fact that these keys would switch daily, making all efforts up to that point futile. Of course, as you may know, the challenge was met by Alan Turing and his team at Bletchley Park which led to a breakthrough in computing and became a foundation for “Artificial Intelligence”. However, this article is not about Turing or his methods (albeit they share some qualities). Nor will this be about decrypting Nazi communications. Instead, we will take a geekier tact and look at a (fictional) cryptic message intercepted by agents of S.H.I.E.L.D from the genocidal warlord of Titan, Thanos (the central villain that concluded the initial 22-film Marvel cinematic universe). You will play the part of a S.H.I.E.L.D analyst, who only through the use of Python and his knowledge of Markov Chain Monte Carlo (MCMC) will attempt to decrypt the code and save the Universe. If you are interested in the actual Enigma machine and how it was decrypted, I recommend starting with this Numberphile video here: https://www.youtube.com/watch?v=G2_Q9FoD-oQ "huvw !kzcq7nv3 qv3!hqv ,evwrhqv3rvq9qwi3qvhuv2cq,3vmk,7v,7zvbikb!kvhuvzqe3!7ufv3 qvmk,7nv,evuriv57r1nv!ev3rvieqv3 qvwreh!wvq73!3!qev57r17v,ev3 qv!7b!7!3uve3r7qev3rv1!mqv ,kbvrbv3 qvi7!;qceqvri3vrbvq9!e3q7wqverv3 ,3v3 qvr3 qcv ,kbvh,uv3 c!;qfvricv2cq,3qe3vw ,kkq72qv ,evtqq7vb!7z!72v3 qve3r7qev!7v3 !ev;,e3vi7!;qceqnvti3v7r1v3 quv,cqv1!3 !7vricv2c,emfv3 qvem,wqve3r7qnv57r1ev,kerv,ev3 qv3qeeqc,w3nvcqe!zqevr7v,e2,czfv,b3qcvkr5!evb,!kicqvr7vq,c3 nv3 rcv ,ev3,5q7v!3v,7zvmi3v!3v!7vrz!7ev;,ik3fv3 qvmr1qcve3r7qv!evr7vhrc,2fv!v ,;qvrczqcqzvcr7,7v3 qv,wwieqcv3rvcq3c!q;qv!3vbrcvhqnv!7vcq3ic7v!ve ,kkvzqe3cruv9,7z,cfv3 qvh!7zve3r7qv!evr7vq,c3 nv!vmi3v!3v!7v3 qve3,bbv!v2,;qv3rvkr5!nvti3v7r1v!v ,;qv q,czv3 ,3v!3v!evmr1qc!72v,vwutrc2v57r17v,ev3 qv;!e!r7fv3 qvcq,k!3uve3r7qv!evr7v3 qvwqkqe3!,kv q,zv57r17v,ev57r1 qcqfv!3v!ev1!3 v3,7qkqqcv3!;,7v!7v !evm,3 q3!wvwrkkqw3!r7nv2!b3qzv3rv !hvtuv3 qv,e2,cz!,7ev,b3qcv3 qvz,c5vqk;qevb,!kicqv!7v,wxi!c!72vbrcv3 qheqk;qefv3 qv3!hqve3r7qv!ev,kervr7vq,c3 nv1!3 v,v2crimvrbvercwqcqcenvwiccq73kuv2i,czqzvtuv3 q!cvkq,zqcnv3 qv,7w!q73vr7qfv3 qvk,e3ve3r7qnv3 qverikve3r7qnv ,evuq3v3rvtqvbri7znvti3v!v ,;qvmi3vhuvb,;ric!3qvz,i2 3qcnv2,hrc,nvr7v3rv!3ev3c,!knv,7zve qv ,ev7r3vz!e,mmr!73qzvhqvuq3fvr7wqv,ve3r7qv!evwrkkqw3qzv!v1!kkvtqv,tkqv3rv ,c7qeev!3evmr1qcvie!72v,v2,i73kq3v!v ,;qvrczqcqzv3 qvz1,c;qevr7v7!z,;qkk!cfv3 qv3!hqvbrcvwreh!wvrczqcv!ev7q,cnv,7zv1 q7v!vwrkkqw3v,kkv3 qve3r7qev!v1!kkv rkzvi7!;qceqv!7vhuv ,7zefv i2ev,7zv5!eeqenvv3 ,7re" The above is the cryptic message we have intercepted. The characters are alphanumerical, from the English language and include some scattered punctuation. We also note common characters such as 7, 3 and v, but there is no hope in solving this by hand. Luckily, Graduate school taught us about MCMCs and we feel it might be a good fit for the problem. There are 7 steps to the MCMC algorithm, which are as followed: Step 1 — Pick a random solution. Step 2 — Apply the solution to the problem. Step 3 — Evaluate how well that worked. Step 4 — Make 1 adjustment to the solution. Step 5 — Apply the new solution to the problem. Step 6 — Re-score our solution. Step 7 (a) — If the new solution has a better score, it becomes the current solution and we repeat from Step 4. Otherwise: Step 7 (b) -Calculate the ratio between the new solution and the previous, then pick a random number between 0 and 1. If the ratio exceeds that number, accept the solution. If it does not, reject the solution. Either way, we repeat from Step 4. Note, Step 7 (b) allows for a greater percentage of the potential solution space to be explored by sometimes allowing “worse” solutions that may eventually provide a better answer. The probability of accepting these “worse” solutions is dependent on how much worse they are. This is often referred to as the “local minima problem”. However, there’s one problem: how do we measure how well the solution worked? We need an empirical score that can tell us which of our two solutions is more likely to be the real decrypted message. To do this, we look at neighbouring letters. For instance, in the crypted message one of the first strings is “!kzcq7nv3”. We could calculate how likely in the English language it is for ‘k’ to follow ‘!’, or ‘z’ to follow ‘k’, and so on. Then if we were to randomly change a letter, we could see if the new letter pairings are more or less likely to be from English words. To get these pair probabilities, we will need a huge corpus of English words — preferably one that includes Marvel words such as Avengers, Thanos or Hulk. To do this, we can scrape the entire Marvel Wiki (see GitHub) and count how often each letter will follow another. From this, we find the letter pairing ‘ba’ 41,943 times whilst ‘bn’ only appears 141 times (“subnet” & “Kly’bn”, if you were wondering). We can then convert these counts to percentages. As these percentages tend to be very small, it makes sense to take their logs as to somewhat normalise their values. This will turn a value such as 0.0001% into -4. Now we have a dictionary of every letter pairing and their respective log-likelihoods we can evaluate any attempt at decrypting the message by simply adding all the log-likelihoods of each letter pairing together. For instance, if we evaluated the string ‘hello’ the log-likelihood would be -8.6, whilst the string ‘z9kk3’ would have -32.6. This is due to the fact that in the Marvel Wiki (or any English text), ‘he’ is far more common than ‘z9’, and so on. Given we now have a function to evaluate any potential solution, we can implement the MCMC method to attempt to decrypt the message, the code of which is above. We start with Step 1 by randomly choosing a solution and evaluating how well this scores. Applying the first solution renders the following “decrypted” message: “i;1vd5awx47;.vx;.d x;vnq;1c x;.c;x:x1!.x; i;8wxn.;h5n4;n4a;t!5td5; i;” This has a log-likelihood of -11,396. We then make one change to the solution by switching a letter pairing, re-score the model and determine whether this has made the solution more or less likely. Rinse and repeat. By the 1000th iteration the score has improved dramatically to -4,792 and the decrypted message now reads: “fyalpimoc nhasp asif aprtalef asea j lus afyagc rsavmrnarnoabumbimafya”. It’s still far from readable, but the spaces look natural and the numbers/ improper punctuation have vanished. By the 3,000th iteration the message starts to look almost English, with a score of -3,891: “by gpildren, spe sibe pat gobe so exeguse by hreas clan and mulmil by” On the 7,000th attempt, we can read the opening line of the message: “my children. the time has come to execute my great plan and fulfil my” It takes until the 24,000 iteration for the full stop above to be correctly switched with a comma, and the score to converge on its global optimal at -3,451. The final solution is as followed ( WARNING — partial spoilers for a few Marvel films!): My children, the time has come to execute my great plan and fulfil my destiny. The plan, as you know, is to use the cosmic entities known as the infinity stones to wipe half of the universe out of existence so that the other half may thrive. Our greatest challenge has been finding the stones in this vast universe, but now they are within our grasp. The space stone, knows also as the Tesseract, resides on Asgard. after Loki's failure on earth, Thor has taken it and put it in Odin's vault. The power stone is on Morag. I have ordered Ronan the accuser to retrieve it for me, in return I shall destroy Xandar. The mind stone is on Earth, I put it in the staff I gave to Loki, but now I have heard that it is powering a cyborg known as the Vision. The reality stone is on the celestial head known as Knowhere. It is with Taneleer Tivan in his pathetic collection, gifted to him by the Asgardians after the dark elves failure in acquiring it for themselves. The time stone is also on earth, with a group of sorcerers, currently guarded by their leader, the Ancient One. The last stone, the soul stone, has yet to be found, but I have put my favourite daughter, Gamora, on to its trail, and she has not disappointed me yet. Once a stone is collected I will be able to harness its power using a gauntlet I have ordered the Dwarves to make for me on Nidavellir. The time for cosmic order is near, and when I collect all the stones I will hold Universe in my hands. Hugs and kisses, Thanos (With thanks to the ultra Marvel geek Bob Gard, for writing this for me.) You quickly print off the message and whiz it over to your boss. Within hours the Avengers have assembled and are drawing out plans to protect the stones and defeat Thanos. You are swiftly promoted to Senior Data Scientist and given a healthy raise. But, as per the Marvel comics, there exists infinite universes with infinite possibilities. In all of these, were you successful in decrypting the message and defeating Thanos? To test this hypothesis, we can re-run the MCMC algorithm 100 times and see how many times it converges to the correct solution. As we can see from the above, it is not always successful at reaching the global maximum. In fact, we can look at the distributions of the final log-likelihood to see how many of these 100 times we were close to the optimal. From here, we find that in exactly 50% of the 100 Universes we would have correctly decrypted the message and saved Earth. But what about the other 50 times? What message would they have seen? The table below gives you an idea of what solution you would have presented to your boss, Nick Fury, depending on which score the algorithm converged on. However, it is likely that with enough iterations most of these would have eventually found their way to the right answer. The exception being the last one, which has fallen for a trap that is nearly impossible to recover from. The common letters have been almost all replaced by numbers. Given that numbers most likely follow other numbers, any attempt at replacing a single character with a letter would be met with a disastrous decrease in log-likelihood that would almost never be accepted. Take the word “children”, for instance. In the lowest scoring attempt, it was decrypted as: “.46!?327,”. If the algorithm had switched the “2” for the correct character “r”, it would have not improved the score given “32” and “27” will have occurred more often than “3r” and “r7” in the Marvel wiki. A simple solution for this is to repeat steps 1–3 (choosing completely new random solutions and evaluating them) a handful of times at the start of the algorithm, then continue with the highest performing of these. By including this, and by increasing the iterations to 100,000 we were able to converge close to the solution (1 or 2 incorrect characters) 100% of the time. This saves not only our Universe, but all the multi-verses that have found themselves in the same predicament. GitHub: https://github.com/JackWillz/Projects/tree/master/MCMC%20-%20Enigma%20Thanos You got to the end of the article! My name is Jack J and I’m a professional Data Scientist applying AI to competitive gaming & esports. I’m the founder of iTero.GG and jung.gg. You can follow me on Twitter, join the iTero Discord or drop me an e-mail at [email protected]. See you at the next one. Originally published at https://itero.gg/blogs/.
[ { "code": null, "e": 477, "s": 172, "text": "Knowledge is Power. This rule can be applied to almost any domain, yet it is arguably never more relevant than during times of war. The ability to predict your enemies next move is equally difficult as it is rewarding, a task which is made considerably easier if one could read their plans ahead of time." }, { "code": null, "e": 835, "s": 477, "text": "This is something all sides knew during World War II, and Nazi Germany put great effort into ensuring the privacy and security of their communication. A primary tool for this was the “Engima”, a machine which allowed their correspondents to be safely encrypted and decrypted through a simple process of letter switching (all ‘a’s become ‘z’s, for instance)." }, { "code": null, "e": 1318, "s": 835, "text": "Although the encryption process was simple (by today’s standards, at least), it was a tremendous task for the Allies to find the correct keys to decrypt the intercepted messages. This was compounded by the fact that these keys would switch daily, making all efforts up to that point futile. Of course, as you may know, the challenge was met by Alan Turing and his team at Bletchley Park which led to a breakthrough in computing and became a foundation for “Artificial Intelligence”." }, { "code": null, "e": 1903, "s": 1318, "text": "However, this article is not about Turing or his methods (albeit they share some qualities). Nor will this be about decrypting Nazi communications. Instead, we will take a geekier tact and look at a (fictional) cryptic message intercepted by agents of S.H.I.E.L.D from the genocidal warlord of Titan, Thanos (the central villain that concluded the initial 22-film Marvel cinematic universe). You will play the part of a S.H.I.E.L.D analyst, who only through the use of Python and his knowledge of Markov Chain Monte Carlo (MCMC) will attempt to decrypt the code and save the Universe." }, { "code": null, "e": 2079, "s": 1903, "text": "If you are interested in the actual Enigma machine and how it was decrypted, I recommend starting with this Numberphile video here: https://www.youtube.com/watch?v=G2_Q9FoD-oQ" }, { "code": null, "e": 3548, "s": 2079, "text": "\"huvw !kzcq7nv3 qv3!hqv ,evwrhqv3rvq9qwi3qvhuv2cq,3vmk,7v,7zvbikb!kvhuvzqe3!7ufv3 qvmk,7nv,evuriv57r1nv!ev3rvieqv3 qvwreh!wvq73!3!qev57r17v,ev3 qv!7b!7!3uve3r7qev3rv1!mqv ,kbvrbv3 qvi7!;qceqvri3vrbvq9!e3q7wqverv3 ,3v3 qvr3 qcv ,kbvh,uv3 c!;qfvricv2cq,3qe3vw ,kkq72qv ,evtqq7vb!7z!72v3 qve3r7qev!7v3 !ev;,e3vi7!;qceqnvti3v7r1v3 quv,cqv1!3 !7vricv2c,emfv3 qvem,wqve3r7qnv57r1ev,kerv,ev3 qv3qeeqc,w3nvcqe!zqevr7v,e2,czfv,b3qcvkr5!evb,!kicqvr7vq,c3 nv3 rcv ,ev3,5q7v!3v,7zvmi3v!3v!7vrz!7ev;,ik3fv3 qvmr1qcve3r7qv!evr7vhrc,2fv!v ,;qvrczqcqzvcr7,7v3 qv,wwieqcv3rvcq3c!q;qv!3vbrcvhqnv!7vcq3ic7v!ve ,kkvzqe3cruv9,7z,cfv3 qvh!7zve3r7qv!evr7vq,c3 nv!vmi3v!3v!7v3 qve3,bbv!v2,;qv3rvkr5!nvti3v7r1v!v ,;qv q,czv3 ,3v!3v!evmr1qc!72v,vwutrc2v57r17v,ev3 qv;!e!r7fv3 qvcq,k!3uve3r7qv!evr7v3 qvwqkqe3!,kv q,zv57r17v,ev57r1 qcqfv!3v!ev1!3 v3,7qkqqcv3!;,7v!7v !evm,3 q3!wvwrkkqw3!r7nv2!b3qzv3rv !hvtuv3 qv,e2,cz!,7ev,b3qcv3 qvz,c5vqk;qevb,!kicqv!7v,wxi!c!72vbrcv3 qheqk;qefv3 qv3!hqve3r7qv!ev,kervr7vq,c3 nv1!3 v,v2crimvrbvercwqcqcenvwiccq73kuv2i,czqzvtuv3 q!cvkq,zqcnv3 qv,7w!q73vr7qfv3 qvk,e3ve3r7qnv3 qverikve3r7qnv ,evuq3v3rvtqvbri7znvti3v!v ,;qvmi3vhuvb,;ric!3qvz,i2 3qcnv2,hrc,nvr7v3rv!3ev3c,!knv,7zve qv ,ev7r3vz!e,mmr!73qzvhqvuq3fvr7wqv,ve3r7qv!evwrkkqw3qzv!v1!kkvtqv,tkqv3rv ,c7qeev!3evmr1qcvie!72v,v2,i73kq3v!v ,;qvrczqcqzv3 qvz1,c;qevr7v7!z,;qkk!cfv3 qv3!hqvbrcvwreh!wvrczqcv!ev7q,cnv,7zv1 q7v!vwrkkqw3v,kkv3 qve3r7qev!v1!kkv rkzvi7!;qceqv!7vhuv ,7zefv i2ev,7zv5!eeqenvv3 ,7re\"" }, { "code": null, "e": 3963, "s": 3548, "text": "The above is the cryptic message we have intercepted. The characters are alphanumerical, from the English language and include some scattered punctuation. We also note common characters such as 7, 3 and v, but there is no hope in solving this by hand. Luckily, Graduate school taught us about MCMCs and we feel it might be a good fit for the problem. There are 7 steps to the MCMC algorithm, which are as followed:" }, { "code": null, "e": 3996, "s": 3963, "text": "Step 1 — Pick a random solution." }, { "code": null, "e": 4040, "s": 3996, "text": "Step 2 — Apply the solution to the problem." }, { "code": null, "e": 4080, "s": 4040, "text": "Step 3 — Evaluate how well that worked." }, { "code": null, "e": 4124, "s": 4080, "text": "Step 4 — Make 1 adjustment to the solution." }, { "code": null, "e": 4172, "s": 4124, "text": "Step 5 — Apply the new solution to the problem." }, { "code": null, "e": 4204, "s": 4172, "text": "Step 6 — Re-score our solution." }, { "code": null, "e": 4327, "s": 4204, "text": "Step 7 (a) — If the new solution has a better score, it becomes the current solution and we repeat from Step 4. Otherwise:" }, { "code": null, "e": 4572, "s": 4327, "text": "Step 7 (b) -Calculate the ratio between the new solution and the previous, then pick a random number between 0 and 1. If the ratio exceeds that number, accept the solution. If it does not, reject the solution. Either way, we repeat from Step 4." }, { "code": null, "e": 4904, "s": 4572, "text": "Note, Step 7 (b) allows for a greater percentage of the potential solution space to be explored by sometimes allowing “worse” solutions that may eventually provide a better answer. The probability of accepting these “worse” solutions is dependent on how much worse they are. This is often referred to as the “local minima problem”." }, { "code": null, "e": 5102, "s": 4904, "text": "However, there’s one problem: how do we measure how well the solution worked? We need an empirical score that can tell us which of our two solutions is more likely to be the real decrypted message." }, { "code": null, "e": 5746, "s": 5102, "text": "To do this, we look at neighbouring letters. For instance, in the crypted message one of the first strings is “!kzcq7nv3”. We could calculate how likely in the English language it is for ‘k’ to follow ‘!’, or ‘z’ to follow ‘k’, and so on. Then if we were to randomly change a letter, we could see if the new letter pairings are more or less likely to be from English words. To get these pair probabilities, we will need a huge corpus of English words — preferably one that includes Marvel words such as Avengers, Thanos or Hulk. To do this, we can scrape the entire Marvel Wiki (see GitHub) and count how often each letter will follow another." }, { "code": null, "e": 6555, "s": 5746, "text": "From this, we find the letter pairing ‘ba’ 41,943 times whilst ‘bn’ only appears 141 times (“subnet” & “Kly’bn”, if you were wondering). We can then convert these counts to percentages. As these percentages tend to be very small, it makes sense to take their logs as to somewhat normalise their values. This will turn a value such as 0.0001% into -4. Now we have a dictionary of every letter pairing and their respective log-likelihoods we can evaluate any attempt at decrypting the message by simply adding all the log-likelihoods of each letter pairing together. For instance, if we evaluated the string ‘hello’ the log-likelihood would be -8.6, whilst the string ‘z9kk3’ would have -32.6. This is due to the fact that in the Marvel Wiki (or any English text), ‘he’ is far more common than ‘z9’, and so on." }, { "code": null, "e": 6716, "s": 6555, "text": "Given we now have a function to evaluate any potential solution, we can implement the MCMC method to attempt to decrypt the message, the code of which is above." }, { "code": null, "e": 6877, "s": 6716, "text": "We start with Step 1 by randomly choosing a solution and evaluating how well this scores. Applying the first solution renders the following “decrypted” message:" }, { "code": null, "e": 6949, "s": 6877, "text": "“i;1vd5awx47;.vx;.d x;vnq;1c x;.c;x:x1!.x; i;8wxn.;h5n4;n4a;t!5td5; i;”" }, { "code": null, "e": 7272, "s": 6949, "text": "This has a log-likelihood of -11,396. We then make one change to the solution by switching a letter pairing, re-score the model and determine whether this has made the solution more or less likely. Rinse and repeat. By the 1000th iteration the score has improved dramatically to -4,792 and the decrypted message now reads:" }, { "code": null, "e": 7346, "s": 7272, "text": "“fyalpimoc nhasp asif aprtalef asea j lus afyagc rsavmrnarnoabumbimafya”." }, { "code": null, "e": 7457, "s": 7346, "text": "It’s still far from readable, but the spaces look natural and the numbers/ improper punctuation have vanished." }, { "code": null, "e": 7549, "s": 7457, "text": "By the 3,000th iteration the message starts to look almost English, with a score of -3,891:" }, { "code": null, "e": 7621, "s": 7549, "text": "“by gpildren, spe sibe pat gobe so exeguse by hreas clan and mulmil by”" }, { "code": null, "e": 7690, "s": 7621, "text": "On the 7,000th attempt, we can read the opening line of the message:" }, { "code": null, "e": 7762, "s": 7690, "text": "“my children. the time has come to execute my great plan and fulfil my”" }, { "code": null, "e": 8009, "s": 7762, "text": "It takes until the 24,000 iteration for the full stop above to be correctly switched with a comma, and the score to converge on its global optimal at -3,451. The final solution is as followed ( WARNING — partial spoilers for a few Marvel films!):" }, { "code": null, "e": 9495, "s": 8009, "text": "My children, the time has come to execute my great plan and fulfil my destiny. The plan, as you know, is to use the cosmic entities known as the infinity stones to wipe half of the universe out of existence so that the other half may thrive. Our greatest challenge has been finding the stones in this vast universe, but now they are within our grasp. The space stone, knows also as the Tesseract, resides on Asgard. after Loki's failure on earth, Thor has taken it and put it in Odin's vault. The power stone is on Morag. I have ordered Ronan the accuser to retrieve it for me, in return I shall destroy Xandar. The mind stone is on Earth, I put it in the staff I gave to Loki, but now I have heard that it is powering a cyborg known as the Vision. The reality stone is on the celestial head known as Knowhere. It is with Taneleer Tivan in his pathetic collection, gifted to him by the Asgardians after the dark elves failure in acquiring it for themselves. The time stone is also on earth, with a group of sorcerers, currently guarded by their leader, the Ancient One. The last stone, the soul stone, has yet to be found, but I have put my favourite daughter, Gamora, on to its trail, and she has not disappointed me yet. Once a stone is collected I will be able to harness its power using a gauntlet I have ordered the Dwarves to make for me on Nidavellir. The time for cosmic order is near, and when I collect all the stones I will hold Universe in my hands. Hugs and kisses, Thanos" }, { "code": null, "e": 9569, "s": 9495, "text": "(With thanks to the ultra Marvel geek Bob Gard, for writing this for me.)" }, { "code": null, "e": 9819, "s": 9569, "text": "You quickly print off the message and whiz it over to your boss. Within hours the Avengers have assembled and are drawing out plans to protect the stones and defeat Thanos. You are swiftly promoted to Senior Data Scientist and given a healthy raise." }, { "code": null, "e": 10125, "s": 9819, "text": "But, as per the Marvel comics, there exists infinite universes with infinite possibilities. In all of these, were you successful in decrypting the message and defeating Thanos? To test this hypothesis, we can re-run the MCMC algorithm 100 times and see how many times it converges to the correct solution." }, { "code": null, "e": 10350, "s": 10125, "text": "As we can see from the above, it is not always successful at reaching the global maximum. In fact, we can look at the distributions of the final log-likelihood to see how many of these 100 times we were close to the optimal." }, { "code": null, "e": 10697, "s": 10350, "text": "From here, we find that in exactly 50% of the 100 Universes we would have correctly decrypted the message and saved Earth. But what about the other 50 times? What message would they have seen? The table below gives you an idea of what solution you would have presented to your boss, Nick Fury, depending on which score the algorithm converged on." }, { "code": null, "e": 10820, "s": 10697, "text": "However, it is likely that with enough iterations most of these would have eventually found their way to the right answer." }, { "code": null, "e": 11192, "s": 10820, "text": "The exception being the last one, which has fallen for a trap that is nearly impossible to recover from. The common letters have been almost all replaced by numbers. Given that numbers most likely follow other numbers, any attempt at replacing a single character with a letter would be met with a disastrous decrease in log-likelihood that would almost never be accepted." }, { "code": null, "e": 11492, "s": 11192, "text": "Take the word “children”, for instance. In the lowest scoring attempt, it was decrypted as: “.46!?327,”. If the algorithm had switched the “2” for the correct character “r”, it would have not improved the score given “32” and “27” will have occurred more often than “3r” and “r7” in the Marvel wiki." }, { "code": null, "e": 11976, "s": 11492, "text": "A simple solution for this is to repeat steps 1–3 (choosing completely new random solutions and evaluating them) a handful of times at the start of the algorithm, then continue with the highest performing of these. By including this, and by increasing the iterations to 100,000 we were able to converge close to the solution (1 or 2 incorrect characters) 100% of the time. This saves not only our Universe, but all the multi-verses that have found themselves in the same predicament." }, { "code": null, "e": 12061, "s": 11976, "text": "GitHub: https://github.com/JackWillz/Projects/tree/master/MCMC%20-%20Enigma%20Thanos" }, { "code": null, "e": 12355, "s": 12061, "text": "You got to the end of the article! My name is Jack J and I’m a professional Data Scientist applying AI to competitive gaming & esports. I’m the founder of iTero.GG and jung.gg. You can follow me on Twitter, join the iTero Discord or drop me an e-mail at [email protected]. See you at the next one." } ]
Golang Program to count the set bits in an integer.
For example, 101, 11, 11011 and 1001001 set bits count 2, 2, 4 and 3 respectively. Approach to solve this problem Step 1 − Convert number into binary representation. Step 2 − Count the number of 1s; return count. Live Demo package main import ( "fmt" "strconv" ) func NumOfSetBits(n int) int{ count := 0 for n !=0{ count += n &1 n >>= 1 } return count } func main(){ n := 20 fmt.Printf("Binary representation of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2)) fmt.Printf("The total number of set bits in %d is %d.\n", n, NumOfSetBits(n)) } Binary representation of 20 is: 10100. The total number of set bits in 20 is 2.
[ { "code": null, "e": 1145, "s": 1062, "text": "For example, 101, 11, 11011 and 1001001 set bits count 2, 2, 4 and 3 respectively." }, { "code": null, "e": 1176, "s": 1145, "text": "Approach to solve this problem" }, { "code": null, "e": 1228, "s": 1176, "text": "Step 1 − Convert number into binary representation." }, { "code": null, "e": 1275, "s": 1228, "text": "Step 2 − Count the number of 1s; return count." }, { "code": null, "e": 1286, "s": 1275, "text": " Live Demo" }, { "code": null, "e": 1647, "s": 1286, "text": "package main\nimport (\n \"fmt\"\n \"strconv\"\n)\nfunc NumOfSetBits(n int) int{\n count := 0\n for n !=0{\n count += n &1\n n >>= 1\n }\n return count\n}\nfunc main(){\n n := 20\n fmt.Printf(\"Binary representation of %d is: %s.\\n\", n,\n strconv.FormatInt(int64(n), 2))\n fmt.Printf(\"The total number of set bits in %d is %d.\\n\", n, NumOfSetBits(n))\n}" }, { "code": null, "e": 1727, "s": 1647, "text": "Binary representation of 20 is: 10100.\nThe total number of set bits in 20 is 2." } ]
HTML <meta> content Attribute
The content attribute of the <meta> element is used to set the meta information in an HTML document. This can be the information for the description or the keywords, for name attribute. Following is the syntax: <meta content="text"> Above, the text is the meta information. Let us now see an example to implement the content attribute of the <meta> element: Live Demo <!DOCTYPE html> <html> <head> <meta name="description" content="Learn for free"> </head> <body> <h2>Tutorials</h2> <p>Programming tutorials for free:</p> <ol> <li>Java</li> <li>C++</li> <li>C</li> <li>C#</li> </ol> </body> </html> In the above example, under the <head> element, we have set the <meta> description: <head> <meta name="description" content="Learn for free"> </head> The description i.e. the meta information is set using the content attribute of the <meta> element: content="Learn for free"
[ { "code": null, "e": 1248, "s": 1062, "text": "The content attribute of the <meta> element is used to set the meta information in an HTML document. This can be the information for the description or the keywords, for name attribute." }, { "code": null, "e": 1273, "s": 1248, "text": "Following is the syntax:" }, { "code": null, "e": 1295, "s": 1273, "text": "<meta content=\"text\">" }, { "code": null, "e": 1336, "s": 1295, "text": "Above, the text is the meta information." }, { "code": null, "e": 1420, "s": 1336, "text": "Let us now see an example to implement the content attribute of the <meta> element:" }, { "code": null, "e": 1431, "s": 1420, "text": " Live Demo" }, { "code": null, "e": 1674, "s": 1431, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"description\" content=\"Learn for free\">\n</head>\n<body>\n<h2>Tutorials</h2>\n<p>Programming tutorials for free:</p>\n<ol>\n <li>Java</li>\n <li>C++</li>\n <li>C</li>\n <li>C#</li>\n</ol>\n</body>\n</html>" }, { "code": null, "e": 1758, "s": 1674, "text": "In the above example, under the <head> element, we have set the <meta> description:" }, { "code": null, "e": 1824, "s": 1758, "text": "<head>\n<meta name=\"description\" content=\"Learn for free\">\n</head>" }, { "code": null, "e": 1924, "s": 1824, "text": "The description i.e. the meta information is set using the content attribute of the <meta> element:" }, { "code": null, "e": 1949, "s": 1924, "text": "content=\"Learn for free\"" } ]
Java program to print a prime number
Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example − 7 = 1 × 7 Few prime number are − 1, 2, 3, 5 , 7, 11 etc. 1. Take integer variable A 2. Divide the variable A with (A-1 to 2) 3. If A is divisible by any value (A-1 to 2) it is not prime 4. Else it is prime import java.util.Scanner; public class PrimeNumber { public static void main(String args[]){ int loop, number; int prime = 1; Scanner sc = new Scanner(System.in); System.out.println("Enter a number ::"); number = sc.nextInt(); for(loop = 2; loop < number; loop++) { if((number % loop) == 0) { prime = 0; } } if (prime == 1) System.out.println(number+" is a prime number"); else System.out.println(number+" is not a prime number"); } } Enter a number :: 2 2 is a prime number
[ { "code": null, "e": 1257, "s": 1062, "text": "Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example −" }, { "code": null, "e": 1267, "s": 1257, "text": "7 = 1 × 7" }, { "code": null, "e": 1314, "s": 1267, "text": "Few prime number are − 1, 2, 3, 5 , 7, 11 etc." }, { "code": null, "e": 1463, "s": 1314, "text": "1. Take integer variable A\n2. Divide the variable A with (A-1 to 2)\n3. If A is divisible by any value (A-1 to 2) it is not prime\n4. Else it is prime" }, { "code": null, "e": 2012, "s": 1463, "text": "import java.util.Scanner;\npublic class PrimeNumber {\n public static void main(String args[]){\n int loop, number;\n int prime = 1;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a number ::\");\n number = sc.nextInt();\n \n for(loop = 2; loop < number; loop++) {\n if((number % loop) == 0) {\n prime = 0;\n }\n }\n if (prime == 1)\n System.out.println(number+\" is a prime number\");\n else\n System.out.println(number+\" is not a prime number\");\n }\n}" }, { "code": null, "e": 2052, "s": 2012, "text": "Enter a number ::\n2\n2 is a prime number" } ]
How to convert an object x to a string representation in Python?
Most commonly used str() function from Python library returns a string representation of object. >>> no=100 >>> str(no) '100' >>> L1=[1,2,3,4] >>> str(L1) '[1, 2, 3, 4]' >>> d={'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> str(d) "{'a': 1, 'b': 2, 'c': 3, 'd': 4}" However, repr() returns a default and unambiguous representation of the object, where as str() gives an informal representation that may be readable but may not be always unambiguous. >>> str(d) "{'a': 1, 'b': 2, 'c': 3, 'd': 4}" >>> repr(d) "{'a': 1, 'b': 2, 'c': 3, 'd': 4}" >>> repr(L1) '[1, 2, 3, 4]' >>> repr(no) '100'
[ { "code": null, "e": 1159, "s": 1062, "text": "Most commonly used str() function from Python library returns a string representation of object." }, { "code": null, "e": 1317, "s": 1159, "text": ">>> no=100\n>>> str(no)\n'100'\n>>> L1=[1,2,3,4]\n>>> str(L1)\n'[1, 2, 3, 4]'\n>>> d={'a': 1, 'b': 2, 'c': 3, 'd': 4}\n>>> str(d)\n\"{'a': 1, 'b': 2, 'c': 3, 'd': 4}\"" }, { "code": null, "e": 1501, "s": 1317, "text": "However, repr() returns a default and unambiguous representation of the object, where as str() gives an informal representation that may be readable but may not be always unambiguous." }, { "code": null, "e": 1641, "s": 1501, "text": ">>> str(d)\n\"{'a': 1, 'b': 2, 'c': 3, 'd': 4}\"\n>>> repr(d)\n\"{'a': 1, 'b': 2, 'c': 3, 'd': 4}\"\n>>> repr(L1)\n'[1, 2, 3, 4]'\n>>> repr(no)\n'100'" } ]
Java program to calculate the GCD of a given number using recursion
You can calculate the GCD of given two numbers, using recursion as shown in the following program. import java.util.Scanner; public class GCDUsingRecursion { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter first number :: "); int firstNum = sc.nextInt(); System.out.println("Enter second number :: "); int secondNum = sc.nextInt(); System.out.println("GCD of given two numbers is ::"+gcd(firstNum, secondNum)); } public static int gcd(int num1, int num2) { if (num2 != 0){ return gcd(num2, num1 % num2); } else{ return num1; } } } Enter first number :: 625 Enter second number :: 125 GCD of given two numbers is ::125
[ { "code": null, "e": 1161, "s": 1062, "text": "You can calculate the GCD of given two numbers, using recursion as shown in the following program." }, { "code": null, "e": 1734, "s": 1161, "text": "import java.util.Scanner;\npublic class GCDUsingRecursion {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter first number :: \");\n int firstNum = sc.nextInt();\n System.out.println(\"Enter second number :: \");\n int secondNum = sc.nextInt();\n System.out.println(\"GCD of given two numbers is ::\"+gcd(firstNum, secondNum));\n }\n\n public static int gcd(int num1, int num2) {\n if (num2 != 0){\n return gcd(num2, num1 % num2);\n } else{\n return num1;\n }\n }\n}" }, { "code": null, "e": 1821, "s": 1734, "text": "Enter first number ::\n625\nEnter second number ::\n125\nGCD of given two numbers is ::125" } ]
How to set a proxy for wget on Linux?
Wget is a Linux command line utility that is used to retrieve files from World Wide Web(WWW) and makes use of protocols like HTTPS and FTP. It is a freely available package and can be downloaded and installed on any Linux supporting architecture. One of the key features of wget is its ability to automatically start downloading where it was left off in case there is a network issue. It should also be noted that it deletes files recursively and it will keep trying to download all the files until it has been retrieved completely. sudo apt-get install wget yum install wget Now we know about wget, let’s first explore an example where we will try to download a file from a url with the help of the wget command. wget http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz immukul@192 linux-code % wget http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz --2021-07-11 12:12:20-- http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz Resolving ftp.gnu.org (ftp.gnu.org)... 209.51.188.20 Connecting to ftp.gnu.org (ftp.gnu.org)|209.51.188.20|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 446966 (436K) [application/x-gzip] Saving to: 'wget-1.5.3.tar.gz' wget-1.5.3.tar.gz 100%[========================================================>] 436.49K 285KB/s in 1.5s 2021-07-11 12:12:23 (285 KB/s) - 'wget-1.5.3.tar.gz' saved [446966/446966] Now, if we want to use a proxy with the wget command, we can make use of either of the two approaches mentioned below. wget -e use_proxy=yes -e http_proxy=localhost:8080 ... use_proxy=yes http_proxy=localhost:8080 https_proxy=localhost:8080 Both the above approaches will enable you to run the wget with a proxy on.
[ { "code": null, "e": 1309, "s": 1062, "text": "Wget is a Linux command line utility that is used to retrieve files from World Wide Web(WWW) and makes use of protocols like HTTPS and FTP. It is a freely available package and can be downloaded and installed on any Linux supporting architecture." }, { "code": null, "e": 1595, "s": 1309, "text": "One of the key features of wget is its ability to automatically start downloading where it was left off in case there is a network issue. It should also be noted that it deletes files recursively and it will keep trying to download all the files until it has been retrieved completely." }, { "code": null, "e": 1621, "s": 1595, "text": "sudo apt-get install wget" }, { "code": null, "e": 1638, "s": 1621, "text": "yum install wget" }, { "code": null, "e": 1776, "s": 1638, "text": "Now we know about wget, let’s first explore an example where we will try to download a file from a url with the help of the wget command." }, { "code": null, "e": 1827, "s": 1776, "text": "wget http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz" }, { "code": null, "e": 2402, "s": 1827, "text": "immukul@192 linux-code % wget http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz\n--2021-07-11 12:12:20-- http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz\nResolving ftp.gnu.org (ftp.gnu.org)... 209.51.188.20\nConnecting to ftp.gnu.org (ftp.gnu.org)|209.51.188.20|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 446966 (436K) [application/x-gzip]\nSaving to: 'wget-1.5.3.tar.gz'\n\nwget-1.5.3.tar.gz\n100%[========================================================>]\n436.49K 285KB/s in 1.5s\n\n2021-07-11 12:12:23 (285 KB/s) - 'wget-1.5.3.tar.gz' saved [446966/446966]" }, { "code": null, "e": 2521, "s": 2402, "text": "Now, if we want to use a proxy with the wget command, we can make use of either of the two approaches mentioned below." }, { "code": null, "e": 2576, "s": 2521, "text": "wget -e use_proxy=yes -e http_proxy=localhost:8080 ..." }, { "code": null, "e": 2645, "s": 2576, "text": "use_proxy=yes\n\nhttp_proxy=localhost:8080\n\nhttps_proxy=localhost:8080" }, { "code": null, "e": 2720, "s": 2645, "text": "Both the above approaches will enable you to run the wget with a proxy on." } ]
Egg Dropping Puzzle | Practice | GeeksforGeeks
You are given N identical eggs and you have access to a K-floored building from 1 to K. There exists a floor f where 0 <= f <= K such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. There are few rules given below. An egg that survives a fall can be used again. A broken egg must be discarded. The effect of a fall is the same for all eggs. If the egg doesn't break at a certain floor, it will not break at any floor below. If the eggs breaks at a certain floor, it will break at any floor above. Return the minimum number of moves that you need to determine with certainty what the value of f is. For more description on this problem see wiki page Example 1: Input: N = 1, K = 2 Output: 2 Explanation: 1. Drop the egg from floor 1. If it breaks, we know that f = 0. 2. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. 3. If it does not break, then we know f = 2. 4. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. Example 2: Input: N = 2, K = 10 Output: 4 Your Task: Complete the function eggDrop() which takes two positive integer N and K as input parameters and returns the minimum number of attempts you need in order to find the critical floor. Expected Time Complexity : O(N*(K^2)) Expected Auxiliary Space: O(N*K) Constraints: 1<=N<=200 1<=K<=200 0 mayanksh4rmain 1 hour GETTING SEGFAULT, PLEASE HELP: class Solution { public: vector<vector<int>> dp; int solve(int eggs, int floors){ if(floors == 0 or floors == 1){ return floors; } if(eggs == 1){ return floors; } if(dp[eggs][floors] != -1){ return dp[eggs][floors]; } int ans = INT_MAX; for(int currentFloor = 1; currentFloor <= floors; currentFloor++){ int temp = 1 + max(solve(eggs-1, currentFloor - 1), solve(eggs, floors - currentFloor)); int ans = min(ans, temp); } dp[eggs][floors] = ans; return dp[eggs][floors]; } int eggDrop(int n, int k) { dp.resize(n, vector<int>(k, -1)); return solve(n, k); } }; +1 shivamshuklashivam295 days ago class Solution { public: int arr[202][202]; Solution(){ memset(arr , -1 , sizeof(arr)); } int eggDrop(int e, int f) { if(f == 0 || f == 1) return f; if(e == 1) return f; if(arr[e][f] != -1) return arr[e][f]; int ans = INT_MAX; for(int k=1;k<=f;k++){ int temp = 1+ max(eggDrop(e-1,k-1) , eggDrop(e , f-k)); if(temp < ans) ans = temp; } return arr[e][f] = ans; } }; +1 vinamrajha5 days ago int eggDrop(int n, int k) { // your code here int dp[k+1][n+1]; for(int i =1; i<=n; ++i){ dp[0][i] =0; dp[1][i] =1; } for(int i =1; i<=k; ++i)dp[i][1] = i; for(int i =2; i<=k; ++i){ for(int j =2; j<=n; ++j){ dp[i][j] = INT_MAX; for(int x =1; x<=i; ++x) dp[i][j] = min(dp[i][j], 1+max(dp[x-1][j-1], dp[i-x][j])); } } return dp[k][n]; } 0 milindprajapatmst196 days ago 0.08/1.07 const int N = 200; int dp[N + 1][N + 1]; class Solution { public: int eggDrop(int n, int k) { if (k == 0 || k == 1 || n == 1) return k; if (dp[n][k] == -1) { int result = INT_MAX; for (int f = 1; f <= k; f++) result = min(result, 1 + max(eggDrop(n - 1, f - 1), eggDrop(n, k - f))); dp[n][k] = result; } return dp[n][k]; } Solution() { memset(dp, -1, sizeof(dp)); } }; 0 divyansh1923cse10022 weeks ago Why TLE in python Code? import sys class Solution: #Function to find minimum number of attempts needed in #order to find the critical floor. def eggDrop(self,n, k): dp=[[-1 for i in range(200)] for j in range(200)] if k==0 or k==1: return k mn=sys.maxsize if n==1: return k if dp[n][k]!=-1: return dp[k][n] for t in range(1,k): if dp[n-1][t-1]!=-1: left=dp[n-1][t-1] else: left=self.eggDrop(n-1,t-1) dp[n-1][t-1]=left if dp[n][k-t]!=-1: right=dp[n][k-t] else: right=self.eggDrop(n,k-t) dp[n][k-t]=right temp=1+max(left,right) mn=min(temp,mn) dp[n][k]=mn return dp[n][k] 0 jainmuskan5652 weeks ago // MCM variation question int solve(int egg,int flr){ // starting floor base condition if(flr==1 || flr==0){ return flr; } // if only 1 egg we start from bottom floor until f where it breaks for the first time if(egg==1){ return flr; } // memoization if(dp[egg][flr]!= -1){ return dp[egg][flr]; } int ans= INT_MAX; for(int k=1;k<=flr;k++){ // check worst case thats why max // if egg breaks then egg-1 and floor till kth floor // if it doesn't break then egg and floor above k (floor-k) would be 1st floor for next recursion int temp= 1+max(solve(egg-1,k-1),solve(egg,flr-k)); // min of all the worst maxes ans= min(ans,temp); } return dp[egg][flr]= ans; } int eggDrop(int n, int k) { memset(dp,-1,sizeof(dp)); return solve(n,k); } 0 ashutosh0920002 weeks ago class Solution { //Function to find minimum number of attempts needed in //order to find the critical floor. static int eggDrop(int n, int k) { int[][] dp = new int [n+1][k+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=k;j++){ if(i==1){ dp[i][j] = j ; } else if(j==1){ dp[i][j]=1; } else{ int min = Integer.MAX_VALUE; for(int mj = j-1,pj=0;mj>=0;mj--,pj++){ int val1 = dp[i][mj];//egg survives int val2 = dp[i-1][pj];//egg breaks int val = Math.max(val1,val2); min = Math.min(val,min); } dp[i][j] = min+1; } } } return dp[n][k];}} 0 ashutosh092000 This comment was deleted. 0 aishwaryadwani97993 weeks ago class Solution { static int t[][] = new int[201][201]; static int solve(int e, int f) { if (f == 0 || f == 1 || e == 1) return f; if (t[e][f] != -1) return t[e][f]; int ans = Integer.MAX_VALUE; for (int k = 1; k <= f; k++) { int tempAns = 1 + Math.max(solve(e - 1, k - 1), solve(e, f - k)); ans = Math.min(ans, tempAns); } return t[e][f] = ans; } static int eggDrop(int e, int f) { for (int arr[] : t) { Arrays.fill(arr, -1); } return solve(e, f); } } 0 shrustis1764 weeks ago C++ solution (fully optimised) int t[201][201]; int solve( int e, int f) { if( f==0 || f==1) return f; if(e==1) return f; if(t[e][f] != -1) return t[e][f]; int mn = INT_MAX; int low, high; for(int k=1; k<=f; k++) { if(t[e-1][k-1] != -1) { low = t[e-1][k-1]; } else { low=solve( e-1, k-1); t[e-1][k-1] = low; } if(t[e][f-k] != -1) { high = t[e][f-k]; } else { high =solve( e, f-k); t[e][f-k] = high; } int temp = 1+max(low,high); mn = min(mn, temp); } return t[e][f] =mn; } int eggDrop(int n, int k) { // your code here memset(t,-1,sizeof(t)); return solve(n,k); }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 326, "s": 238, "text": "You are given N identical eggs and you have access to a K-floored building from 1 to K." }, { "code": null, "e": 520, "s": 326, "text": "There exists a floor f where 0 <= f <= K such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. There are few rules given below. " }, { "code": null, "e": 567, "s": 520, "text": "An egg that survives a fall can be used again." }, { "code": null, "e": 599, "s": 567, "text": "A broken egg must be discarded." }, { "code": null, "e": 646, "s": 599, "text": "The effect of a fall is the same for all eggs." }, { "code": null, "e": 729, "s": 646, "text": "If the egg doesn't break at a certain floor, it will not break at any floor below." }, { "code": null, "e": 802, "s": 729, "text": "If the eggs breaks at a certain floor, it will break at any floor above." }, { "code": null, "e": 903, "s": 802, "text": "Return the minimum number of moves that you need to determine with certainty what the value of f is." }, { "code": null, "e": 954, "s": 903, "text": "For more description on this problem see wiki page" }, { "code": null, "e": 965, "s": 954, "text": "Example 1:" }, { "code": null, "e": 1292, "s": 965, "text": "Input:\nN = 1, K = 2\nOutput: 2\nExplanation: \n1. Drop the egg from floor 1. If it \n breaks, we know that f = 0.\n2. Otherwise, drop the egg from floor 2.\n If it breaks, we know that f = 1.\n3. If it does not break, then we know f = 2.\n4. Hence, we need at minimum 2 moves to\n determine with certainty what the value of f is." }, { "code": null, "e": 1303, "s": 1292, "text": "Example 2:" }, { "code": null, "e": 1334, "s": 1303, "text": "Input:\nN = 2, K = 10\nOutput: 4" }, { "code": null, "e": 1527, "s": 1334, "text": "Your Task:\nComplete the function eggDrop() which takes two positive integer N and K as input parameters and returns the minimum number of attempts you need in order to find the critical floor." }, { "code": null, "e": 1598, "s": 1527, "text": "Expected Time Complexity : O(N*(K^2))\nExpected Auxiliary Space: O(N*K)" }, { "code": null, "e": 1631, "s": 1598, "text": "Constraints:\n1<=N<=200\n1<=K<=200" }, { "code": null, "e": 1633, "s": 1631, "text": "0" }, { "code": null, "e": 1655, "s": 1633, "text": "mayanksh4rmain 1 hour" }, { "code": null, "e": 1686, "s": 1655, "text": "GETTING SEGFAULT, PLEASE HELP:" }, { "code": null, "e": 2516, "s": 1686, "text": "class Solution\n{\n public:\n vector<vector<int>> dp;\n \n int solve(int eggs, int floors){\n if(floors == 0 or floors == 1){\n return floors;\n }\n \n if(eggs == 1){\n return floors;\n }\n \n if(dp[eggs][floors] != -1){\n return dp[eggs][floors];\n }\n \n int ans = INT_MAX;\n \n for(int currentFloor = 1; currentFloor <= floors; currentFloor++){\n int temp = 1 + max(solve(eggs-1, currentFloor - 1), solve(eggs, floors - currentFloor));\n \n int ans = min(ans, temp);\n }\n \n dp[eggs][floors] = ans;\n \n return dp[eggs][floors];\n }\n \n int eggDrop(int n, int k) \n {\n dp.resize(n, vector<int>(k, -1));\n return solve(n, k);\n }\n};" }, { "code": null, "e": 2519, "s": 2516, "text": "+1" }, { "code": null, "e": 2550, "s": 2519, "text": "shivamshuklashivam295 days ago" }, { "code": null, "e": 3057, "s": 2550, "text": "class Solution\n{\n public:\n int arr[202][202];\n Solution(){\n memset(arr , -1 , sizeof(arr));\n }\n int eggDrop(int e, int f) \n { \n \n if(f == 0 || f == 1) return f;\n if(e == 1) return f;\n \n if(arr[e][f] != -1) return arr[e][f];\n \n int ans = INT_MAX;\n for(int k=1;k<=f;k++){\n int temp = 1+ max(eggDrop(e-1,k-1) , eggDrop(e , f-k));\n if(temp < ans) ans = temp;\n }\n return arr[e][f] = ans;\n }\n};" }, { "code": null, "e": 3060, "s": 3057, "text": "+1" }, { "code": null, "e": 3081, "s": 3060, "text": "vinamrajha5 days ago" }, { "code": null, "e": 3553, "s": 3081, "text": "int eggDrop(int n, int k) \n {\n // your code here\n int dp[k+1][n+1];\n for(int i =1; i<=n; ++i){\n dp[0][i] =0;\n dp[1][i] =1;\n }\n for(int i =1; i<=k; ++i)dp[i][1] = i;\n for(int i =2; i<=k; ++i){\n for(int j =2; j<=n; ++j){\n dp[i][j] = INT_MAX;\n for(int x =1; x<=i; ++x) dp[i][j] = min(dp[i][j], 1+max(dp[x-1][j-1], dp[i-x][j]));\n }\n }\n return dp[k][n];\n }" }, { "code": null, "e": 3555, "s": 3553, "text": "0" }, { "code": null, "e": 3585, "s": 3555, "text": "milindprajapatmst196 days ago" }, { "code": null, "e": 3596, "s": 3585, "text": "0.08/1.07 " }, { "code": null, "e": 4089, "s": 3596, "text": "const int N = 200;\nint dp[N + 1][N + 1];\n\nclass Solution {\n public:\n int eggDrop(int n, int k) {\n if (k == 0 || k == 1 || n == 1)\n return k;\n if (dp[n][k] == -1) {\n int result = INT_MAX;\n for (int f = 1; f <= k; f++)\n result = min(result, 1 + max(eggDrop(n - 1, f - 1), eggDrop(n, k - f)));\n dp[n][k] = result;\n }\n return dp[n][k];\n }\n Solution() {\n memset(dp, -1, sizeof(dp));\n }\n};" }, { "code": null, "e": 4091, "s": 4089, "text": "0" }, { "code": null, "e": 4122, "s": 4091, "text": "divyansh1923cse10022 weeks ago" }, { "code": null, "e": 4146, "s": 4122, "text": "Why TLE in python Code?" }, { "code": null, "e": 4978, "s": 4146, "text": "import sys\nclass Solution:\n \n #Function to find minimum number of attempts needed in \n #order to find the critical floor.\n def eggDrop(self,n, k):\n dp=[[-1 for i in range(200)] for j in range(200)]\n if k==0 or k==1:\n return k\n mn=sys.maxsize\n if n==1:\n return k\n if dp[n][k]!=-1:\n return dp[k][n]\n for t in range(1,k):\n if dp[n-1][t-1]!=-1:\n left=dp[n-1][t-1]\n else:\n left=self.eggDrop(n-1,t-1)\n dp[n-1][t-1]=left\n if dp[n][k-t]!=-1:\n right=dp[n][k-t]\n else:\n right=self.eggDrop(n,k-t)\n dp[n][k-t]=right\n temp=1+max(left,right)\n mn=min(temp,mn)\n dp[n][k]=mn\n return dp[n][k]" }, { "code": null, "e": 4980, "s": 4978, "text": "0" }, { "code": null, "e": 5005, "s": 4980, "text": "jainmuskan5652 weeks ago" }, { "code": null, "e": 5946, "s": 5005, "text": "// MCM variation question int solve(int egg,int flr){ // starting floor base condition if(flr==1 || flr==0){ return flr; } // if only 1 egg we start from bottom floor until f where it breaks for the first time if(egg==1){ return flr; } // memoization if(dp[egg][flr]!= -1){ return dp[egg][flr]; } int ans= INT_MAX; for(int k=1;k<=flr;k++){ // check worst case thats why max // if egg breaks then egg-1 and floor till kth floor // if it doesn't break then egg and floor above k (floor-k) would be 1st floor for next recursion int temp= 1+max(solve(egg-1,k-1),solve(egg,flr-k)); // min of all the worst maxes ans= min(ans,temp); } return dp[egg][flr]= ans; } int eggDrop(int n, int k) { memset(dp,-1,sizeof(dp)); return solve(n,k); }" }, { "code": null, "e": 5948, "s": 5946, "text": "0" }, { "code": null, "e": 5974, "s": 5948, "text": "ashutosh0920002 weeks ago" }, { "code": null, "e": 6768, "s": 5974, "text": "class Solution { //Function to find minimum number of attempts needed in //order to find the critical floor. static int eggDrop(int n, int k) { int[][] dp = new int [n+1][k+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=k;j++){ if(i==1){ dp[i][j] = j ; } else if(j==1){ dp[i][j]=1; } else{ int min = Integer.MAX_VALUE; for(int mj = j-1,pj=0;mj>=0;mj--,pj++){ int val1 = dp[i][mj];//egg survives int val2 = dp[i-1][pj];//egg breaks int val = Math.max(val1,val2); min = Math.min(val,min); } dp[i][j] = min+1; } } } return dp[n][k];}} " }, { "code": null, "e": 6770, "s": 6768, "text": "0" }, { "code": null, "e": 6785, "s": 6770, "text": "ashutosh092000" }, { "code": null, "e": 6811, "s": 6785, "text": "This comment was deleted." }, { "code": null, "e": 6813, "s": 6811, "text": "0" }, { "code": null, "e": 6843, "s": 6813, "text": "aishwaryadwani97993 weeks ago" }, { "code": null, "e": 6860, "s": 6843, "text": "class Solution {" }, { "code": null, "e": 6902, "s": 6860, "text": " static int t[][] = new int[201][201];" }, { "code": null, "e": 6941, "s": 6904, "text": " static int solve(int e, int f) {" }, { "code": null, "e": 6981, "s": 6941, "text": " if (f == 0 || f == 1 || e == 1)" }, { "code": null, "e": 7003, "s": 6981, "text": " return f;" }, { "code": null, "e": 7030, "s": 7003, "text": " if (t[e][f] != -1)" }, { "code": null, "e": 7058, "s": 7030, "text": " return t[e][f];" }, { "code": null, "e": 7095, "s": 7058, "text": " int ans = Integer.MAX_VALUE;" }, { "code": null, "e": 7134, "s": 7095, "text": " for (int k = 1; k <= f; k++) {" }, { "code": null, "e": 7212, "s": 7134, "text": " int tempAns = 1 + Math.max(solve(e - 1, k - 1), solve(e, f - k));" }, { "code": null, "e": 7254, "s": 7212, "text": " ans = Math.min(ans, tempAns);" }, { "code": null, "e": 7264, "s": 7254, "text": " }" }, { "code": null, "e": 7294, "s": 7264, "text": " return t[e][f] = ans;" }, { "code": null, "e": 7300, "s": 7294, "text": " }" }, { "code": null, "e": 7341, "s": 7302, "text": " static int eggDrop(int e, int f) {" }, { "code": null, "e": 7371, "s": 7341, "text": " for (int arr[] : t) {" }, { "code": null, "e": 7405, "s": 7371, "text": " Arrays.fill(arr, -1);" }, { "code": null, "e": 7415, "s": 7405, "text": " }" }, { "code": null, "e": 7443, "s": 7415, "text": " return solve(e, f);" }, { "code": null, "e": 7449, "s": 7443, "text": " }" }, { "code": null, "e": 7451, "s": 7449, "text": "}" }, { "code": null, "e": 7453, "s": 7451, "text": "0" }, { "code": null, "e": 7476, "s": 7453, "text": "shrustis1764 weeks ago" }, { "code": null, "e": 7507, "s": 7476, "text": "C++ solution (fully optimised)" }, { "code": null, "e": 8450, "s": 7509, "text": "int t[201][201]; int solve( int e, int f) { if( f==0 || f==1) return f; if(e==1) return f; if(t[e][f] != -1) return t[e][f]; int mn = INT_MAX; int low, high; for(int k=1; k<=f; k++) { if(t[e-1][k-1] != -1) { low = t[e-1][k-1]; } else { low=solve( e-1, k-1); t[e-1][k-1] = low; } if(t[e][f-k] != -1) { high = t[e][f-k]; } else { high =solve( e, f-k); t[e][f-k] = high; } int temp = 1+max(low,high); mn = min(mn, temp); } return t[e][f] =mn; } int eggDrop(int n, int k) { // your code here memset(t,-1,sizeof(t)); return solve(n,k); }}; " }, { "code": null, "e": 8596, "s": 8450, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8632, "s": 8596, "text": " Login to access your submissions. " }, { "code": null, "e": 8642, "s": 8632, "text": "\nProblem\n" }, { "code": null, "e": 8652, "s": 8642, "text": "\nContest\n" }, { "code": null, "e": 8715, "s": 8652, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8863, "s": 8715, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9071, "s": 8863, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 9177, "s": 9071, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to filter String stream and map to lower case in Java? Perform sort as well.
Let’s say the following is String array, which we have converted to List − Arrays.asList("DE", "GH", "JK", "MN", "PQ", "RS", "TU", "VW", "XY", "BC") Now filter String stream and map to lower case − .stream() .filter(a-> a.startsWith("V")) .map(String::toLowerCase) To sort now, use the sorted() and display using forEach(). The following is an example to filter string stream and map to lowercase − import java.util.Arrays; public class Demo { public static void main(String[] args) throws Exception { Arrays.asList("DE", "GH", "JK", "MN", "PQ", "RS", "TU", "VW", "XY", "BC") .stream() .filter(a-> a.startsWith("V")) .map(String::toLowerCase) .sorted() .forEach(System.out::println); } } Vw
[ { "code": null, "e": 1137, "s": 1062, "text": "Let’s say the following is String array, which we have converted to List −" }, { "code": null, "e": 1211, "s": 1137, "text": "Arrays.asList(\"DE\", \"GH\", \"JK\", \"MN\", \"PQ\", \"RS\", \"TU\", \"VW\", \"XY\", \"BC\")" }, { "code": null, "e": 1260, "s": 1211, "text": "Now filter String stream and map to lower case −" }, { "code": null, "e": 1327, "s": 1260, "text": ".stream()\n.filter(a-> a.startsWith(\"V\"))\n.map(String::toLowerCase)" }, { "code": null, "e": 1386, "s": 1327, "text": "To sort now, use the sorted() and display using forEach()." }, { "code": null, "e": 1461, "s": 1386, "text": "The following is an example to filter string stream and map to lowercase −" }, { "code": null, "e": 1792, "s": 1461, "text": "import java.util.Arrays;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n Arrays.asList(\"DE\", \"GH\", \"JK\", \"MN\", \"PQ\", \"RS\", \"TU\", \"VW\", \"XY\", \"BC\")\n .stream()\n .filter(a-> a.startsWith(\"V\"))\n .map(String::toLowerCase)\n .sorted()\n .forEach(System.out::println);\n }\n}" }, { "code": null, "e": 1795, "s": 1792, "text": "Vw" } ]
Gradle - Build a JAVA Project
This chapter explains how to build a java project using Gradle build file. First of all, we have to add java plugin to the build script, because, it provides the tasks to compile Java source code, to run the unit tests, to create a Javadoc and to create a JAR file. Use the following line in build.gradle file. apply plugin: 'java' Whenever you add a plugin to your build, it assumes a certain setup of your Java project (similar to Maven). Take a look at the following directory structure. src/main/java contains the Java source code. src/test/java contains the Java tests. If you follow this setup, the following build file is sufficient to compile, test, and bundle a Java project. To start the build, type the following command on the command line. C:\> gradle build SourceSets can be used to specify a different project structure. For example, the sources are stored in a src folder rather than in src/main/java. Take a look at the following directory structure. apply plugin: 'java' sourceSets { main { java { srcDir 'src' } } test { java { srcDir 'test' } } } Gradle does not yet support multiple project templates. But it offers an init task to create the structure of a new Gradle project. Without additional parameters, this task creates a Gradle project, which contains the gradle wrapper files, a build.gradle and settings.gradle file. When adding the --type parameter with java-library as value, a java project structure is created and the build.gradle file contains a certain Java template with Junit. Take a look at the following code for build.gradle file. apply plugin: 'java' repositories { jcenter() } dependencies { compile 'org.slf4j:slf4j-api:1.7.12' testCompile 'junit:junit:4.12' } In the repositories section, it defines where to find the dependencies. Jcenter is for resolving your dependencies. Dependencies section is for providing information about external dependencies. Usually, a Java project has a version and a target JRE on which it is compiled. The version and sourceCompatibility property can be set in the build.gradle file. version = 0.1.0 sourceCompatibility = 1.8 If the artifact is an executable Java application, the MANIFEST.MF file must be aware of the class with the main method. apply plugin: 'java' jar { manifest { attributes 'Main-Class': 'com.example.main.Application' } } Create a directory structure as shown in the below screenshot. Copy the below given java code into App.java file and store into consumerbanking\src\main\java\com\bank directory. package com.bank; /** * Hello world! * */ public class App { public static void main( String[] args ){ System.out.println( "Hello World!" ); } } Copy the below given java code into AppTset.java file and store into consumerbanking\src\test\java\com\bank directory. package com.bank; /** * Hello world! * */ public class App{ public static void main( String[] args ){ System.out.println( "Hello World!" ); } } Copy the below given code into build.gradle file and placed into consumerbanking\ directory. apply plugin: 'java' repositories { jcenter() } dependencies { compile 'org.slf4j:slf4j-api:1.7.12' testCompile 'junit:junit:4.12' } jar { manifest { attributes 'Main-Class': 'com.example.main.Application' } } To compile and execute the above script use the below given commands. consumerbanking\> gradle tasks consumerbanking\> gradle assemble consumerbanking\> gradle build Check all the class files in the respective directories and check consumerbanking\build\lib folder for consumerbanking.jar file. Print Add Notes Bookmark this page
[ { "code": null, "e": 1957, "s": 1882, "text": "This chapter explains how to build a java project using Gradle build file." }, { "code": null, "e": 2148, "s": 1957, "text": "First of all, we have to add java plugin to the build script, because, it provides the tasks to compile Java source code, to run the unit tests, to create a Javadoc and to create a JAR file." }, { "code": null, "e": 2193, "s": 2148, "text": "Use the following line in build.gradle file." }, { "code": null, "e": 2215, "s": 2193, "text": "apply plugin: 'java'\n" }, { "code": null, "e": 2374, "s": 2215, "text": "Whenever you add a plugin to your build, it assumes a certain setup of your Java project (similar to Maven). Take a look at the following directory structure." }, { "code": null, "e": 2419, "s": 2374, "text": "src/main/java contains the Java source code." }, { "code": null, "e": 2458, "s": 2419, "text": "src/test/java contains the Java tests." }, { "code": null, "e": 2568, "s": 2458, "text": "If you follow this setup, the following build file is sufficient to compile, test, and bundle a Java project." }, { "code": null, "e": 2636, "s": 2568, "text": "To start the build, type the following command on the command line." }, { "code": null, "e": 2655, "s": 2636, "text": "C:\\> gradle build\n" }, { "code": null, "e": 2852, "s": 2655, "text": "SourceSets can be used to specify a different project structure. For example, the sources are stored in a src folder rather than in src/main/java. Take a look at the following directory structure." }, { "code": null, "e": 3007, "s": 2852, "text": "apply plugin: 'java'\nsourceSets {\n main {\n java {\n srcDir 'src'\n }\n }\n\t\n test {\n java {\n srcDir 'test'\n }\n }\n}" }, { "code": null, "e": 3288, "s": 3007, "text": "Gradle does not yet support multiple project templates. But it offers an init task to create the structure of a new Gradle project. Without additional parameters, this task creates a Gradle project, which contains the gradle wrapper files, a build.gradle and settings.gradle file." }, { "code": null, "e": 3513, "s": 3288, "text": "When adding the --type parameter with java-library as value, a java project structure is created and the build.gradle file contains a certain Java template with Junit. Take a look at the following code for build.gradle file." }, { "code": null, "e": 3657, "s": 3513, "text": "apply plugin: 'java'\n\nrepositories {\n jcenter()\n}\n\ndependencies {\n compile 'org.slf4j:slf4j-api:1.7.12'\n testCompile 'junit:junit:4.12'\n}" }, { "code": null, "e": 3852, "s": 3657, "text": "In the repositories section, it defines where to find the dependencies. Jcenter is for resolving your dependencies. Dependencies section is for providing information about external dependencies." }, { "code": null, "e": 4014, "s": 3852, "text": "Usually, a Java project has a version and a target JRE on which it is compiled. The version and sourceCompatibility property can be set in the build.gradle file." }, { "code": null, "e": 4057, "s": 4014, "text": "version = 0.1.0\nsourceCompatibility = 1.8\n" }, { "code": null, "e": 4178, "s": 4057, "text": "If the artifact is an executable Java application, the MANIFEST.MF file must be aware of the class with the main method." }, { "code": null, "e": 4289, "s": 4178, "text": "apply plugin: 'java'\n\njar {\n manifest {\n attributes 'Main-Class': 'com.example.main.Application'\n }\n}" }, { "code": null, "e": 4352, "s": 4289, "text": "Create a directory structure as shown in the below screenshot." }, { "code": null, "e": 4467, "s": 4352, "text": "Copy the below given java code into App.java file and store into consumerbanking\\src\\main\\java\\com\\bank directory." }, { "code": null, "e": 4626, "s": 4467, "text": "package com.bank;\n\n/**\n* Hello world!\n*\n*/\n\npublic class App {\n public static void main( String[] args ){\n System.out.println( \"Hello World!\" );\n }\n}" }, { "code": null, "e": 4745, "s": 4626, "text": "Copy the below given java code into AppTset.java file and store into consumerbanking\\src\\test\\java\\com\\bank directory." }, { "code": null, "e": 4903, "s": 4745, "text": "package com.bank;\n\n/**\n* Hello world!\n*\n*/\n\npublic class App{\n public static void main( String[] args ){\n System.out.println( \"Hello World!\" );\n }\n}" }, { "code": null, "e": 4996, "s": 4903, "text": "Copy the below given code into build.gradle file and placed into consumerbanking\\ directory." }, { "code": null, "e": 5230, "s": 4996, "text": "apply plugin: 'java'\n\nrepositories {\n jcenter()\n}\n\ndependencies {\n compile 'org.slf4j:slf4j-api:1.7.12'\n testCompile 'junit:junit:4.12'\n}\n\njar {\n manifest {\n attributes 'Main-Class': 'com.example.main.Application'\n }\n}" }, { "code": null, "e": 5300, "s": 5230, "text": "To compile and execute the above script use the below given commands." }, { "code": null, "e": 5397, "s": 5300, "text": "consumerbanking\\> gradle tasks\nconsumerbanking\\> gradle assemble\nconsumerbanking\\> gradle build\n" }, { "code": null, "e": 5526, "s": 5397, "text": "Check all the class files in the respective directories and check consumerbanking\\build\\lib folder for consumerbanking.jar file." }, { "code": null, "e": 5533, "s": 5526, "text": " Print" }, { "code": null, "e": 5544, "s": 5533, "text": " Add Notes" } ]
First uppercase letter in a string (Iterative and Recursive) - GeeksforGeeks
12 Jan, 2022 Given a string find its first uppercase letterExamples : Input : geeksforgeeKs Output : K Input : geekS Output : S Method 1: linear search Using linear search, find the first character which is capital C++ Java Python3 C# PHP Javascript // C++ program to find the first// uppercase letter using linear search#include <bits/stdc++.h>using namespace std; // Function to find string which has// first character of each word.char first(string str){ for (int i = 0; i < str.length(); i++) if (isupper(str[i])) return str[i]; return 0;} // Driver codeint main(){ string str = "geeksforGeeKS"; char res = first(str); if (res == 0) cout << "No uppercase letter"; else cout << res << "\n"; return 0;} // Java program to find the first// uppercase letter using linear searchimport java.io.*;import java.util.*; class GFG { // Function to find string which has // first character of each word. static char first(String str) { for (int i = 0; i < str.length(); i++) if (Character.isUpperCase(str.charAt(i))) return str.charAt(i); return 0; } // Driver program public static void main(String args[]) { String str = "geeksforGeeKS"; char res = first(str); if (res == 0) System.out.println("No uppercase letter"); else System.out.println(res); }} // This code is contributed// by Nikita Tiwari. # Python3 program to find the first# uppercase letter using linear search # Function to find string which has# first character of each word.def first(str) : for i in range(0, len(str)) : if (str[i].istitle()) : return str[i] return 0 # Driver codestr = "geeksforGeeKS"res = first(str) if (res == 0) : print("No uppercase letter") else : print(res) # This code is contributed by Nikita Tiwari // C# program to find the first uppercase// letter using linear searchusing System; class GFG { // Function to find string which has // first character of each word. static char first(string str) { for (int i = 0; i < str.Length; i++) if (char.IsUpper(str[i]) ) return str[i]; return '0'; } // Driver function public static void Main() { string str = "geeksforGeeKS"; char res = first(str); if (res == '0') Console.WriteLine("No uppercase" + " letter"); else Console.WriteLine(res); }} // This code is contributed by Sam007 <?php// PHP program to find the first// uppercase letter using linear search // Function to find string which has// first character of each word.function first($str){ for ($i = 0; $i < strlen($str); $i++) if (ctype_upper($str[$i])) { return $str[$i]; } return 0;} // Driver code $str = "geeksforGeeKS"; $res = first($str); if (ord($res) ==ord(0) ) echo "No uppercase letter"; else echo $res . "\n"; // This code is contributed by Sam007?> <script> // JavaScript program to find the first // uppercase letter using linear search // Function to find string which has // first character of each word. function first(str) { for (var i = 0; i < str.length; i++) if (str[i] === str[i].toUpperCase()) return str[i]; return 0; } // Driver code var str = "geeksforGeeKS"; var res = first(str); if (res == 0) document.write("No uppercase letter"); else { document.write(res); document.write("<br>"); } // This code is contributed by rdtank. </script> Output: G Method 2 (Using recursion) Recursively traverse the string and if any uppercase is found return that character C++ Java Python 3 C# PHP Javascript // C++ program to find the// first uppercase letter.#include <bits/stdc++.h>using namespace std; // Function to find string which has// first character of each word.char first(string str, int i=0){ if (str[i] == '\0') return 0; if (isupper(str[i])) return str[i]; return first(str, i+1);} // Driver codeint main(){ string str = "geeksforGeeKS"; char res = first(str); if (res == 0) cout << "No uppercase letter"; else cout << res << "\n"; return 0;} // Java program to find the// first uppercase letter.import java.io.*; class GFG { // Function to find string which has // first character of each word. static char first(String str, int i) { if(str.charAt(i)=='\0'){ return 0; } if(Character.isUpperCase(str.charAt(i))) { return str.charAt(i); } try { return first(str, i + 1); } catch(Exception e){ System.out.println("Exception occures"); } return 0; } // Driver code public static void main(String args[]) { String str = "geeksforGeeKS"; char res = first(str,0); if (res == 0) System.out.println("No uppercase letter"); else System.out.println (res ); }} // This code is contributed// by Shravan Sutar(suthar826) def capital(N, i, x): if i >= x: return -1 elif N[i].isupper(): return i if i < x: return capital(N, i + 1, x) def main(): N = input() N = list(N) x = len(N) y = (capital(N, 0, x)) print(y) if __name__ == '__main__': main() // C# program to find the// first uppercase letter.using System; class GFG{ // Function to find string // which has first character // of each word. static char first(string str, int i) { if (str[i] == '\0') return '0'; if (char.IsUpper(str[i])) return (str[i]); return first(str, i + 1); } // Driver code static public void Main () { string str = "geeksforGeeKS"; char res = first(str, 0); if (res == 0) Console.WriteLine("No uppercase letter"); else Console.WriteLine(res ); }} // This code is contributed by Anuj_67. <?php//PHP program to find the// first uppercase letter. // Function to find string// which has first character// of each word. function first($str, $i = 0){ if ($str[$i] == '\0') return 0; if (ctype_upper($str[$i])) return $str[$i]; return first($str, $i+1);} // Driver code $str = "geeksforGeeKS"; $res = first($str); if (ord($res) ==ord(0)) echo "No uppercase letter"; else echo $res , "\n"; // This code is contributed// by m_kit?> <script> // Javascript program to find the// first uppercase letter. // Function to find string which has// first character of each word.function first(str,i=0){ if (i == str.length) return 0; if (str[i] == str[i].toUpperCase()) return str[i]; return first(str, i+1);} // Driver codevar str = "geeksforGeeKS";var res = first(str);if (res == 0) document.write( "No uppercase letter");else document.write( res + "<br>"); </script> Output : G Sam007 vt_m jit_t Smitha Dinesh Semwal harshitshukla2 rdtank noob2000 suthar826 Recursion Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all possible combinations of r elements in a given array of size n Recursive Practice Problems with Solutions Write a program to reverse digits of a number Recursive Functions Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 25623, "s": 25595, "text": "\n12 Jan, 2022" }, { "code": null, "e": 25681, "s": 25623, "text": "Given a string find its first uppercase letterExamples : " }, { "code": null, "e": 25741, "s": 25681, "text": "Input : geeksforgeeKs\nOutput : K\n\nInput : geekS\nOutput : S" }, { "code": null, "e": 25830, "s": 25741, "text": "Method 1: linear search Using linear search, find the first character which is capital " }, { "code": null, "e": 25834, "s": 25830, "text": "C++" }, { "code": null, "e": 25839, "s": 25834, "text": "Java" }, { "code": null, "e": 25847, "s": 25839, "text": "Python3" }, { "code": null, "e": 25850, "s": 25847, "text": "C#" }, { "code": null, "e": 25854, "s": 25850, "text": "PHP" }, { "code": null, "e": 25865, "s": 25854, "text": "Javascript" }, { "code": "// C++ program to find the first// uppercase letter using linear search#include <bits/stdc++.h>using namespace std; // Function to find string which has// first character of each word.char first(string str){ for (int i = 0; i < str.length(); i++) if (isupper(str[i])) return str[i]; return 0;} // Driver codeint main(){ string str = \"geeksforGeeKS\"; char res = first(str); if (res == 0) cout << \"No uppercase letter\"; else cout << res << \"\\n\"; return 0;}", "e": 26373, "s": 25865, "text": null }, { "code": "// Java program to find the first// uppercase letter using linear searchimport java.io.*;import java.util.*; class GFG { // Function to find string which has // first character of each word. static char first(String str) { for (int i = 0; i < str.length(); i++) if (Character.isUpperCase(str.charAt(i))) return str.charAt(i); return 0; } // Driver program public static void main(String args[]) { String str = \"geeksforGeeKS\"; char res = first(str); if (res == 0) System.out.println(\"No uppercase letter\"); else System.out.println(res); }} // This code is contributed// by Nikita Tiwari.", "e": 27085, "s": 26373, "text": null }, { "code": "# Python3 program to find the first# uppercase letter using linear search # Function to find string which has# first character of each word.def first(str) : for i in range(0, len(str)) : if (str[i].istitle()) : return str[i] return 0 # Driver codestr = \"geeksforGeeKS\"res = first(str) if (res == 0) : print(\"No uppercase letter\") else : print(res) # This code is contributed by Nikita Tiwari", "e": 27548, "s": 27085, "text": null }, { "code": "// C# program to find the first uppercase// letter using linear searchusing System; class GFG { // Function to find string which has // first character of each word. static char first(string str) { for (int i = 0; i < str.Length; i++) if (char.IsUpper(str[i]) ) return str[i]; return '0'; } // Driver function public static void Main() { string str = \"geeksforGeeKS\"; char res = first(str); if (res == '0') Console.WriteLine(\"No uppercase\" + \" letter\"); else Console.WriteLine(res); }} // This code is contributed by Sam007", "e": 28229, "s": 27548, "text": null }, { "code": "<?php// PHP program to find the first// uppercase letter using linear search // Function to find string which has// first character of each word.function first($str){ for ($i = 0; $i < strlen($str); $i++) if (ctype_upper($str[$i])) { return $str[$i]; } return 0;} // Driver code $str = \"geeksforGeeKS\"; $res = first($str); if (ord($res) ==ord(0) ) echo \"No uppercase letter\"; else echo $res . \"\\n\"; // This code is contributed by Sam007?>", "e": 28754, "s": 28229, "text": null }, { "code": "<script> // JavaScript program to find the first // uppercase letter using linear search // Function to find string which has // first character of each word. function first(str) { for (var i = 0; i < str.length; i++) if (str[i] === str[i].toUpperCase()) return str[i]; return 0; } // Driver code var str = \"geeksforGeeKS\"; var res = first(str); if (res == 0) document.write(\"No uppercase letter\"); else { document.write(res); document.write(\"<br>\"); } // This code is contributed by rdtank. </script>", "e": 29371, "s": 28754, "text": null }, { "code": null, "e": 29380, "s": 29371, "text": "Output: " }, { "code": null, "e": 29382, "s": 29380, "text": "G" }, { "code": null, "e": 29494, "s": 29382, "text": "Method 2 (Using recursion) Recursively traverse the string and if any uppercase is found return that character " }, { "code": null, "e": 29498, "s": 29494, "text": "C++" }, { "code": null, "e": 29503, "s": 29498, "text": "Java" }, { "code": null, "e": 29512, "s": 29503, "text": "Python 3" }, { "code": null, "e": 29515, "s": 29512, "text": "C#" }, { "code": null, "e": 29519, "s": 29515, "text": "PHP" }, { "code": null, "e": 29530, "s": 29519, "text": "Javascript" }, { "code": "// C++ program to find the// first uppercase letter.#include <bits/stdc++.h>using namespace std; // Function to find string which has// first character of each word.char first(string str, int i=0){ if (str[i] == '\\0') return 0; if (isupper(str[i])) return str[i]; return first(str, i+1);} // Driver codeint main(){ string str = \"geeksforGeeKS\"; char res = first(str); if (res == 0) cout << \"No uppercase letter\"; else cout << res << \"\\n\"; return 0;}", "e": 30037, "s": 29530, "text": null }, { "code": "// Java program to find the// first uppercase letter.import java.io.*; class GFG { // Function to find string which has // first character of each word. static char first(String str, int i) { if(str.charAt(i)=='\\0'){ return 0; } if(Character.isUpperCase(str.charAt(i))) { return str.charAt(i); } try { return first(str, i + 1); } catch(Exception e){ System.out.println(\"Exception occures\"); } return 0; } // Driver code public static void main(String args[]) { String str = \"geeksforGeeKS\"; char res = first(str,0); if (res == 0) System.out.println(\"No uppercase letter\"); else System.out.println (res ); }} // This code is contributed// by Shravan Sutar(suthar826)", "e": 30897, "s": 30037, "text": null }, { "code": "def capital(N, i, x): if i >= x: return -1 elif N[i].isupper(): return i if i < x: return capital(N, i + 1, x) def main(): N = input() N = list(N) x = len(N) y = (capital(N, 0, x)) print(y) if __name__ == '__main__': main()", "e": 31171, "s": 30897, "text": null }, { "code": "// C# program to find the// first uppercase letter.using System; class GFG{ // Function to find string // which has first character // of each word. static char first(string str, int i) { if (str[i] == '\\0') return '0'; if (char.IsUpper(str[i])) return (str[i]); return first(str, i + 1); } // Driver code static public void Main () { string str = \"geeksforGeeKS\"; char res = first(str, 0); if (res == 0) Console.WriteLine(\"No uppercase letter\"); else Console.WriteLine(res ); }} // This code is contributed by Anuj_67.", "e": 31828, "s": 31171, "text": null }, { "code": "<?php//PHP program to find the// first uppercase letter. // Function to find string// which has first character// of each word. function first($str, $i = 0){ if ($str[$i] == '\\0') return 0; if (ctype_upper($str[$i])) return $str[$i]; return first($str, $i+1);} // Driver code $str = \"geeksforGeeKS\"; $res = first($str); if (ord($res) ==ord(0)) echo \"No uppercase letter\"; else echo $res , \"\\n\"; // This code is contributed// by m_kit?>", "e": 32322, "s": 31828, "text": null }, { "code": "<script> // Javascript program to find the// first uppercase letter. // Function to find string which has// first character of each word.function first(str,i=0){ if (i == str.length) return 0; if (str[i] == str[i].toUpperCase()) return str[i]; return first(str, i+1);} // Driver codevar str = \"geeksforGeeKS\";var res = first(str);if (res == 0) document.write( \"No uppercase letter\");else document.write( res + \"<br>\"); </script>", "e": 32786, "s": 32322, "text": null }, { "code": null, "e": 32796, "s": 32786, "text": "Output : " }, { "code": null, "e": 32799, "s": 32796, "text": "G " }, { "code": null, "e": 32806, "s": 32799, "text": "Sam007" }, { "code": null, "e": 32811, "s": 32806, "text": "vt_m" }, { "code": null, "e": 32817, "s": 32811, "text": "jit_t" }, { "code": null, "e": 32838, "s": 32817, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 32853, "s": 32838, "text": "harshitshukla2" }, { "code": null, "e": 32860, "s": 32853, "text": "rdtank" }, { "code": null, "e": 32869, "s": 32860, "text": "noob2000" }, { "code": null, "e": 32879, "s": 32869, "text": "suthar826" }, { "code": null, "e": 32889, "s": 32879, "text": "Recursion" }, { "code": null, "e": 32897, "s": 32889, "text": "Strings" }, { "code": null, "e": 32905, "s": 32897, "text": "Strings" }, { "code": null, "e": 32915, "s": 32905, "text": "Recursion" }, { "code": null, "e": 33013, "s": 32915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33041, "s": 33013, "text": "Backtracking | Introduction" }, { "code": null, "e": 33114, "s": 33041, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 33157, "s": 33114, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 33203, "s": 33157, "text": "Write a program to reverse digits of a number" }, { "code": null, "e": 33223, "s": 33203, "text": "Recursive Functions" }, { "code": null, "e": 33269, "s": 33223, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33294, "s": 33269, "text": "Reverse a string in Java" }, { "code": null, "e": 33328, "s": 33294, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33343, "s": 33328, "text": "C++ Data Types" } ]
HTML <img> referrerpolicy Attribute - GeeksforGeeks
02 Mar, 2022 The HTML <img> referrerpolicy attribute is used to specify the reference information that will be sent to the server when fetching the image. Syntax: <img referrerpolicy="value"> Attribute Values : no-referrer: It specifies that no reference information will be sent along with a request. no-referrer-when-downgrade: It has a default value. It specifies that refer header will not be sent to origins without HTTPS. origin: It specifies to send the origin of the document as the referrer in all cases. origin-when-cross-origin: It sends the origin, path, and query string when performing a same-origin request, but only send the origin of the document for other cases. unsafe-url: It sends origin. path and query string but not include fragment, password and username. Example: Below code illustrates the use of <img> referrer policy attribute. HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2> HTML img referrerpolicy Attribute </h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks logo" referrerpolicy="no-referrer" ></body> </html> Output: Supported Browsers: Google Chrome 53.0 Internet Explorer Not Supported Firefox 50.0 Safari 14.0 Opera 40.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery DOM (Document Object Model) Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24894, "s": 24866, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25037, "s": 24894, "text": "The HTML <img> referrerpolicy attribute is used to specify the reference information that will be sent to the server when fetching the image. " }, { "code": null, "e": 25045, "s": 25037, "text": "Syntax:" }, { "code": null, "e": 25076, "s": 25045, "text": "<img referrerpolicy=\"value\"> " }, { "code": null, "e": 25096, "s": 25076, "text": "Attribute Values : " }, { "code": null, "e": 25187, "s": 25096, "text": "no-referrer: It specifies that no reference information will be sent along with a request." }, { "code": null, "e": 25313, "s": 25187, "text": "no-referrer-when-downgrade: It has a default value. It specifies that refer header will not be sent to origins without HTTPS." }, { "code": null, "e": 25399, "s": 25313, "text": "origin: It specifies to send the origin of the document as the referrer in all cases." }, { "code": null, "e": 25566, "s": 25399, "text": "origin-when-cross-origin: It sends the origin, path, and query string when performing a same-origin request, but only send the origin of the document for other cases." }, { "code": null, "e": 25666, "s": 25566, "text": "unsafe-url: It sends origin. path and query string but not include fragment, password and username." }, { "code": null, "e": 25743, "s": 25666, "text": "Example: Below code illustrates the use of <img> referrer policy attribute. " }, { "code": null, "e": 25748, "s": 25743, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2> HTML img referrerpolicy Attribute </h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks logo\" referrerpolicy=\"no-referrer\" ></body> </html>", "e": 26034, "s": 25748, "text": null }, { "code": null, "e": 26042, "s": 26034, "text": "Output:" }, { "code": null, "e": 26062, "s": 26042, "text": "Supported Browsers:" }, { "code": null, "e": 26081, "s": 26062, "text": "Google Chrome 53.0" }, { "code": null, "e": 26113, "s": 26081, "text": "Internet Explorer Not Supported" }, { "code": null, "e": 26126, "s": 26113, "text": "Firefox 50.0" }, { "code": null, "e": 26138, "s": 26126, "text": "Safari 14.0" }, { "code": null, "e": 26149, "s": 26138, "text": "Opera 40.0" }, { "code": null, "e": 26286, "s": 26149, "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": 26306, "s": 26286, "text": "hritikbhatnagar2182" }, { "code": null, "e": 26322, "s": 26306, "text": "HTML-Attributes" }, { "code": null, "e": 26327, "s": 26322, "text": "HTML" }, { "code": null, "e": 26344, "s": 26327, "text": "Web Technologies" }, { "code": null, "e": 26349, "s": 26344, "text": "HTML" }, { "code": null, "e": 26447, "s": 26349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26471, "s": 26447, "text": "REST API (Introduction)" }, { "code": null, "e": 26508, "s": 26471, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26528, "s": 26508, "text": "Angular File Upload" }, { "code": null, "e": 26557, "s": 26528, "text": "Form validation using jQuery" }, { "code": null, "e": 26585, "s": 26557, "text": "DOM (Document Object Model)" }, { "code": null, "e": 26627, "s": 26585, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26670, "s": 26627, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26703, "s": 26670, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26748, "s": 26703, "text": "Convert a string to an integer in JavaScript" } ]
Regularization Techniques And Their Implementation In TensorFlow(Keras) | by Richmond Alake | Towards Data Science
Deep Neural Networks(DNN) have a vast amount of weights parameters internal to the architecture that learn a range of values. These range of values are the essential key to enabling the neural network to solve huge complex functions. The deeper a neural network is, the more representational power it possesses, but, there is a shortcoming that occurs as the number of weight parameter increases. This shortcoming is that the neural network is more prone to overfitting the training dataset. Overfitting: This problem involves the algorithm predicting new instances of patterns presented to it, based too closely on instances of patterns it observed and learnt during training. This can cause the machine-learning algorithm to not generalize accurately to unseen data. Overfitting can occur if the training data does not accurately represent the distribution of test data. Overfitting can be fixed by reducing the number of features in the training data and reducing the complexity of the network through various techniques Regularization techniques reduce the possibility of a neural network overfitting by constraining the range of values that the weight values within the network hold(more on this later). This article introduces two regularization strategies that impose constraining terms on the results of loss functions. The loss function is a method that quantifies ‘how well’ a machine learning model performs. The quantification is an output(cost) based on a set of inputs, which are referred to as parameter values. The parameter values are used to estimate a prediction, and the ‘loss’ is the difference between the predictions and the actual values. This article won’t focus on the maths of regularization. Instead, this article presents some standard regularization methods and how to implement them within neural networks using TensorFlow(Keras). For more details on the maths, these article by Raimi Karim and Renu Khandelwal present L1 and L2 regularization maths reasonably. medium.com towardsdatascience.com From the previous section, we can understand that the regularization technique acts on the weights parameters within neural networks. More specifically, it modifies the result loss function, which in turn modifies the weight values produced. L1 regularization effect on the neural network weight values is that it penalizes weight values that are close to 0 by making them equal to 0. Negative weight values also take a value of 0; so if a weight value is -2, under the effect of L1 regularization, it becomes 0. The general intuition with L1 regularization is that, if a weight value is close to 0 or very small, then it’s negligible when it comes to the overall performance of the model, therefore making it 0 does not affect the model’s performance and can reduce the memory capacity of the model. L1 penalizes the sum of the absolute values of the weights (|weight|) I know I said I wouldn’t get into the maths, but the mathematical notation below should be relatively easy to understand. We have our loss function, in this case, Mean squared error. Then we add the product of the sum of the absolute values of the weights and the regularization hyperparameter value, represented by the lambda symbol (). ‘i’ in the mathematical notation represent the index of the current weight, and ’n’ represents the total number of weights values within the layer. ‘W’ represents the weight value. L2 regularization also penalizes weight values. For both small weight values and relatively large ones, L2 regularization transforms the values to a number close to 0, but not quite 0. l2 penalizes the sum of the square of the weights (weight2) If you were to combine the effect of L1 and L2 regularization techniques, then you would arrive at ‘Elastic Net regularization’. Regularization techniques effect is imposed on the neural network during training and not inference. Now we have some basic understanding of regularization(feel free to explore the maths of both methods) and some examples, let’s see how they are implemented. The first step is to import tools and libraries that are utilized to either implement or support the implementation of the neural network. TensorFlow: An open-source platform for the implementation, training, and deployment of machine learning models. Keras: An open-source library used for the implementation of neural network architectures that run on both CPUs and GPUs. import tensorflow as tffrom tensorflow import keras The dataset we’ll be utilizing is the trivial fashion-MNIST dataset. The fashion-MNIST dataset contains 70,000 images of clothing. More specifically, it includes 60,000 training examples and 10,000 testing examples, that are all grayscale images with dimension 28 x 28 categorized into ten classes. Preparation of the dataset includes the normalization of the training image and test images by dividing each pixel value by 255.0. This places the pixel value within the range 0 and 1. A validation portion of the dataset is also created at this stage. This group of the dataset is utilized during training to assess the performance of the network at various iterations. (train_images, train_labels),(test_images, test_labels) = keras.datasets.fashion_mnist.load_data()train_images = train_images / 255.0test_images = test_images / 255.0validation_images = train_images[:5000]validation_labels = train_labels[:5000] Next, we implement a simple model using the Keras Sequential API. The hidden layers in our model have a variety of regularization techniques used. To add a regularizer to a layer, you simply have to pass in the prefered regularization technique to the layer’s keyword argument ‘kernel_regularizer’. The Keras regularization implementation methods can provide a parameter that represents the regularization hyperparameter value. This is shown in some of the layers below. Keras provides an implementation of the l1 and l2 regularizers that we will utilize in some of the hidden layers in the code snippet below. Also, we include a layer that leverages both l1 and l2 regularization. And that’s all there is to implementing various regularization techniques within neural networks. Not too difficult. model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28,28]), keras.layers.Dense(200, activation='relu', kernel_regularizer=keras.regularizers.l1()), keras.layers.Dense(100, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)), keras.layers.Dense(50, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.01)), keras.layers.Dense(10, activation='softmax')]) In the next snippet of code we set and specify the optimization algorithm used to train the implemented neural network; along with the loss function and hyperparameters such as learning rate and the number of epochs. sgd = keras.optimizers.SGD(lr=0.01)model.compile(loss="sparse_categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])model.fit(train_images, train_labels, epochs=60, validation_data=(validation_images, validation_labels)) The evaluation of the model performance is conducted using the test data set aside earlier. With evaluation results, you can decide to fine-tune the network hyperparameters or move forward to production after observing the accuracy of the evaluation over the test dataset. model.evaluate(test_images, test_labels) The implemented model will probably have a better performance on the test dataset if the regularization terms on the loss function were excluded from the layers and trained for the same number of epochs. Regularization is more commonly utilized in a deeper neural network with millions of parameters and more features. I hope you the reader now have an intuition on the variety of regularization techniques and how they can be implemented. It might be of interest to explore other regularization methods within neural network implementation and training, such as Dropout or Early Stopping. Below is the GitHub repository for the code included in this article.
[ { "code": null, "e": 405, "s": 171, "text": "Deep Neural Networks(DNN) have a vast amount of weights parameters internal to the architecture that learn a range of values. These range of values are the essential key to enabling the neural network to solve huge complex functions." }, { "code": null, "e": 663, "s": 405, "text": "The deeper a neural network is, the more representational power it possesses, but, there is a shortcoming that occurs as the number of weight parameter increases. This shortcoming is that the neural network is more prone to overfitting the training dataset." }, { "code": null, "e": 1195, "s": 663, "text": "Overfitting: This problem involves the algorithm predicting new instances of patterns presented to it, based too closely on instances of patterns it observed and learnt during training. This can cause the machine-learning algorithm to not generalize accurately to unseen data. Overfitting can occur if the training data does not accurately represent the distribution of test data. Overfitting can be fixed by reducing the number of features in the training data and reducing the complexity of the network through various techniques" }, { "code": null, "e": 1380, "s": 1195, "text": "Regularization techniques reduce the possibility of a neural network overfitting by constraining the range of values that the weight values within the network hold(more on this later)." }, { "code": null, "e": 1499, "s": 1380, "text": "This article introduces two regularization strategies that impose constraining terms on the results of loss functions." }, { "code": null, "e": 1834, "s": 1499, "text": "The loss function is a method that quantifies ‘how well’ a machine learning model performs. The quantification is an output(cost) based on a set of inputs, which are referred to as parameter values. The parameter values are used to estimate a prediction, and the ‘loss’ is the difference between the predictions and the actual values." }, { "code": null, "e": 2033, "s": 1834, "text": "This article won’t focus on the maths of regularization. Instead, this article presents some standard regularization methods and how to implement them within neural networks using TensorFlow(Keras)." }, { "code": null, "e": 2164, "s": 2033, "text": "For more details on the maths, these article by Raimi Karim and Renu Khandelwal present L1 and L2 regularization maths reasonably." }, { "code": null, "e": 2175, "s": 2164, "text": "medium.com" }, { "code": null, "e": 2198, "s": 2175, "text": "towardsdatascience.com" }, { "code": null, "e": 2440, "s": 2198, "text": "From the previous section, we can understand that the regularization technique acts on the weights parameters within neural networks. More specifically, it modifies the result loss function, which in turn modifies the weight values produced." }, { "code": null, "e": 2711, "s": 2440, "text": "L1 regularization effect on the neural network weight values is that it penalizes weight values that are close to 0 by making them equal to 0. Negative weight values also take a value of 0; so if a weight value is -2, under the effect of L1 regularization, it becomes 0." }, { "code": null, "e": 2999, "s": 2711, "text": "The general intuition with L1 regularization is that, if a weight value is close to 0 or very small, then it’s negligible when it comes to the overall performance of the model, therefore making it 0 does not affect the model’s performance and can reduce the memory capacity of the model." }, { "code": null, "e": 3069, "s": 2999, "text": "L1 penalizes the sum of the absolute values of the weights (|weight|)" }, { "code": null, "e": 3191, "s": 3069, "text": "I know I said I wouldn’t get into the maths, but the mathematical notation below should be relatively easy to understand." }, { "code": null, "e": 3252, "s": 3191, "text": "We have our loss function, in this case, Mean squared error." }, { "code": null, "e": 3407, "s": 3252, "text": "Then we add the product of the sum of the absolute values of the weights and the regularization hyperparameter value, represented by the lambda symbol ()." }, { "code": null, "e": 3588, "s": 3407, "text": "‘i’ in the mathematical notation represent the index of the current weight, and ’n’ represents the total number of weights values within the layer. ‘W’ represents the weight value." }, { "code": null, "e": 3773, "s": 3588, "text": "L2 regularization also penalizes weight values. For both small weight values and relatively large ones, L2 regularization transforms the values to a number close to 0, but not quite 0." }, { "code": null, "e": 3833, "s": 3773, "text": "l2 penalizes the sum of the square of the weights (weight2)" }, { "code": null, "e": 3962, "s": 3833, "text": "If you were to combine the effect of L1 and L2 regularization techniques, then you would arrive at ‘Elastic Net regularization’." }, { "code": null, "e": 4063, "s": 3962, "text": "Regularization techniques effect is imposed on the neural network during training and not inference." }, { "code": null, "e": 4221, "s": 4063, "text": "Now we have some basic understanding of regularization(feel free to explore the maths of both methods) and some examples, let’s see how they are implemented." }, { "code": null, "e": 4360, "s": 4221, "text": "The first step is to import tools and libraries that are utilized to either implement or support the implementation of the neural network." }, { "code": null, "e": 4473, "s": 4360, "text": "TensorFlow: An open-source platform for the implementation, training, and deployment of machine learning models." }, { "code": null, "e": 4595, "s": 4473, "text": "Keras: An open-source library used for the implementation of neural network architectures that run on both CPUs and GPUs." }, { "code": null, "e": 4647, "s": 4595, "text": "import tensorflow as tffrom tensorflow import keras" }, { "code": null, "e": 4716, "s": 4647, "text": "The dataset we’ll be utilizing is the trivial fashion-MNIST dataset." }, { "code": null, "e": 4946, "s": 4716, "text": "The fashion-MNIST dataset contains 70,000 images of clothing. More specifically, it includes 60,000 training examples and 10,000 testing examples, that are all grayscale images with dimension 28 x 28 categorized into ten classes." }, { "code": null, "e": 5131, "s": 4946, "text": "Preparation of the dataset includes the normalization of the training image and test images by dividing each pixel value by 255.0. This places the pixel value within the range 0 and 1." }, { "code": null, "e": 5316, "s": 5131, "text": "A validation portion of the dataset is also created at this stage. This group of the dataset is utilized during training to assess the performance of the network at various iterations." }, { "code": null, "e": 5561, "s": 5316, "text": "(train_images, train_labels),(test_images, test_labels) = keras.datasets.fashion_mnist.load_data()train_images = train_images / 255.0test_images = test_images / 255.0validation_images = train_images[:5000]validation_labels = train_labels[:5000]" }, { "code": null, "e": 5708, "s": 5561, "text": "Next, we implement a simple model using the Keras Sequential API. The hidden layers in our model have a variety of regularization techniques used." }, { "code": null, "e": 5860, "s": 5708, "text": "To add a regularizer to a layer, you simply have to pass in the prefered regularization technique to the layer’s keyword argument ‘kernel_regularizer’." }, { "code": null, "e": 6032, "s": 5860, "text": "The Keras regularization implementation methods can provide a parameter that represents the regularization hyperparameter value. This is shown in some of the layers below." }, { "code": null, "e": 6243, "s": 6032, "text": "Keras provides an implementation of the l1 and l2 regularizers that we will utilize in some of the hidden layers in the code snippet below. Also, we include a layer that leverages both l1 and l2 regularization." }, { "code": null, "e": 6360, "s": 6243, "text": "And that’s all there is to implementing various regularization techniques within neural networks. Not too difficult." }, { "code": null, "e": 6774, "s": 6360, "text": "model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28,28]), keras.layers.Dense(200, activation='relu', kernel_regularizer=keras.regularizers.l1()), keras.layers.Dense(100, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)), keras.layers.Dense(50, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.01)), keras.layers.Dense(10, activation='softmax')])" }, { "code": null, "e": 6991, "s": 6774, "text": "In the next snippet of code we set and specify the optimization algorithm used to train the implemented neural network; along with the loss function and hyperparameters such as learning rate and the number of epochs." }, { "code": null, "e": 7221, "s": 6991, "text": "sgd = keras.optimizers.SGD(lr=0.01)model.compile(loss=\"sparse_categorical_crossentropy\", optimizer=sgd, metrics=[\"accuracy\"])model.fit(train_images, train_labels, epochs=60, validation_data=(validation_images, validation_labels))" }, { "code": null, "e": 7313, "s": 7221, "text": "The evaluation of the model performance is conducted using the test data set aside earlier." }, { "code": null, "e": 7494, "s": 7313, "text": "With evaluation results, you can decide to fine-tune the network hyperparameters or move forward to production after observing the accuracy of the evaluation over the test dataset." }, { "code": null, "e": 7535, "s": 7494, "text": "model.evaluate(test_images, test_labels)" }, { "code": null, "e": 7739, "s": 7535, "text": "The implemented model will probably have a better performance on the test dataset if the regularization terms on the loss function were excluded from the layers and trained for the same number of epochs." }, { "code": null, "e": 7854, "s": 7739, "text": "Regularization is more commonly utilized in a deeper neural network with millions of parameters and more features." }, { "code": null, "e": 7975, "s": 7854, "text": "I hope you the reader now have an intuition on the variety of regularization techniques and how they can be implemented." }, { "code": null, "e": 8125, "s": 7975, "text": "It might be of interest to explore other regularization methods within neural network implementation and training, such as Dropout or Early Stopping." } ]
SOAP - Fault
If an error occurs during processing, the response to a SOAP message is a SOAP fault element in the body of the message, and the fault is returned to the sender of the SOAP message. The SOAP fault mechanism returns specific information about the error, including a predefined code, a description, and the address of the SOAP processor that generated the fault. A SOAP message can carry only one fault block. A SOAP message can carry only one fault block. Fault is an optional part of a SOAP message. Fault is an optional part of a SOAP message. For HTTP binding, a successful response is linked to the 200 to 299 range of status codes. For HTTP binding, a successful response is linked to the 200 to 299 range of status codes. SOAP Fault is linked to the 500 to 599 range of status codes. SOAP Fault is linked to the 500 to 599 range of status codes. The SOAP Fault has the following sub elements − <faultCode> It is a text code used to indicate a class of errors. See the next Table for a listing of predefined fault codes. <faultString> It is a text message explaining the error. <faultActor> It is a text string indicating who caused the fault. It is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needs to know which node caused the error. A node that does not act as the ultimate destination must include a faultActor element. <detail> It is an element used to carry application-specific error messages. The detail element can contain child elements called detail entries. The faultCode values defined below must be used in the faultcode element while describing faults. SOAP-ENV:VersionMismatch Found an invalid namespace for the SOAP Envelope element. SOAP-ENV:MustUnderstand An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood. SOAP-ENV:Client The message was incorrectly formed or contained incorrect information. SOAP-ENV:Server There was a problem with the server, so the message could not proceed. The following code is a sample Fault. The client has requested a method named ValidateCreditCard, but the service does not support such a method. This represents a client request error, and the server returns the following SOAP response − <?xml version = '1.0' encoding = 'UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi = "http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/1999/XMLSchema"> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode xsi:type = "xsd:string">SOAP-ENV:Client</faultcode> <faultstring xsi:type = "xsd:string"> Failed to locate method (ValidateCreditCard) in class (examplesCreditCard) at /usr/local/ActivePerl-5.6/lib/site_perl/5.6.0/SOAP/Lite.pm line 1555. </faultstring> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope> 8 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 1896, "s": 1714, "text": "If an error occurs during processing, the response to a SOAP message is a SOAP fault element in the body of the message, and the fault is returned to the sender of the SOAP message." }, { "code": null, "e": 2075, "s": 1896, "text": "The SOAP fault mechanism returns specific information about the error, including a predefined code, a description, and the address of the SOAP processor that generated the fault." }, { "code": null, "e": 2122, "s": 2075, "text": "A SOAP message can carry only one fault block." }, { "code": null, "e": 2169, "s": 2122, "text": "A SOAP message can carry only one fault block." }, { "code": null, "e": 2214, "s": 2169, "text": "Fault is an optional part of a SOAP message." }, { "code": null, "e": 2259, "s": 2214, "text": "Fault is an optional part of a SOAP message." }, { "code": null, "e": 2350, "s": 2259, "text": "For HTTP binding, a successful response is linked to the 200 to 299 range of status codes." }, { "code": null, "e": 2441, "s": 2350, "text": "For HTTP binding, a successful response is linked to the 200 to 299 range of status codes." }, { "code": null, "e": 2503, "s": 2441, "text": "SOAP Fault is linked to the 500 to 599 range of status codes." }, { "code": null, "e": 2565, "s": 2503, "text": "SOAP Fault is linked to the 500 to 599 range of status codes." }, { "code": null, "e": 2613, "s": 2565, "text": "The SOAP Fault has the following sub elements −" }, { "code": null, "e": 2625, "s": 2613, "text": "<faultCode>" }, { "code": null, "e": 2739, "s": 2625, "text": "It is a text code used to indicate a class of errors. See the next Table for a listing of predefined fault codes." }, { "code": null, "e": 2753, "s": 2739, "text": "<faultString>" }, { "code": null, "e": 2796, "s": 2753, "text": "It is a text message explaining the error." }, { "code": null, "e": 2809, "s": 2796, "text": "<faultActor>" }, { "code": null, "e": 3097, "s": 2809, "text": "It is a text string indicating who caused the fault. It is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needs to know which node caused the error. A node that does not act as the ultimate destination must include a faultActor element." }, { "code": null, "e": 3106, "s": 3097, "text": "<detail>" }, { "code": null, "e": 3243, "s": 3106, "text": "It is an element used to carry application-specific error messages. The detail element can contain child elements called detail entries." }, { "code": null, "e": 3341, "s": 3243, "text": "The faultCode values defined below must be used in the faultcode element while describing faults." }, { "code": null, "e": 3366, "s": 3341, "text": "SOAP-ENV:VersionMismatch" }, { "code": null, "e": 3424, "s": 3366, "text": "Found an invalid namespace for the SOAP Envelope element." }, { "code": null, "e": 3448, "s": 3424, "text": "SOAP-ENV:MustUnderstand" }, { "code": null, "e": 3564, "s": 3448, "text": "An immediate child element of the Header element, with the mustUnderstand attribute set to \"1\", was not understood." }, { "code": null, "e": 3580, "s": 3564, "text": "SOAP-ENV:Client" }, { "code": null, "e": 3651, "s": 3580, "text": "The message was incorrectly formed or contained incorrect information." }, { "code": null, "e": 3667, "s": 3651, "text": "SOAP-ENV:Server" }, { "code": null, "e": 3738, "s": 3667, "text": "There was a problem with the server, so the message could not proceed." }, { "code": null, "e": 3977, "s": 3738, "text": "The following code is a sample Fault. The client has requested a method named ValidateCreditCard, but the service does not support such a method. This represents a client request error, and the server returns the following SOAP response −" }, { "code": null, "e": 4639, "s": 3977, "text": "<?xml version = '1.0' encoding = 'UTF-8'?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENV = \"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:xsi = \"http://www.w3.org/1999/XMLSchema-instance\"\n xmlns:xsd = \"http://www.w3.org/1999/XMLSchema\">\n\n <SOAP-ENV:Body>\n <SOAP-ENV:Fault>\n <faultcode xsi:type = \"xsd:string\">SOAP-ENV:Client</faultcode>\n <faultstring xsi:type = \"xsd:string\">\n Failed to locate method (ValidateCreditCard) in class (examplesCreditCard) at\n /usr/local/ActivePerl-5.6/lib/site_perl/5.6.0/SOAP/Lite.pm line 1555.\n </faultstring>\n </SOAP-ENV:Fault>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 4671, "s": 4639, "text": "\n 8 Lectures \n 4 hours \n" }, { "code": null, "e": 4688, "s": 4671, "text": " Frahaan Hussain" }, { "code": null, "e": 4695, "s": 4688, "text": " Print" }, { "code": null, "e": 4706, "s": 4695, "text": " Add Notes" } ]
Difference between Inter and Intra Frame Compression - GeeksforGeeks
24 Nov, 2021 In Compression, we reduce the size of our data to achieve high efficiency and easy storage. It is quite cumbersome to transfer files having large size so we need to compress it. Compressed file takes less time for data transmission and reduce the cost of storage. Compression Ratio = B1 / B2 where, B1 = Total Numbers of bits required to represent data before compression B2 = Total Numbers of bits required to represent data after compression There are 2 main types of compression: Inter Frame Compression Intra Frame Compression Inter Frame Compression Intra Frame Compression Difference between Inter and Intra Frame Compression : Inter Frame Compression Intra Frame Compression A few popular inter frame codec are: H.264-A variant of MPEG-4MPEG-4MPEG-2AVCHD-A variant of H.264 AVCXDCAM-Sony’s babyXAVC-Sony’s new baby H.264-A variant of MPEG-4 MPEG-4 MPEG-2 AVCHD-A variant of H.264 AVC XDCAM-Sony’s baby XAVC-Sony’s new baby A few popular intra frame codec are: MJPEG-JPEGS bunched togetherProres-Apple’s favoriteDN*HD-Avid’s babyALL-I-Found in the newer DSLRsCinema DNG-Adobe’s baby for raw image sequences. MJPEG-JPEGS bunched together Prores-Apple’s favorite DN*HD-Avid’s baby ALL-I-Found in the newer DSLRs Cinema DNG-Adobe’s baby for raw image sequences. mikeyj125 Computer Networks Difference Between Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) GSM in Wireless Communication Intrusion Detection System (IDS) Secure Socket Layer (SSL) Multiple Access Protocols in Computer Network Difference between BFS and DFS Class method vs Static method in Python Difference between var, let and const keywords in JavaScript Differences between Black Box Testing vs White Box Testing Stack vs Heap Memory Allocation
[ { "code": null, "e": 24510, "s": 24482, "text": "\n24 Nov, 2021" }, { "code": null, "e": 24775, "s": 24510, "text": "In Compression, we reduce the size of our data to achieve high efficiency and easy storage. It is quite cumbersome to transfer files having large size so we need to compress it. Compressed file takes less time for data transmission and reduce the cost of storage. " }, { "code": null, "e": 24804, "s": 24775, "text": "Compression Ratio = B1 / B2 " }, { "code": null, "e": 24957, "s": 24804, "text": "where, B1 = Total Numbers of bits required to represent data before compression B2 = Total Numbers of bits required to represent data after compression " }, { "code": null, "e": 24998, "s": 24957, "text": "There are 2 main types of compression: " }, { "code": null, "e": 25047, "s": 24998, "text": "Inter Frame Compression Intra Frame Compression " }, { "code": null, "e": 25072, "s": 25047, "text": "Inter Frame Compression " }, { "code": null, "e": 25097, "s": 25072, "text": "Intra Frame Compression " }, { "code": null, "e": 25153, "s": 25097, "text": "Difference between Inter and Intra Frame Compression : " }, { "code": null, "e": 25177, "s": 25153, "text": "Inter Frame Compression" }, { "code": null, "e": 25201, "s": 25177, "text": "Intra Frame Compression" }, { "code": null, "e": 25239, "s": 25201, "text": "A few popular inter frame codec are: " }, { "code": null, "e": 25342, "s": 25239, "text": "H.264-A variant of MPEG-4MPEG-4MPEG-2AVCHD-A variant of H.264 AVCXDCAM-Sony’s babyXAVC-Sony’s new baby" }, { "code": null, "e": 25368, "s": 25342, "text": "H.264-A variant of MPEG-4" }, { "code": null, "e": 25375, "s": 25368, "text": "MPEG-4" }, { "code": null, "e": 25382, "s": 25375, "text": "MPEG-2" }, { "code": null, "e": 25411, "s": 25382, "text": "AVCHD-A variant of H.264 AVC" }, { "code": null, "e": 25429, "s": 25411, "text": "XDCAM-Sony’s baby" }, { "code": null, "e": 25450, "s": 25429, "text": "XAVC-Sony’s new baby" }, { "code": null, "e": 25489, "s": 25450, "text": "A few popular intra frame codec are: " }, { "code": null, "e": 25638, "s": 25489, "text": "MJPEG-JPEGS bunched togetherProres-Apple’s favoriteDN*HD-Avid’s babyALL-I-Found in the newer DSLRsCinema DNG-Adobe’s baby for raw image sequences. " }, { "code": null, "e": 25667, "s": 25638, "text": "MJPEG-JPEGS bunched together" }, { "code": null, "e": 25691, "s": 25667, "text": "Prores-Apple’s favorite" }, { "code": null, "e": 25709, "s": 25691, "text": "DN*HD-Avid’s baby" }, { "code": null, "e": 25740, "s": 25709, "text": "ALL-I-Found in the newer DSLRs" }, { "code": null, "e": 25791, "s": 25740, "text": "Cinema DNG-Adobe’s baby for raw image sequences. " }, { "code": null, "e": 25803, "s": 25793, "text": "mikeyj125" }, { "code": null, "e": 25821, "s": 25803, "text": "Computer Networks" }, { "code": null, "e": 25840, "s": 25821, "text": "Difference Between" }, { "code": null, "e": 25858, "s": 25840, "text": "Computer Networks" }, { "code": null, "e": 25956, "s": 25858, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25965, "s": 25956, "text": "Comments" }, { "code": null, "e": 25978, "s": 25965, "text": "Old Comments" }, { "code": null, "e": 26013, "s": 25978, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 26043, "s": 26013, "text": "GSM in Wireless Communication" }, { "code": null, "e": 26076, "s": 26043, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 26102, "s": 26076, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 26148, "s": 26102, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 26179, "s": 26148, "text": "Difference between BFS and DFS" }, { "code": null, "e": 26219, "s": 26179, "text": "Class method vs Static method in Python" }, { "code": null, "e": 26280, "s": 26219, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26339, "s": 26280, "text": "Differences between Black Box Testing vs White Box Testing" } ]
Socket.IO - Quick Guide
Socket.IO is a JavaScript library for real-time web applications. It enables real-time, bi-directional communication between web clients and servers. It has two parts − a client-side library that runs in the browser, and a server-side library for node.js. Both components have an identical API. A real-time application (RTA) is an application that functions within a period that the user senses as immediate or current. Some examples of real-time applications are − Instant messengers − Chat apps like Whatsapp, Facebook Messenger, etc. You need not refresh your app/website to receive new messages. Instant messengers − Chat apps like Whatsapp, Facebook Messenger, etc. You need not refresh your app/website to receive new messages. Push Notifications − When someone tags you in a picture on Facebook, you receive a notification instantly. Push Notifications − When someone tags you in a picture on Facebook, you receive a notification instantly. Collaboration Applications − Apps like google docs, which allow multiple people to update same documents simultaneously and apply changes to all people's instances. Collaboration Applications − Apps like google docs, which allow multiple people to update same documents simultaneously and apply changes to all people's instances. Online Gaming − Games like Counter Strike, Call of Duty, etc., are also some examples of real-time applications. Online Gaming − Games like Counter Strike, Call of Duty, etc., are also some examples of real-time applications. Writing a real-time application with popular web applications stacks like LAMP (PHP) has traditionally been very hard. It involves polling the server for changes, keeping track of timestamps, and it is a lot slower than it should be. Sockets have traditionally been the solution around which most real-time systems are architected, providing a bi-directional communication channel between a client and a server. This means that the server can push messages to clients. Whenever an event occurs, the idea is that the server will get it and push it to the concerned connected clients. Socket.IO is quite popular, it is used by Microsoft Office, Yammer, Zendesk, Trello,. and numerous other organizations to build robust real-time systems. It one of the most powerful JavaScript frameworks on GitHub, and most depended-upon NPM (Node Package Manager) module. Socket.IO also has a huge community, which means finding help is quite easy. We will be using express to build the web server that Socket.IO will work with. Any other node-server-side framework or even node HTTP server can be used. However, ExpressJS makes it easy to define routes and other things. To read more about express and get a basic idea about it, head to – ExpressJS tutorial. To get started with developing using the Socket.IO, you need to have Node and npm (node package manager) installed. If you do not have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. node --version npm --version You should get an output similar to − v14.17.0 6.14.13Open your terminal and enter the following in your terminal to create a new folder and enter the following commands − $ mkdir test-project $ cd test-proect $ npm init It will ask you some questions; answer them in the following way − This will create a 'package.json node.js' configuration file. Now we need to install Express and Socket.IO. To install these and save them to package.json file, enter the following command in your terminal, into the project directory − npm install --save express socket.io One final thing is that we should keep restarting the server. When we make changes, we will need a tool called nodemon. To install nodemon, open your terminal and enter the following command − npm install -g nodemon Whenever you need to start the server, instead of using the node app.js use, nodemon app.js. This will ensure that you do not need to restart the server whenever you change a file. It speeds up the development process. Now, we have our development environment set up. Let us now get started with developing real-time applications with Socket.IO. In the following chapter we will discuss the basic example using Socket.IO library along with ExpressJS. First of all, create a file called app.js and enter the following code to set up an express application − var app = require('express')(); var http = require('http').Server(app); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); We will need an index.html file to serve, create a new file called index.html and enter the following code in it − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <body>Hello world</body> </html> To test if this works, go to the terminal and run this app using the following command − nodemon app.js This will run the server on localhost:3000. Go to the browser and enter localhost:3000 to check this. If everything goes well a message saying "Hello World" is printed on the page. Following is another example (this require Socket.IO), it will log "A user connected", every time a user goes to this page and "A user disconnected", every time someone navigates away/closes this page. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); //Whenever someone connects this gets executed io.on('connection', function(socket){ console.log('A user connected'); //Whenever someone disconnects this piece of code executed socket.on('disconnect', function () { console.log('A user disconnected'); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); The require('socket.io')(http) creates a new socket.io instance attached to the http server. The io.on event handler handles connection, disconnection, etc., events in it, using the socket object. We have set up our server to log messages on connections and disconnections. We now have to include the client script and initialize the socket object there, so that clients can establish connections when required. The script is served by our io server at '/socket.io/socket.io.js'. After completing the above procedure, the index.html file will look as follows − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); </script> <body>Hello world</body> </html> If you go to localhost:3000 now (make sure your server is running), you will get Hello World printed in your browser. Now check your server console logs, it will show the following message − A user connected If you refresh your browser, it will disconnect the socket connection and recreate. You can see the following on your console logs − A user connected A user disconnected A user connected Sockets work based on events. There are some reserved events, which can be accessed using the socket object on the server side. These are − Connect Message Disconnect Reconnect Ping Join and Leave. The client-side socket object also provides us with some reserved events, which are − Connect Connect_error Connect_timeout Reconnect, etc. Now, let us see an example to handle events using SocketIO library. In the Hello World example, we used the connection and disconnection events to log when a user connected and left. Now we will be using the message event to pass message from the server to the client. To do this, modify the io.on ('connection', function(socket)) as shown below –var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); io.on('connection', function(socket){ console.log('A user connected'); // Send a message after a timeout of 4seconds setTimeout(function(){ socket.send('Sent a message 4seconds after connection!'); }, 4000); socket.on('disconnect', function () { console.log('A user disconnected'); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); This will send an event called message(built in) to our client, four seconds after the client connects. The send function on socket object associates the 'message' event. Now, we need to handle this event on our client side, to do so, replace the contents of the index.html page with the following − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('message', function(data){document.write(data)}); </script> <body>Hello world</body> </html> We are now handling the 'message' event on the client. When you go to the page in your browser now, you will be presented with the following screenshot. After 4 seconds pass and the server sends the message event, our client will handle it and produce the following output − Note − We sent a string of text here; we can also send an object in any event. Message was a built-in event provided by the API, but is of not much use in a real application, as we need to be able to differentiate between events. To allow this, Socket.IO provides us the ability to create custom events. You can create and fire custom events using the socket.emit function. Following code emits an event called testerEvent − var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); io.on('connection', function(socket){ console.log('A user connected'); // Send a message when setTimeout(function(){ // Sending an object when emmiting an event socket.emit('testerEvent', { description: 'A custom event named testerEvent!'}); }, 4000); socket.on('disconnect', function () { console.log('A user disconnected'); }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); To handle this custom event on client we need a listener that listens for the event testerEvent. The following code handles this event on the client − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('testerEvent', function(data){document.write(data.description)}); </script> <body>Hello world</body> </html> This will work in the same way as our previous example, with the event being testerEvent in this case. When you open your browser and go to localhost:3000, you'l be greeted with − Hello world After four seconds, this event will be fired and the browser will have the text changed to − A custom event named testerEvent! We can also emit events from the client. To emit an event from your client, use the emit function on the socket object. <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.emit('clientEvent', 'Sent an event from the client!'); </script> <body>Hello world</body> </html> To handle these events, use the on function on the socket object on your server. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); io.on('connection', function(socket){ socket.on('clientEvent', function(data){ console.log(data); }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); So, now if we go to localhost:3000, we will get a custom event called clientEvent fired. This event will be handled on the server by logging − Sent an event from the client! Broadcasting means sending a message to all connected clients. Broadcasting can be done at multiple levels. We can send the message to all the connected clients, to clients on a namespace and clients in a particular room. To broadcast an event to all the clients, we can use the io.sockets.emit method. Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event). In this example, we will broadcast the number of connected clients to all the users. Update the app.js file to incorporate the following − var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); var clients = 0; io.on('connection', function(socket){ clients++; io.sockets.emit('broadcast',{ description: clients + ' clients connected!'}); socket.on('disconnect', function () { clients--; io.sockets.emit('broadcast',{ description: clients + ' clients connected!'}); }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); On the client side, we just need to handle the broadcast event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('broadcast',function(data){ document.body.innerHTML = ''; document.write(data.description); }); </script> <body>Hello world</body> </html> If you connect four clients, you will get the following result − This was to send an event to everyone. Now, if we want to send an event to everyone, but the client that caused it (in the previous example, it was caused by new clients on connecting), we can use the socket.broadcast.emit. Let us send the new user a welcome message and update the other clients about him/her joining. So, in your app.js file, on connection of client send him a welcome message and broadcast connected client number to all others. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html'); }); var clients = 0; io.on('connection', function(socket){ clients++; socket.emit('newclientconnect',{ description: 'Hey, welcome!'}); socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'}) socket.on('disconnect', function () { clients--; socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'}) }); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); And your html to handle this event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('newclientconnect',function(data){ document.body.innerHTML = ''; document.write(data.description); }); </script> <body>Hello world</body> </html> Now, the newest client gets a welcome message and others get how many clients are connected currently to the server. Socket.IO allows you to "namespace" your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server. Namespaces are created on the server side. However, they are joined by clients by sending a request to the server. The root namespace '/' is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket-object client side are made to the default namespace. For example − var socket = io(); This will connect the client to the default namespace. All events on this namespace connection will be handled by the io object on the server. All the previous examples were utilizing default namespaces to communicate with the server and back. We can create our own custom namespaces. To set up a custom namespace, we can call the 'of' function on the server side − var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html');}); var nsp = io.of('/my-namespace'); nsp.on('connection', function(socket){ console.log('someone connected'); nsp.emit('hi', 'Hello everyone!'); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); Now, to connect a client to this namespace, you need to provide the namespace as an argument to the io constructor call to create a connection and a socket object on client side. For example, to connect to the above namespace, use the following HTML − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io('/my-namespace'); socket.on('hi',function(data){ document.body.innerHTML = ''; document.write(data); }); </script> <body></body> </html> Every time someone connects to this namespace, they will receive a 'hi' event displaying the message "Hello everyone!". Within each namespace, you can also define arbitrary channels that sockets can join and leave. These channels are called rooms. Rooms are used to further-separate concerns. Rooms also share the same socket connection like namespaces. One thing to keep in mind while using rooms is that they can only be joined on the server side. You can call the join method on the socket to subscribe the socket to a given channel/room. For example, let us create rooms called 'room-<room-number>' and join some clients. As soon as this room is full, create another room and join clients there. Note − We are currently doing this on the default namespace, i.e. '/'. You can also implement this in custom namespaces in the same fashion. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile('index.html'); }); var roomno = 1; io.on('connection', function(socket){ socket.join("room-"+roomno); //Send this event to everyone in the room. io.sockets.in("room-"+roomno).emit('connectToRoom', "You are in room no. "+roomno); }) http.listen(3000, function(){ console.log('listening on localhost:3000'); }); Just handle this connectToRoom event on the client. <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); socket.on('connectToRoom',function(data){ document.body.innerHTML = ''; document.write(data); }); </script> <body></body> </html> Now if you connect three clients, the first two will get the following message − You are in room no. 1 To leave a room, you need to call the leave function just as you called the join function on the socket. For example − To leave room 'room-1', socket.leave("room-"+roomno); We have worked on local servers until now, which will almost never give us errors related to connections, timeouts, etc. However, in real life production environments, handling such errors are of utmost importance. Therefore, we will now discuss how we can handle connection errors on the client side. The client API provides us with following built in events − Connect − When the client successfully connects. Connect − When the client successfully connects. Connecting − When the client is in the process of connecting. Connecting − When the client is in the process of connecting. Disconnect − When the client is disconnected. Disconnect − When the client is disconnected. Connect_failed − When the connection to the server fails. Connect_failed − When the connection to the server fails. Error − An error event is sent from the server. Error − An error event is sent from the server. Message − When the server sends a message using the send function. Message − When the server sends a message using the send function. Reconnect − When reconnection to the server is successful. Reconnect − When reconnection to the server is successful. Reconnecting − When the client is in the process of connecting. Reconnecting − When the client is in the process of connecting. Reconnect_failed − When the reconnection attempt fails. Reconnect_failed − When the reconnection attempt fails. To handle errors, we can handle these events using the out-socket object that we created on our client. For example – If we have a connection that fails, we can use the following code to connect to the server again − socket.on('connect_failed', function() { document.write("Sorry, there seems to be an issue with the connection!"); }) Socket.IO uses a very famous debugging module developed by ExpresJS's main author, called debug. Earlier Socket.IO used to log everything to the console making it quite difficult to debug the problem. After the v1.0 release, you can specify what you want to log. The best way to see what information is available is to use the * − DEBUG=* node app.js This will colorize and output everything that happens to your server console. For example, we can consider the following screenshot. Paste this to console, click enter and refresh your page. This will again output everything related to Socket.io to your console. localStorage.debug = '*'; You can limit the output to get the debug info with incoming data from the socket using the following command. localStorage.debug = 'socket.io-client:socket'; You can see the result like the following screenshot, if you use the second statement to log the info − There is a very good blog post related to socket.io debugging here. In this chapter, we will discuss regarding Fallbacks, Connection using Socket.IO, Events and Messages. Socket.IO has a lot of underlying transport mechanisms, which deal with various constraints arising due to cross browser issues, WebSocket implementations, firewalls, port blocking, etc. Though W3C has a defined specification for WebSocket API, it is still lacking in implementation. Socket.IO provides us with fallback mechanisms, which can deal with such issues. If we develop apps using the native API, we have to implement the fallbacks ourselves. Socket.IO covers a large list of fallbacks in the following order − WebSockets FlashSocket XHR long polling XHR multipart streaming XHR polling JSONP polling iframes The Socket.IO connection begins with the handshake. This makes the handshake a special part of the protocol. Apart from the handshake, all the other events and messages in the protocol are transferred over the socket. Socket.IO is intended for use with web applications, and therefore it is assumed that these applications will always be able to use HTTP. It is because of this reasoning that the Socket.IO handshake takes place over HTTP using a POST request on the handshake URI (passed to the connect method). WebSocket native API only sends messages across. Socket.IO provides an addition layer over these messages, which allows us to create events and again helps us develop apps easily by separating the different types of messages sent. The native API sends messages only in plain text. This is also taken care of by Socket.IO. It handles the serialization and deserialization of data for us. We have an official client API for the web. For other clients such as native mobile phones, other application clients also we can use Socket.IO using the following steps. Step 1 − A connection needs to be established using the same connection protocol discussed above. Step 1 − A connection needs to be established using the same connection protocol discussed above. Step 2 − The messages need to be in the same format as specified by Socket.IO. This format enables Socket.IO to determine the type of the message and the data sent in the message and some metadata useful for operation. Step 2 − The messages need to be in the same format as specified by Socket.IO. This format enables Socket.IO to determine the type of the message and the data sent in the message and some metadata useful for operation. The message format is − [type] : [id ('+')] : [endpoint] (: [data] The parameters in the above command are explained below − Type is a single digit integer, specifying what type message it is. Type is a single digit integer, specifying what type message it is. ID is message ID, an incremental integer used for acknowledgements. ID is message ID, an incremental integer used for acknowledgements. Endpoint is the socket endpoint that the message is intended to be delivered to... Endpoint is the socket endpoint that the message is intended to be delivered to... Data is the associated data to be delivered to the socket. In case of messages, it is treated as plain text, for other events, it is treated as JSON. Data is the associated data to be delivered to the socket. In case of messages, it is treated as plain text, for other events, it is treated as JSON. In the next chapter, we will write a chat application in Socket.IO. Now that we are well acquainted with Socket.IO, let us write a chat application, which we can use to chat on different chat rooms. We will allow users to choose a username and allow them to chat using them. So first, let us set up our HTML file to request for a username − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); </script> <body> <input type="text" name="name" value="" placeholder="Enter your name!"> <button type="button" name="button">Let me chat!</button> </body> </html> Now that we have set up our HTML to request for a username, let us create the server to accept connections from the client. We will allow people to send their chosen usernames using the setUsername event. If a user exists, we will respond by a userExists event, else using a userSet event. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html');}); users = []; io.on('connection', function(socket){ console.log('A user connected'); socket.on('setUsername', function(data){ if(users.indexOf(data) > -1){ users.push(data); socket.emit('userSet', {username: data}); } else { socket.emit('userExists', data + ' username is taken! Try some other username.'); } }) }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); We need to send the username to the server when people click on the button. If user exists, we show an error message; else, we show a messaging screen − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); function setUsername(){ socket.emit('setUsername', document.getElementById('name').value); }; var user; socket.on('userExists', function(data){ document.getElementById('error-container').innerHTML = data; }); socket.on('userSet', function(data){ user = data.username; document.body.innerHTML = '<input type="text" id="message">\ <button type="button" name="button" onclick="sendMessage()">Send</button>\ <div id="message-container"></div>'; }); function sendMessage(){ var msg = document.getElementById('message').value; if(msg){ socket.emit('msg', {message: msg, user: user}); } } socket.on('newmsg', function(data){ if(user){ document.getElementById('message-container').innerHTML +='<div><b>' + data.user + '</b>: ' + data.message + '</div>' } }) </script> <body> <div id="error-container"></div> <input id="name" type="text" name="name" value="" placeholder="Enter your name!"> <button type="button" name="button" onclick="setUsername()">Let me chat!</button> </body> </html> Now if you connect two clients with same username, it will give you an error as shown in the screenshot below − Once you have provided an acceptable username, you will be taken to a screen with a message box and a button to send messages. Now, we have to handle and direct the messages to the connected client. For that, modify your app.js file to include the following changes − var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile('E:/test/index.html');}); users = []; io.on('connection', function(socket){ console.log('A user connected'); socket.on('setUsername', function(data){ console.log(data); if(users.indexOf(data) > -1){ socket.emit('userExists', data + ' username is taken! Try some other username.'); } else { users.push(data); socket.emit('userSet', {username: data}); } }); socket.on('msg', function(data){ //Send message to everyone io.sockets.emit('newmsg', data); }) }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); Now connect any number of clients to your server, provide them a username and start chatting! In the following example, we have connected two clients with names Ayush and Harshit and sent some messages from both the clients − 35 Lectures 2.5 hours Nicholas Lever Print Add Notes Bookmark this page
[ { "code": null, "e": 2160, "s": 1865, "text": "Socket.IO is a JavaScript library for real-time web applications. It enables real-time, bi-directional communication between web clients and servers. It has two parts − a client-side library that runs in the browser, and a server-side library for node.js. Both components have an identical API." }, { "code": null, "e": 2285, "s": 2160, "text": "A real-time application (RTA) is an application that functions within a period that the user senses as immediate or current." }, { "code": null, "e": 2331, "s": 2285, "text": "Some examples of real-time applications are −" }, { "code": null, "e": 2465, "s": 2331, "text": "Instant messengers − Chat apps like Whatsapp, Facebook Messenger, etc. You need not refresh your app/website to receive new messages." }, { "code": null, "e": 2599, "s": 2465, "text": "Instant messengers − Chat apps like Whatsapp, Facebook Messenger, etc. You need not refresh your app/website to receive new messages." }, { "code": null, "e": 2706, "s": 2599, "text": "Push Notifications − When someone tags you in a picture on Facebook, you receive a notification instantly." }, { "code": null, "e": 2813, "s": 2706, "text": "Push Notifications − When someone tags you in a picture on Facebook, you receive a notification instantly." }, { "code": null, "e": 2978, "s": 2813, "text": "Collaboration Applications − Apps like google docs, which allow multiple people to update same documents simultaneously and apply changes to all people's instances." }, { "code": null, "e": 3143, "s": 2978, "text": "Collaboration Applications − Apps like google docs, which allow multiple people to update same documents simultaneously and apply changes to all people's instances." }, { "code": null, "e": 3256, "s": 3143, "text": "Online Gaming − Games like Counter Strike, Call of Duty, etc., are also some examples of real-time applications." }, { "code": null, "e": 3369, "s": 3256, "text": "Online Gaming − Games like Counter Strike, Call of Duty, etc., are also some examples of real-time applications." }, { "code": null, "e": 3603, "s": 3369, "text": "Writing a real-time application with popular web applications stacks like LAMP (PHP) has traditionally been very hard. It involves polling the server for changes, keeping track of timestamps, and it is a lot slower than it should be." }, { "code": null, "e": 3952, "s": 3603, "text": "Sockets have traditionally been the solution around which most real-time systems are architected, providing a bi-directional communication channel between a client and a server. This means that the server can push messages to clients. Whenever an event occurs, the idea is that the server will get it and push it to the concerned connected clients." }, { "code": null, "e": 4302, "s": 3952, "text": "Socket.IO is quite popular, it is used by Microsoft Office, Yammer, Zendesk, Trello,. and numerous other organizations to build robust real-time systems. It one of the most powerful JavaScript frameworks on GitHub, and most depended-upon NPM (Node Package Manager) module. Socket.IO also has a huge community, which means finding help is quite easy." }, { "code": null, "e": 4613, "s": 4302, "text": "We will be using express to build the web server that Socket.IO will work with. Any other node-server-side framework or even node HTTP server can be used. However, ExpressJS makes it easy to define routes and other things. To read more about express and get a basic idea about it, head to – ExpressJS tutorial." }, { "code": null, "e": 4909, "s": 4613, "text": "To get started with developing using the Socket.IO, you need to have Node and npm (node package manager) installed. If you do not have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal." }, { "code": null, "e": 4939, "s": 4909, "text": "node --version\nnpm --version\n" }, { "code": null, "e": 4977, "s": 4939, "text": "You should get an output similar to −" }, { "code": null, "e": 4987, "s": 4977, "text": "v14.17.0\n" }, { "code": null, "e": 5112, "s": 4987, "text": "6.14.13Open your terminal and enter the following in your terminal to create a new folder and enter the following commands −" }, { "code": null, "e": 5161, "s": 5112, "text": "$ mkdir test-project\n$ cd test-proect\n$ npm init" }, { "code": null, "e": 5228, "s": 5161, "text": "It will ask you some questions; answer them in the following way −" }, { "code": null, "e": 5464, "s": 5228, "text": "This will create a 'package.json node.js' configuration file. Now we need to install Express and Socket.IO. To install these and save them to package.json file, enter the following command in your terminal, into the project directory −" }, { "code": null, "e": 5502, "s": 5464, "text": "npm install --save express socket.io\n" }, { "code": null, "e": 5695, "s": 5502, "text": "One final thing is that we should keep restarting the server. When we make changes, we will need a tool called nodemon. To install nodemon, open your terminal and enter the following command −" }, { "code": null, "e": 5719, "s": 5695, "text": "npm install -g nodemon\n" }, { "code": null, "e": 5938, "s": 5719, "text": "Whenever you need to start the server, instead of using the node app.js use, nodemon app.js. This will ensure that you do not need to restart the server whenever you change a file. It speeds up the development process." }, { "code": null, "e": 6065, "s": 5938, "text": "Now, we have our development environment set up. Let us now get started with developing real-time applications with Socket.IO." }, { "code": null, "e": 6170, "s": 6065, "text": "In the following chapter we will discuss the basic example using Socket.IO library along with ExpressJS." }, { "code": null, "e": 6276, "s": 6170, "text": "First of all, create a file called app.js and enter the following code to set up an express application −" }, { "code": null, "e": 6499, "s": 6276, "text": "var app = require('express')();\nvar http = require('http').Server(app);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\n\nhttp.listen(3000, function(){\n console.log('listening on *:3000');\n});" }, { "code": null, "e": 6614, "s": 6499, "text": "We will need an index.html file to serve, create a new file called index.html and enter the following code in it −" }, { "code": null, "e": 6716, "s": 6614, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 6805, "s": 6716, "text": "To test if this works, go to the terminal and run this app using the following command −" }, { "code": null, "e": 6821, "s": 6805, "text": "nodemon app.js\n" }, { "code": null, "e": 7002, "s": 6821, "text": "This will run the server on localhost:3000. Go to the browser and enter localhost:3000 to check this. If everything goes well a message saying \"Hello World\" is printed on the page." }, { "code": null, "e": 7204, "s": 7002, "text": "Following is another example (this require Socket.IO), it will log \"A user connected\", every time a user goes to this page and \"A user disconnected\", every time someone navigates away/closes this page." }, { "code": null, "e": 7742, "s": 7204, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){ res.sendFile('E:/test/index.html');\n});\n\n//Whenever someone connects this gets executed\nio.on('connection', function(socket){\n console.log('A user connected');\n \n //Whenever someone disconnects this piece of code executed\n socket.on('disconnect', function () {\n console.log('A user disconnected');\n });\n});\nhttp.listen(3000, function(){\n console.log('listening on *:3000');\n});" }, { "code": null, "e": 7939, "s": 7742, "text": "The require('socket.io')(http) creates a new socket.io instance attached to the http server. The io.on event handler handles connection, disconnection, etc., events in it, using the socket object." }, { "code": null, "e": 8222, "s": 7939, "text": "We have set up our server to log messages on connections and disconnections. We now have to include the client script and initialize the socket object there, so that clients can establish connections when required. The script is served by our io server at '/socket.io/socket.io.js'." }, { "code": null, "e": 8303, "s": 8222, "text": "After completing the above procedure, the index.html file will look as follows −" }, { "code": null, "e": 8506, "s": 8303, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 8697, "s": 8506, "text": "If you go to localhost:3000 now (make sure your server is running), you will get Hello World printed in your browser. Now check your server console logs, it will show the following message −" }, { "code": null, "e": 8715, "s": 8697, "text": "A user connected\n" }, { "code": null, "e": 8848, "s": 8715, "text": "If you refresh your browser, it will disconnect the socket connection and recreate. You can see the following on your console logs −" }, { "code": null, "e": 8903, "s": 8848, "text": "A user connected\nA user disconnected\nA user connected\n" }, { "code": null, "e": 9031, "s": 8903, "text": "Sockets work based on events. There are some reserved events, which can be accessed using the socket object on the server side." }, { "code": null, "e": 9043, "s": 9031, "text": "These are −" }, { "code": null, "e": 9051, "s": 9043, "text": "Connect" }, { "code": null, "e": 9059, "s": 9051, "text": "Message" }, { "code": null, "e": 9070, "s": 9059, "text": "Disconnect" }, { "code": null, "e": 9080, "s": 9070, "text": "Reconnect" }, { "code": null, "e": 9085, "s": 9080, "text": "Ping" }, { "code": null, "e": 9094, "s": 9085, "text": "Join and" }, { "code": null, "e": 9101, "s": 9094, "text": "Leave." }, { "code": null, "e": 9187, "s": 9101, "text": "The client-side socket object also provides us with some reserved events, which are −" }, { "code": null, "e": 9195, "s": 9187, "text": "Connect" }, { "code": null, "e": 9209, "s": 9195, "text": "Connect_error" }, { "code": null, "e": 9225, "s": 9209, "text": "Connect_timeout" }, { "code": null, "e": 9241, "s": 9225, "text": "Reconnect, etc." }, { "code": null, "e": 9309, "s": 9241, "text": "Now, let us see an example to handle events using SocketIO library." }, { "code": null, "e": 10171, "s": 9309, "text": "In the Hello World example, we used the connection and disconnection events to\nlog when a user connected and left. Now we will be using the message event to\npass message from the server to the client. To do this, modify the io.on\n('connection', function(socket)) as shown below –var app =\nrequire('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\n \nio.on('connection', function(socket){\n console.log('A user connected');\n \n // Send a message after a timeout of 4seconds\n setTimeout(function(){\n socket.send('Sent a message 4seconds after connection!');\n }, 4000);\n socket.on('disconnect', function () {\n console.log('A user disconnected');\n });\n});\nhttp.listen(3000, function(){\n console.log('listening on *:3000');\n});" }, { "code": null, "e": 10342, "s": 10171, "text": "This will send an event called message(built in) to our client, four seconds after the client connects. The send function on socket object associates the 'message' event." }, { "code": null, "e": 10471, "s": 10342, "text": "Now, we need to handle this event on our client side, to do so, replace the contents of the index.html page with the following −" }, { "code": null, "e": 10740, "s": 10471, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('message', function(data){document.write(data)});\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 10893, "s": 10740, "text": "We are now handling the 'message' event on the client. When you go to the page in your browser now, you will be presented with the following screenshot." }, { "code": null, "e": 11015, "s": 10893, "text": "After 4 seconds pass and the server sends the message event, our client will handle it and produce the following output −" }, { "code": null, "e": 11094, "s": 11015, "text": "Note − We sent a string of text here; we can also send an object in any event." }, { "code": null, "e": 11245, "s": 11094, "text": "Message was a built-in event provided by the API, but is of not much use in a real application, as we need to be able to differentiate between events." }, { "code": null, "e": 11440, "s": 11245, "text": "To allow this, Socket.IO provides us the ability to create custom events. You can create and fire custom events using the socket.emit function. Following code emits an event called testerEvent −" }, { "code": null, "e": 12081, "s": 11440, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\n \nio.on('connection', function(socket){\n console.log('A user connected');\n // Send a message when\n setTimeout(function(){\n // Sending an object when emmiting an event\n socket.emit('testerEvent', { description: 'A custom event named testerEvent!'});\n }, 4000);\n socket.on('disconnect', function () {\n console.log('A user disconnected');\n });\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 12232, "s": 12081, "text": "To handle this custom event on client we need a listener that listens for the event testerEvent. The following code handles this event on the client −" }, { "code": null, "e": 12517, "s": 12232, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('testerEvent', function(data){document.write(data.description)});\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 12697, "s": 12517, "text": "This will work in the same way as our previous example, with the event being testerEvent in this case. When you open your browser and go to localhost:3000, you'l be greeted with −" }, { "code": null, "e": 12710, "s": 12697, "text": "Hello world\n" }, { "code": null, "e": 12803, "s": 12710, "text": "After four seconds, this event will be fired and the browser will have the text changed to −" }, { "code": null, "e": 12838, "s": 12803, "text": "A custom event named testerEvent!\n" }, { "code": null, "e": 12958, "s": 12838, "text": "We can also emit events from the client. To emit an event from your client, use the emit function on the socket object." }, { "code": null, "e": 13229, "s": 12958, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.emit('clientEvent', 'Sent an event from the client!');\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 13310, "s": 13229, "text": "To handle these events, use the on function on the socket object on your server." }, { "code": null, "e": 13696, "s": 13310, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\nio.on('connection', function(socket){\n socket.on('clientEvent', function(data){\n console.log(data);\n });\n});\n\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 13839, "s": 13696, "text": "So, now if we go to localhost:3000, we will get a custom event called clientEvent fired. This event will be handled on the server by logging −" }, { "code": null, "e": 13871, "s": 13839, "text": "Sent an event from the client!\n" }, { "code": null, "e": 14174, "s": 13871, "text": "Broadcasting means sending a message to all connected clients. Broadcasting can be done at multiple levels. We can send the message to all the connected clients, to clients on a namespace and clients in a particular room. To broadcast an event to all the clients, we can use the io.sockets.emit method." }, { "code": null, "e": 14288, "s": 14174, "text": "Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event)." }, { "code": null, "e": 14427, "s": 14288, "text": "In this example, we will broadcast the number of connected clients to all the users. Update the app.js file to incorporate the following −" }, { "code": null, "e": 15003, "s": 14427, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\n \nvar clients = 0;\n\nio.on('connection', function(socket){\n clients++;\n io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});\n socket.on('disconnect', function () {\n clients--;\n io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});\n });\n});\n\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 15068, "s": 15003, "text": "On the client side, we just need to handle the broadcast event −" }, { "code": null, "e": 15407, "s": 15068, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('broadcast',function(data){\n document.body.innerHTML = '';\n document.write(data.description);\n });\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 15472, "s": 15407, "text": "If you connect four clients, you will get the following result −" }, { "code": null, "e": 15696, "s": 15472, "text": "This was to send an event to everyone. Now, if we want to send an event to everyone, but the client that caused it (in the previous example, it was caused by new clients on connecting), we can use the socket.broadcast.emit." }, { "code": null, "e": 15920, "s": 15696, "text": "Let us send the new user a welcome message and update the other clients about him/her joining. So, in your app.js file, on connection of client send him a welcome message and broadcast connected client number to all others." }, { "code": null, "e": 16583, "s": 15920, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');\n});\nvar clients = 0;\n\nio.on('connection', function(socket){\n clients++;\n socket.emit('newclientconnect',{ description: 'Hey, welcome!'});\n socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'})\n socket.on('disconnect', function () {\n clients--;\n socket.broadcast.emit('newclientconnect',{ description: clients + ' clients connected!'})\n });\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 16620, "s": 16583, "text": "And your html to handle this event −" }, { "code": null, "e": 16978, "s": 16620, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('newclientconnect',function(data){\n document.body.innerHTML = '';\n document.write(data.description);\n });\n </script>\n <body>Hello world</body>\n</html>" }, { "code": null, "e": 17095, "s": 16978, "text": "Now, the newest client gets a welcome message and others get how many clients are connected currently to the server." }, { "code": null, "e": 17518, "s": 17095, "text": "Socket.IO allows you to \"namespace\" your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server." }, { "code": null, "e": 17633, "s": 17518, "text": "Namespaces are created on the server side. However, they are joined by clients by sending a request to the server." }, { "code": null, "e": 17902, "s": 17633, "text": "The root namespace '/' is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket-object client side are made to the default namespace. For example −" }, { "code": null, "e": 17922, "s": 17902, "text": "var socket = io();\n" }, { "code": null, "e": 18166, "s": 17922, "text": "This will connect the client to the default namespace. All events on this namespace connection will be handled by the io object on the server. All the previous examples were utilizing default namespaces to communicate with the server and back." }, { "code": null, "e": 18288, "s": 18166, "text": "We can create our own custom namespaces. To set up a custom namespace, we can call the 'of' function on the server side −" }, { "code": null, "e": 18710, "s": 18288, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');});\n \nvar nsp = io.of('/my-namespace');\nnsp.on('connection', function(socket){\n console.log('someone connected');\n nsp.emit('hi', 'Hello everyone!');\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 18889, "s": 18710, "text": "Now, to connect a client to this namespace, you need to provide the namespace as an argument to the io constructor call to create a connection and a socket object on client side." }, { "code": null, "e": 18962, "s": 18889, "text": "For example, to connect to the above namespace, use the following HTML −" }, { "code": null, "e": 19287, "s": 18962, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io('/my-namespace');\n socket.on('hi',function(data){\n document.body.innerHTML = '';\n document.write(data);\n });\n </script>\n <body></body>\n </html>" }, { "code": null, "e": 19407, "s": 19287, "text": "Every time someone connects to this namespace, they will receive a 'hi' event displaying the message \"Hello everyone!\"." }, { "code": null, "e": 19737, "s": 19407, "text": "Within each namespace, you can also define arbitrary channels that sockets can join and leave. These channels are called rooms. Rooms are used to further-separate concerns. Rooms also share the same socket connection like namespaces. One thing to keep in mind while using rooms is that they can only be joined on the server side." }, { "code": null, "e": 19987, "s": 19737, "text": "You can call the join method on the socket to subscribe the socket to a given channel/room. For example, let us create rooms called 'room-<room-number>' and join some clients. As soon as this room is full, create another room and join clients there." }, { "code": null, "e": 20128, "s": 19987, "text": "Note − We are currently doing this on the default namespace, i.e. '/'. You can also implement this in custom namespaces in the same fashion." }, { "code": null, "e": 20608, "s": 20128, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\napp.get('/', function(req, res){\n res.sendfile('index.html');\n});\nvar roomno = 1;\nio.on('connection', function(socket){\n socket.join(\"room-\"+roomno);\n //Send this event to everyone in the room.\n io.sockets.in(\"room-\"+roomno).emit('connectToRoom', \"You are in room no. \"+roomno);\n})\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 20660, "s": 20608, "text": "Just handle this connectToRoom event on the client." }, { "code": null, "e": 20980, "s": 20660, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n socket.on('connectToRoom',function(data){\n document.body.innerHTML = '';\n document.write(data);\n });\n </script>\n <body></body>\n</html>" }, { "code": null, "e": 21061, "s": 20980, "text": "Now if you connect three clients, the first two will get the following message −" }, { "code": null, "e": 21084, "s": 21061, "text": "You are in room no. 1\n" }, { "code": null, "e": 21189, "s": 21084, "text": "To leave a room, you need to call the leave function just as you called the join function on the socket." }, { "code": null, "e": 21227, "s": 21189, "text": "For example − To leave room 'room-1'," }, { "code": null, "e": 21258, "s": 21227, "text": "socket.leave(\"room-\"+roomno);\n" }, { "code": null, "e": 21560, "s": 21258, "text": "We have worked on local servers until now, which will almost never give us errors related to connections, timeouts, etc. However, in real life production environments, handling such errors are of utmost importance. Therefore, we will now discuss how we can handle connection errors on the client side." }, { "code": null, "e": 21620, "s": 21560, "text": "The client API provides us with following built in events −" }, { "code": null, "e": 21669, "s": 21620, "text": "Connect − When the client successfully connects." }, { "code": null, "e": 21718, "s": 21669, "text": "Connect − When the client successfully connects." }, { "code": null, "e": 21780, "s": 21718, "text": "Connecting − When the client is in the process of connecting." }, { "code": null, "e": 21842, "s": 21780, "text": "Connecting − When the client is in the process of connecting." }, { "code": null, "e": 21888, "s": 21842, "text": "Disconnect − When the client is disconnected." }, { "code": null, "e": 21934, "s": 21888, "text": "Disconnect − When the client is disconnected." }, { "code": null, "e": 21992, "s": 21934, "text": "Connect_failed − When the connection to the server fails." }, { "code": null, "e": 22050, "s": 21992, "text": "Connect_failed − When the connection to the server fails." }, { "code": null, "e": 22098, "s": 22050, "text": "Error − An error event is sent from the server." }, { "code": null, "e": 22146, "s": 22098, "text": "Error − An error event is sent from the server." }, { "code": null, "e": 22213, "s": 22146, "text": "Message − When the server sends a message using the send function." }, { "code": null, "e": 22280, "s": 22213, "text": "Message − When the server sends a message using the send function." }, { "code": null, "e": 22339, "s": 22280, "text": "Reconnect − When reconnection to the server is successful." }, { "code": null, "e": 22398, "s": 22339, "text": "Reconnect − When reconnection to the server is successful." }, { "code": null, "e": 22462, "s": 22398, "text": "Reconnecting − When the client is in the process of connecting." }, { "code": null, "e": 22526, "s": 22462, "text": "Reconnecting − When the client is in the process of connecting." }, { "code": null, "e": 22582, "s": 22526, "text": "Reconnect_failed − When the reconnection attempt fails." }, { "code": null, "e": 22638, "s": 22582, "text": "Reconnect_failed − When the reconnection attempt fails." }, { "code": null, "e": 22742, "s": 22638, "text": "To handle errors, we can handle these events using the out-socket object that we created on our client." }, { "code": null, "e": 22855, "s": 22742, "text": "For example – If we have a connection that fails, we can use the following code to connect to the server again −" }, { "code": null, "e": 22976, "s": 22855, "text": "socket.on('connect_failed', function() {\n document.write(\"Sorry, there seems to be an issue with the connection!\");\n})" }, { "code": null, "e": 23239, "s": 22976, "text": "Socket.IO uses a very famous debugging module developed by ExpresJS's main author, called debug. Earlier Socket.IO used to log everything to the console making it quite difficult to debug the problem. After the v1.0 release, you can specify what you want to log." }, { "code": null, "e": 23307, "s": 23239, "text": "The best way to see what information is available is to use the * −" }, { "code": null, "e": 23328, "s": 23307, "text": "DEBUG=* node app.js\n" }, { "code": null, "e": 23461, "s": 23328, "text": "This will colorize and output everything that happens to your server console. For example, we can consider the following screenshot." }, { "code": null, "e": 23591, "s": 23461, "text": "Paste this to console, click enter and refresh your page. This will again output everything related to Socket.io to your console." }, { "code": null, "e": 23618, "s": 23591, "text": "localStorage.debug = '*';\n" }, { "code": null, "e": 23729, "s": 23618, "text": "You can limit the output to get the debug info with incoming data from the socket using the following command." }, { "code": null, "e": 23778, "s": 23729, "text": "localStorage.debug = 'socket.io-client:socket';\n" }, { "code": null, "e": 23882, "s": 23778, "text": "You can see the result like the following screenshot, if you use the second statement to log the info −" }, { "code": null, "e": 23950, "s": 23882, "text": "There is a very good blog post related to socket.io debugging here." }, { "code": null, "e": 24053, "s": 23950, "text": "In this chapter, we will discuss regarding Fallbacks, Connection using Socket.IO, Events and Messages." }, { "code": null, "e": 24240, "s": 24053, "text": "Socket.IO has a lot of underlying transport mechanisms, which deal with various constraints arising due to cross browser issues, WebSocket implementations, firewalls, port blocking, etc." }, { "code": null, "e": 24573, "s": 24240, "text": "Though W3C has a defined specification for WebSocket API, it is still lacking in implementation. Socket.IO provides us with fallback mechanisms, which can deal with such issues. If we develop apps using the native API, we have to implement the fallbacks ourselves. Socket.IO covers a large list of fallbacks in the following order −" }, { "code": null, "e": 24584, "s": 24573, "text": "WebSockets" }, { "code": null, "e": 24596, "s": 24584, "text": "FlashSocket" }, { "code": null, "e": 24613, "s": 24596, "text": "XHR long polling" }, { "code": null, "e": 24637, "s": 24613, "text": "XHR multipart streaming" }, { "code": null, "e": 24649, "s": 24637, "text": "XHR polling" }, { "code": null, "e": 24663, "s": 24649, "text": "JSONP polling" }, { "code": null, "e": 24671, "s": 24663, "text": "iframes" }, { "code": null, "e": 24889, "s": 24671, "text": "The Socket.IO connection begins with the handshake. This makes the handshake a special part of the protocol. Apart from the handshake, all the other events and messages in the protocol are transferred over the socket." }, { "code": null, "e": 25184, "s": 24889, "text": "Socket.IO is intended for use with web applications, and therefore it is assumed that these applications will always be able to use HTTP. It is because of this reasoning that the Socket.IO handshake takes place over HTTP using a POST request on the handshake URI (passed to the connect method)." }, { "code": null, "e": 25415, "s": 25184, "text": "WebSocket native API only sends messages across. Socket.IO provides an addition layer over these messages, which allows us to create events and again helps us develop apps easily by separating the different types of messages sent." }, { "code": null, "e": 25571, "s": 25415, "text": "The native API sends messages only in plain text. This is also taken care of by Socket.IO. It handles the serialization and deserialization of data for us." }, { "code": null, "e": 25742, "s": 25571, "text": "We have an official client API for the web. For other clients such as native mobile phones, other application clients also we can use Socket.IO using the following steps." }, { "code": null, "e": 25840, "s": 25742, "text": "Step 1 − A connection needs to be established using the same connection protocol discussed above." }, { "code": null, "e": 25938, "s": 25840, "text": "Step 1 − A connection needs to be established using the same connection protocol discussed above." }, { "code": null, "e": 26157, "s": 25938, "text": "Step 2 − The messages need to be in the same format as specified by Socket.IO. This format enables Socket.IO to determine the type of the message and the data sent in the message and some metadata useful for operation." }, { "code": null, "e": 26376, "s": 26157, "text": "Step 2 − The messages need to be in the same format as specified by Socket.IO. This format enables Socket.IO to determine the type of the message and the data sent in the message and some metadata useful for operation." }, { "code": null, "e": 26400, "s": 26376, "text": "The message format is −" }, { "code": null, "e": 26444, "s": 26400, "text": "[type] : [id ('+')] : [endpoint] (: [data]\n" }, { "code": null, "e": 26502, "s": 26444, "text": "The parameters in the above command are explained below −" }, { "code": null, "e": 26570, "s": 26502, "text": "Type is a single digit integer, specifying what type message it is." }, { "code": null, "e": 26638, "s": 26570, "text": "Type is a single digit integer, specifying what type message it is." }, { "code": null, "e": 26706, "s": 26638, "text": "ID is message ID, an incremental integer used for acknowledgements." }, { "code": null, "e": 26774, "s": 26706, "text": "ID is message ID, an incremental integer used for acknowledgements." }, { "code": null, "e": 26857, "s": 26774, "text": "Endpoint is the socket endpoint that the message is intended to be delivered to..." }, { "code": null, "e": 26940, "s": 26857, "text": "Endpoint is the socket endpoint that the message is intended to be delivered to..." }, { "code": null, "e": 27090, "s": 26940, "text": "Data is the associated data to be delivered to the socket. In case of messages, it is treated as plain text, for other events, it is treated as JSON." }, { "code": null, "e": 27240, "s": 27090, "text": "Data is the associated data to be delivered to the socket. In case of messages, it is treated as plain text, for other events, it is treated as JSON." }, { "code": null, "e": 27308, "s": 27240, "text": "In the next chapter, we will write a chat application in Socket.IO." }, { "code": null, "e": 27581, "s": 27308, "text": "Now that we are well acquainted with Socket.IO, let us write a chat application, which we can use to chat on different chat rooms. We will allow users to choose a username and allow them to chat using them. So first, let us set up our HTML file to request for a username −" }, { "code": null, "e": 27919, "s": 27581, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n </script>\n <body>\n <input type=\"text\" name=\"name\" value=\"\" placeholder=\"Enter your name!\">\n <button type=\"button\" name=\"button\">Let me chat!</button>\n </body>\n</html>" }, { "code": null, "e": 28209, "s": 27919, "text": "Now that we have set up our HTML to request for a username, let us create the server to accept connections from the client. We will allow people to send their chosen usernames using the setUsername event. If a user exists, we will respond by a userExists event, else using a userSet event." }, { "code": null, "e": 28842, "s": 28209, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');});\nusers = [];\nio.on('connection', function(socket){\n console.log('A user connected');\n socket.on('setUsername', function(data){\n if(users.indexOf(data) > -1){\n users.push(data);\n socket.emit('userSet', {username: data});\n } else {\n socket.emit('userExists', data + ' username is taken! Try some other username.');\n }\n })\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 28995, "s": 28842, "text": "We need to send the username to the server when people click on the button. If user exists, we show an error message; else, we show a messaging screen −" }, { "code": null, "e": 30351, "s": 28995, "text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io();\n function setUsername(){\n socket.emit('setUsername', document.getElementById('name').value);\n };\n var user;\n socket.on('userExists', function(data){\n document.getElementById('error-container').innerHTML = data;\n });\n socket.on('userSet', function(data){\n user = data.username;\n document.body.innerHTML = '<input type=\"text\" id=\"message\">\\\n <button type=\"button\" name=\"button\" onclick=\"sendMessage()\">Send</button>\\\n <div id=\"message-container\"></div>';\n });\n function sendMessage(){\n var msg = document.getElementById('message').value;\n if(msg){\n socket.emit('msg', {message: msg, user: user});\n }\n }\n socket.on('newmsg', function(data){\n if(user){\n document.getElementById('message-container').innerHTML +='<div><b>' + data.user + '</b>: ' + data.message + '</div>'\n }\n })\n </script>\n <body>\n <div id=\"error-container\"></div>\n <input id=\"name\" type=\"text\" name=\"name\" value=\"\" placeholder=\"Enter your name!\">\n <button type=\"button\" name=\"button\" onclick=\"setUsername()\">Let me chat!</button>\n </body>\n </html>" }, { "code": null, "e": 30463, "s": 30351, "text": "Now if you connect two clients with same username, it will give you an error as shown in the screenshot below −" }, { "code": null, "e": 30731, "s": 30463, "text": "Once you have provided an acceptable username, you will be taken to a screen with a message box and a button to send messages. Now, we have to handle and direct the messages to the connected client. For that, modify your app.js file to include the following changes −" }, { "code": null, "e": 31505, "s": 30731, "text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');});\nusers = [];\nio.on('connection', function(socket){\n console.log('A user connected');\n socket.on('setUsername', function(data){\n console.log(data);\n if(users.indexOf(data) > -1){\n socket.emit('userExists', data + ' username is taken! Try some other username.');\n } else {\n users.push(data);\n socket.emit('userSet', {username: data});\n }\n });\n socket.on('msg', function(data){\n //Send message to everyone\n io.sockets.emit('newmsg', data);\n })\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});" }, { "code": null, "e": 31731, "s": 31505, "text": "Now connect any number of clients to your server, provide them a username and start chatting! In the following example, we have connected two clients with names Ayush and Harshit and sent some messages from both the clients −" }, { "code": null, "e": 31766, "s": 31731, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 31782, "s": 31766, "text": " Nicholas Lever" }, { "code": null, "e": 31789, "s": 31782, "text": " Print" }, { "code": null, "e": 31800, "s": 31789, "text": " Add Notes" } ]
TensorFlow - Basics
In this chapter, we will learn about the basics of TensorFlow. We will begin by understanding the data structure of tensor. Tensors are used as the basic data structures in TensorFlow language. Tensors represent the connecting edges in any flow diagram called the Data Flow Graph. Tensors are defined as multidimensional array or list. Tensors are identified by the following three parameters − Unit of dimensionality described within tensor is called rank. It identifies the number of dimensions of the tensor. A rank of a tensor can be described as the order or n-dimensions of a tensor defined. The number of rows and columns together define the shape of Tensor. Type describes the data type assigned to Tensor’s elements. A user needs to consider the following activities for building a Tensor − Build an n-dimensional array Convert the n-dimensional array. TensorFlow includes various dimensions. The dimensions are described in brief below − One dimensional tensor is a normal array structure which includes one set of values of the same data type. Declaration >>> import numpy as np >>> tensor_1d = np.array([1.3, 1, 4.0, 23.99]) >>> print tensor_1d The implementation with the output is shown in the screenshot below − The indexing of elements is same as Python lists. The first element starts with index of 0; to print the values through index, all you need to do is mention the index number. >>> print tensor_1d[0] 1.3 >>> print tensor_1d[2] 4.0 Sequence of arrays are used for creating “two dimensional tensors”. The creation of two-dimensional tensors is described below − Following is the complete syntax for creating two dimensional arrays − >>> import numpy as np >>> tensor_2d = np.array([(1,2,3,4),(4,5,6,7),(8,9,10,11),(12,13,14,15)]) >>> print(tensor_2d) [[ 1 2 3 4] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] >>> The specific elements of two dimensional tensors can be tracked with the help of row number and column number specified as index numbers. >>> tensor_2d[3][2] 14 In this section, we will learn about Tensor Handling and Manipulations. To begin with, let us consider the following code − import tensorflow as tf import numpy as np matrix1 = np.array([(2,2,2),(2,2,2),(2,2,2)],dtype = 'int32') matrix2 = np.array([(1,1,1),(1,1,1),(1,1,1)],dtype = 'int32') print (matrix1) print (matrix2) matrix1 = tf.constant(matrix1) matrix2 = tf.constant(matrix2) matrix_product = tf.matmul(matrix1, matrix2) matrix_sum = tf.add(matrix1,matrix2) matrix_3 = np.array([(2,7,2),(1,4,2),(9,0,2)],dtype = 'float32') print (matrix_3) matrix_det = tf.matrix_determinant(matrix_3) with tf.Session() as sess: result1 = sess.run(matrix_product) result2 = sess.run(matrix_sum) result3 = sess.run(matrix_det) print (result1) print (result2) print (result3) Output The above code will generate the following output − We have created multidimensional arrays in the above source code. Now, it is important to understand that we created graph and sessions, which manage the Tensors and generate the appropriate output. With the help of graph, we have the output specifying the mathematical calculations between Tensors. 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 29 Lectures 3.5 hours Mohammad Nauman 82 Lectures 4 hours Anis Koubaa Print Add Notes Bookmark this page
[ { "code": null, "e": 2439, "s": 2315, "text": "In this chapter, we will learn about the basics of TensorFlow. We will begin by understanding the data structure of tensor." }, { "code": null, "e": 2651, "s": 2439, "text": "Tensors are used as the basic data structures in TensorFlow language. Tensors represent the connecting edges in any flow diagram called the Data Flow Graph. Tensors are defined as multidimensional array or list." }, { "code": null, "e": 2710, "s": 2651, "text": "Tensors are identified by the following three parameters −" }, { "code": null, "e": 2913, "s": 2710, "text": "Unit of dimensionality described within tensor is called rank. It identifies the number of dimensions of the tensor. A rank of a tensor can be described as the order or n-dimensions of a tensor defined." }, { "code": null, "e": 2981, "s": 2913, "text": "The number of rows and columns together define the shape of Tensor." }, { "code": null, "e": 3041, "s": 2981, "text": "Type describes the data type assigned to Tensor’s elements." }, { "code": null, "e": 3115, "s": 3041, "text": "A user needs to consider the following activities for building a Tensor −" }, { "code": null, "e": 3144, "s": 3115, "text": "Build an n-dimensional array" }, { "code": null, "e": 3177, "s": 3144, "text": "Convert the n-dimensional array." }, { "code": null, "e": 3263, "s": 3177, "text": "TensorFlow includes various dimensions. The dimensions are described in brief below −" }, { "code": null, "e": 3370, "s": 3263, "text": "One dimensional tensor is a normal array structure which includes one set of values of the same data type." }, { "code": null, "e": 3382, "s": 3370, "text": "Declaration" }, { "code": null, "e": 3473, "s": 3382, "text": ">>> import numpy as np\n>>> tensor_1d = np.array([1.3, 1, 4.0, 23.99])\n>>> print tensor_1d\n" }, { "code": null, "e": 3543, "s": 3473, "text": "The implementation with the output is shown in the screenshot below −" }, { "code": null, "e": 3718, "s": 3543, "text": "The indexing of elements is same as Python lists. The first element starts with index of 0; to print the values through index, all you need to do is mention the index number." }, { "code": null, "e": 3773, "s": 3718, "text": ">>> print tensor_1d[0]\n1.3\n>>> print tensor_1d[2]\n4.0\n" }, { "code": null, "e": 3841, "s": 3773, "text": "Sequence of arrays are used for creating “two dimensional tensors”." }, { "code": null, "e": 3902, "s": 3841, "text": "The creation of two-dimensional tensors is described below −" }, { "code": null, "e": 3973, "s": 3902, "text": "Following is the complete syntax for creating two dimensional arrays −" }, { "code": null, "e": 4147, "s": 3973, "text": ">>> import numpy as np\n>>> tensor_2d = np.array([(1,2,3,4),(4,5,6,7),(8,9,10,11),(12,13,14,15)])\n>>> print(tensor_2d)\n[[ 1 2 3 4]\n[ 4 5 6 7]\n[ 8 9 10 11]\n[12 13 14 15]]\n>>>\n" }, { "code": null, "e": 4285, "s": 4147, "text": "The specific elements of two dimensional tensors can be tracked with the help of row number and column number specified as index numbers." }, { "code": null, "e": 4309, "s": 4285, "text": ">>> tensor_2d[3][2]\n14\n" }, { "code": null, "e": 4381, "s": 4309, "text": "In this section, we will learn about Tensor Handling and Manipulations." }, { "code": null, "e": 4433, "s": 4381, "text": "To begin with, let us consider the following code −" }, { "code": null, "e": 5089, "s": 4433, "text": "import tensorflow as tf\nimport numpy as np\n\nmatrix1 = np.array([(2,2,2),(2,2,2),(2,2,2)],dtype = 'int32')\nmatrix2 = np.array([(1,1,1),(1,1,1),(1,1,1)],dtype = 'int32')\n\nprint (matrix1)\nprint (matrix2)\n\nmatrix1 = tf.constant(matrix1)\nmatrix2 = tf.constant(matrix2)\nmatrix_product = tf.matmul(matrix1, matrix2)\nmatrix_sum = tf.add(matrix1,matrix2)\nmatrix_3 = np.array([(2,7,2),(1,4,2),(9,0,2)],dtype = 'float32')\nprint (matrix_3)\n\nmatrix_det = tf.matrix_determinant(matrix_3)\nwith tf.Session() as sess:\n result1 = sess.run(matrix_product)\n result2 = sess.run(matrix_sum)\n result3 = sess.run(matrix_det)\n\nprint (result1)\nprint (result2)\nprint (result3)" }, { "code": null, "e": 5096, "s": 5089, "text": "Output" }, { "code": null, "e": 5148, "s": 5096, "text": "The above code will generate the following output −" }, { "code": null, "e": 5448, "s": 5148, "text": "We have created multidimensional arrays in the above source code. Now, it is important to understand that we created graph and sessions, which manage the Tensors and generate the appropriate output. With the help of graph, we have the output specifying the mathematical calculations between Tensors." }, { "code": null, "e": 5481, "s": 5448, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 5503, "s": 5481, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5536, "s": 5503, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 5558, "s": 5536, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5591, "s": 5558, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 5613, "s": 5591, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5646, "s": 5613, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 5668, "s": 5646, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5703, "s": 5668, "text": "\n 29 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5720, "s": 5703, "text": " Mohammad Nauman" }, { "code": null, "e": 5753, "s": 5720, "text": "\n 82 Lectures \n 4 hours \n" }, { "code": null, "e": 5766, "s": 5753, "text": " Anis Koubaa" }, { "code": null, "e": 5773, "s": 5766, "text": " Print" }, { "code": null, "e": 5784, "s": 5773, "text": " Add Notes" } ]
Assigning multiple characters in an int in C language - GeeksforGeeks
30 Apr, 2018 Consider the following C program. #include <stdio.h>int main(void){ int a = 'd'; printf("%d\n", a); /*OUTPUT - 100 (ASCII Code for character d)*/ int b = 'dd'; printf("%d", b); /*OUTPUT - 25700 (Explanation in detail given below)*/ return 0;} Output : 100 25700 We can easily guess that the output for ‘d’ is 100 as 100 is ASCII value of character ‘d’. Let us consider below line int a = 'dd' (%d, a) prints 25700 as output01100100 01100100 (Binary of 100 100)Assuming int is of 2 bytes, starting byte is occupied by first character ‘d’ and second byte by second character ‘d’. Therefore overall binary involves 0110010001100100 i.e 2^14 + 2^13 + 2^10 + 2^6 + 2^5 + 2^2 = 25700. Now guess the output of following code. #include <stdio.h>int main(void){ int b = 'de'; printf("%d", b); return 0;} C Language Program Output Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Arrow operator -> in C/C++ with Examples delete keyword in C++ Output of C Programs | Set 1 Output of Java Program | Set 1 Different ways to copy a string in C/C++
[ { "code": null, "e": 24321, "s": 24293, "text": "\n30 Apr, 2018" }, { "code": null, "e": 24355, "s": 24321, "text": "Consider the following C program." }, { "code": "#include <stdio.h>int main(void){ int a = 'd'; printf(\"%d\\n\", a); /*OUTPUT - 100 (ASCII Code for character d)*/ int b = 'dd'; printf(\"%d\", b); /*OUTPUT - 25700 (Explanation in detail given below)*/ return 0;}", "e": 24591, "s": 24355, "text": null }, { "code": null, "e": 24600, "s": 24591, "text": "Output :" }, { "code": null, "e": 24611, "s": 24600, "text": "100\n25700\n" }, { "code": null, "e": 24702, "s": 24611, "text": "We can easily guess that the output for ‘d’ is 100 as 100 is ASCII value of character ‘d’." }, { "code": null, "e": 24729, "s": 24702, "text": "Let us consider below line" }, { "code": null, "e": 24743, "s": 24729, "text": "int a = 'dd' " }, { "code": null, "e": 25029, "s": 24743, "text": "(%d, a) prints 25700 as output01100100 01100100 (Binary of 100 100)Assuming int is of 2 bytes, starting byte is occupied by first character ‘d’ and second byte by second character ‘d’. Therefore overall binary involves 0110010001100100 i.e 2^14 + 2^13 + 2^10 + 2^6 + 2^5 + 2^2 = 25700." }, { "code": null, "e": 25069, "s": 25029, "text": "Now guess the output of following code." }, { "code": "#include <stdio.h>int main(void){ int b = 'de'; printf(\"%d\", b); return 0;}", "e": 25154, "s": 25069, "text": null }, { "code": null, "e": 25165, "s": 25154, "text": "C Language" }, { "code": null, "e": 25180, "s": 25165, "text": "Program Output" }, { "code": null, "e": 25199, "s": 25180, "text": "Technical Scripter" }, { "code": null, "e": 25297, "s": 25199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25306, "s": 25297, "text": "Comments" }, { "code": null, "e": 25319, "s": 25306, "text": "Old Comments" }, { "code": null, "e": 25354, "s": 25319, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25382, "s": 25354, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25428, "s": 25382, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25440, "s": 25428, "text": "fork() in C" }, { "code": null, "e": 25472, "s": 25440, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25513, "s": 25472, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 25535, "s": 25513, "text": "delete keyword in C++" }, { "code": null, "e": 25564, "s": 25535, "text": "Output of C Programs | Set 1" }, { "code": null, "e": 25595, "s": 25564, "text": "Output of Java Program | Set 1" } ]
XQuery - concat Function
The concat function is used to concatenate various strings. concat($input as xs:anyAtomicType?) as xs:string $input − one or more inputs separated by comma. $input − one or more inputs separated by comma. let $bookTitle := "Learn XQuery in 24 hours" let $updatedTitle := concat($bookTitle,",price: 200$") return <result> <title>{$updatedTitle}</title> </result> <result> <title>Learn XQuery in 24 hours,price: 200$</title> </result> In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 1932, "s": 1872, "text": "The concat function is used to concatenate various strings." }, { "code": null, "e": 1981, "s": 1932, "text": "concat($input as xs:anyAtomicType?) as xs:string" }, { "code": null, "e": 2029, "s": 1981, "text": "$input − one or more inputs separated by comma." }, { "code": null, "e": 2077, "s": 2029, "text": "$input − one or more inputs separated by comma." }, { "code": null, "e": 2250, "s": 2077, "text": "let $bookTitle := \"Learn XQuery in 24 hours\"\nlet $updatedTitle := concat($bookTitle,\",price: 200$\")\n\nreturn\n <result> \n <title>{$updatedTitle}</title>\n </result>" }, { "code": null, "e": 2325, "s": 2250, "text": "<result>\n <title>Learn XQuery in 24 hours,price: 200$</title>\n</result>\n" }, { "code": null, "e": 2549, "s": 2325, "text": "In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result." }, { "code": null, "e": 2556, "s": 2549, "text": " Print" }, { "code": null, "e": 2567, "s": 2556, "text": " Add Notes" } ]
PostgreSQL - UPDATE Query
The PostgreSQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update the selected rows. Otherwise, all the rows would be updated. The basic syntax of UPDATE query with WHERE clause is as follows − UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; You can combine N number of conditions using AND or OR operators. Consider the table COMPANY, having records as follows − testdb# select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows) The following is an example, which would update ADDRESS for a customer, whose ID is 6 − testdb=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3; Now, COMPANY table would have the following records − id | name | age | address | salary ----+-------+-----+------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 3 | Teddy | 23 | Norway | 15000 (7 rows) If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not need to use WHERE clause and UPDATE query would be as follows − testdb=# UPDATE COMPANY SET ADDRESS = 'Texas', SALARY=20000; Now, COMPANY table will have the following records − id | name | age | address | salary ----+-------+-----+---------+-------- 1 | Paul | 32 | Texas | 20000 2 | Allen | 25 | Texas | 20000 4 | Mark | 25 | Texas | 20000 5 | David | 27 | Texas | 20000 6 | Kim | 22 | Texas | 20000 7 | James | 24 | Texas | 20000 3 | Teddy | 23 | Texas | 20000 (7 rows) 23 Lectures 1.5 hours John Elder 49 Lectures 3.5 hours Niyazi Erdogan 126 Lectures 10.5 hours Abhishek And Pukhraj 35 Lectures 5 hours Karthikeya T 5 Lectures 51 mins Vinay Kumar 5 Lectures 52 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 3018, "s": 2825, "text": "The PostgreSQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update the selected rows. Otherwise, all the rows would be updated." }, { "code": null, "e": 3085, "s": 3018, "text": "The basic syntax of UPDATE query with WHERE clause is as follows −" }, { "code": null, "e": 3184, "s": 3085, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n" }, { "code": null, "e": 3250, "s": 3184, "text": "You can combine N number of conditions using AND or OR operators." }, { "code": null, "e": 3306, "s": 3250, "text": "Consider the table COMPANY, having records as follows −" }, { "code": null, "e": 3698, "s": 3306, "text": "testdb# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)" }, { "code": null, "e": 3786, "s": 3698, "text": "The following is an example, which would update ADDRESS for a customer, whose ID is 6 −" }, { "code": null, "e": 3843, "s": 3786, "text": "testdb=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3;" }, { "code": null, "e": 3897, "s": 3843, "text": "Now, COMPANY table would have the following records −" }, { "code": null, "e": 4267, "s": 3897, "text": " id | name | age | address | salary\n----+-------+-----+------------+--------\n 1 | Paul | 32 | California | 20000\n 2 | Allen | 25 | Texas | 15000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000\n 3 | Teddy | 23 | Norway | 15000\n(7 rows)" }, { "code": null, "e": 4419, "s": 4267, "text": "If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not need to use WHERE clause and UPDATE query would be as follows −" }, { "code": null, "e": 4480, "s": 4419, "text": "testdb=# UPDATE COMPANY SET ADDRESS = 'Texas', SALARY=20000;" }, { "code": null, "e": 4533, "s": 4480, "text": "Now, COMPANY table will have the following records −" }, { "code": null, "e": 4876, "s": 4533, "text": " id | name | age | address | salary\n----+-------+-----+---------+--------\n 1 | Paul | 32 | Texas | 20000\n 2 | Allen | 25 | Texas | 20000\n 4 | Mark | 25 | Texas | 20000\n 5 | David | 27 | Texas | 20000\n 6 | Kim | 22 | Texas | 20000\n 7 | James | 24 | Texas | 20000\n 3 | Teddy | 23 | Texas | 20000\n(7 rows)" }, { "code": null, "e": 4911, "s": 4876, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4923, "s": 4911, "text": " John Elder" }, { "code": null, "e": 4958, "s": 4923, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4974, "s": 4958, "text": " Niyazi Erdogan" }, { "code": null, "e": 5011, "s": 4974, "text": "\n 126 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5033, "s": 5011, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5066, "s": 5033, "text": "\n 35 Lectures \n 5 hours \n" }, { "code": null, "e": 5080, "s": 5066, "text": " Karthikeya T" }, { "code": null, "e": 5111, "s": 5080, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 5124, "s": 5111, "text": " Vinay Kumar" }, { "code": null, "e": 5155, "s": 5124, "text": "\n 5 Lectures \n 52 mins\n" }, { "code": null, "e": 5168, "s": 5155, "text": " Vinay Kumar" }, { "code": null, "e": 5175, "s": 5168, "text": " Print" }, { "code": null, "e": 5186, "s": 5175, "text": " Add Notes" } ]
When should we write our own assignment operator in C++? - GeeksforGeeks
28 Sep, 2018 The answer is same as Copy Constructor. If a class doesn’t contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or any run time allocation of resource like file handle, a network connection..etc. For example, consider the following program. #include<iostream>using namespace std; // A class without user defined assignment operatorclass Test{ int *ptr;public: Test (int i = 0) { ptr = new int(i); } void setValue (int i) { *ptr = i; } void print() { cout << *ptr << endl; }}; int main(){ Test t1(5); Test t2; t2 = t1; t1.setValue(10); t2.print(); return 0;} Output of above program is “10”. If we take a look at main(), we modified ‘t1’ using setValue() function, but the changes are also reflected in object ‘t2’. This type of unexpected changes cause problems.Since there is no user defined assignment operator in the above program, compiler creates a default assignment operator, which copies ‘ptr’ of right hand side to left hand side. So both ‘ptr’s start pointing to the same location. We can handle the above problem in two ways. 1) Do not allow assignment of one object to other object. We can create our own dummy assignment operator and make it private. 2) Write your own assignment operator that does deep copy. Same is true for Copy Constructor. Following is an example of overloading assignment operator for the above class. #include<iostream>using namespace std; class Test{ int *ptr;public: Test (int i = 0) { ptr = new int(i); } void setValue (int i) { *ptr = i; } void print() { cout << *ptr << endl; } Test & operator = (const Test &t);}; Test & Test::operator = (const Test &t){ // Check for self assignment if(this != &t) *ptr = *(t.ptr); return *this;} int main(){ Test t1(5); Test t2; t2 = t1; t1.setValue(10); t2.print(); return 0;} Output 5 We should also add a copy constructor to the above class, so that the statements like “Test t3 = t4;” also don’t cause any problem. Note the if condition in assignment operator. While overloading assignment operator, we must check for self assignment. Otherwise assigning an object to itself may lead to unexpected results (See this). Self assignment check is not necessary for the above ‘Test’ class, because ‘ptr’ always points to one integer and we may reuse the same memory. But in general, it is a recommended practice to do self-assignment check. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Core Dump (Segmentation fault) in C/C++ fork() in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25206, "s": 25178, "text": "\n28 Sep, 2018" }, { "code": null, "e": 25681, "s": 25206, "text": "The answer is same as Copy Constructor. If a class doesn’t contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or any run time allocation of resource like file handle, a network connection..etc. For example, consider the following program." }, { "code": "#include<iostream>using namespace std; // A class without user defined assignment operatorclass Test{ int *ptr;public: Test (int i = 0) { ptr = new int(i); } void setValue (int i) { *ptr = i; } void print() { cout << *ptr << endl; }}; int main(){ Test t1(5); Test t2; t2 = t1; t1.setValue(10); t2.print(); return 0;}", "e": 26044, "s": 25681, "text": null }, { "code": null, "e": 26478, "s": 26044, "text": "Output of above program is “10”. If we take a look at main(), we modified ‘t1’ using setValue() function, but the changes are also reflected in object ‘t2’. This type of unexpected changes cause problems.Since there is no user defined assignment operator in the above program, compiler creates a default assignment operator, which copies ‘ptr’ of right hand side to left hand side. So both ‘ptr’s start pointing to the same location." }, { "code": null, "e": 26523, "s": 26478, "text": "We can handle the above problem in two ways." }, { "code": null, "e": 26650, "s": 26523, "text": "1) Do not allow assignment of one object to other object. We can create our own dummy assignment operator and make it private." }, { "code": null, "e": 26709, "s": 26650, "text": "2) Write your own assignment operator that does deep copy." }, { "code": null, "e": 26744, "s": 26709, "text": "Same is true for Copy Constructor." }, { "code": null, "e": 26824, "s": 26744, "text": "Following is an example of overloading assignment operator for the above class." }, { "code": "#include<iostream>using namespace std; class Test{ int *ptr;public: Test (int i = 0) { ptr = new int(i); } void setValue (int i) { *ptr = i; } void print() { cout << *ptr << endl; } Test & operator = (const Test &t);}; Test & Test::operator = (const Test &t){ // Check for self assignment if(this != &t) *ptr = *(t.ptr); return *this;} int main(){ Test t1(5); Test t2; t2 = t1; t1.setValue(10); t2.print(); return 0;}", "e": 27304, "s": 26824, "text": null }, { "code": null, "e": 27311, "s": 27304, "text": "Output" }, { "code": null, "e": 27313, "s": 27311, "text": "5" }, { "code": null, "e": 27445, "s": 27313, "text": "We should also add a copy constructor to the above class, so that the statements like “Test t3 = t4;” also don’t cause any problem." }, { "code": null, "e": 27866, "s": 27445, "text": "Note the if condition in assignment operator. While overloading assignment operator, we must check for self assignment. Otherwise assigning an object to itself may lead to unexpected results (See this). Self assignment check is not necessary for the above ‘Test’ class, because ‘ptr’ always points to one integer and we may reuse the same memory. But in general, it is a recommended practice to do self-assignment check." }, { "code": null, "e": 27991, "s": 27866, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28002, "s": 27991, "text": "C Language" }, { "code": null, "e": 28006, "s": 28002, "text": "C++" }, { "code": null, "e": 28010, "s": 28006, "text": "CPP" }, { "code": null, "e": 28108, "s": 28010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28143, "s": 28108, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28171, "s": 28143, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 28217, "s": 28171, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 28257, "s": 28217, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 28269, "s": 28257, "text": "fork() in C" }, { "code": null, "e": 28287, "s": 28269, "text": "Vector in C++ STL" }, { "code": null, "e": 28333, "s": 28287, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28352, "s": 28333, "text": "Inheritance in C++" }, { "code": null, "e": 28395, "s": 28352, "text": "Map in C++ Standard Template Library (STL)" } ]
JqueryUI - Menu
A menu widget usually consists of a main menu bar with pop up menus. Items in pop up menus often have sub pop up menus. A menu can be created using the markup elements as long as the parent-child relation is maintained (using <ul> or <ol>). Each menu item has an anchor element. The Menu Widget in jQueryUI can be used for inline and popup menus, or as a base for building more complex menu systems. For example, you can create nested menus with custom positioning. jQueryUI provides menu() methods to create a menu. The menu() method can be used in two forms − $(selector, context).menu (options) Method $(selector, context).menu (options) Method $(selector, context).menu ("action", params) Method $(selector, context).menu ("action", params) Method The menu (options) method declares that an HTML element and its contents should be treated and managed as menus. The options parameter is an object that specifies the appearance and behavior of the menu items involved. $(selector, context).menu (options); You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows − $(selector, context).menu({option1: value1, option2: value2..... }); The following table lists the different options that can be used with this method − This option if set to true disables the menu. By default its value is false. Option - disabled This option if set to true disables the menu. By default its value is false. Syntax $( ".selector" ).menu ( { disabled: true } ); This option sets the icons for submenus. By default its value is { submenu: "ui-icon-carat-1-e" }. Option - icons This option sets the icons for submenus. By default its value is { submenu: "ui-icon-carat-1-e" }. Syntax $( ".selector" ).menu ( { icons: { submenu: "ui-icon-circle-triangle-e" } } ); This option is a selector for the elements that serve as the menu container, including sub-menus. By default its value is ul. Option - menus This option is a selector for the elements that serve as the menu container, including sub-menus. By default its value is ul. Syntax $( ".selector" ).menu ( { menus: "div" } ); This option sets the position of submenus in relation to the associated parent menu item. By default its value is { my: "left top", at: "right top" }. Option - position This option sets the position of submenus in relation to the associated parent menu item. By default its value is { my: "left top", at: "right top" }. Syntax $( ".selector" ).menu ( { position: { my: "left top", at: "right-5 top+5" } } ); This option is used to customize the ARIA roles used for the menu and menu items. By default its value is menu. Option - role This option is used to customize the ARIA roles used for the menu and menu items. By default its value is menu. Syntax $( ".selector" ).menu ( { role: null } ); The following example demonstrates a simple example of menu widget functionality, passing no parameters to the menu() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Menu functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-menu { width: 200px; } </style> <!-- Javascript --> <script> $(function() { $( "#menu-1" ).menu(); }); </script> </head> <body> <!-- HTML --> <ul id = "menu-1"> <li><a href = "#">Spring</a></li> <li><a href = "#">Hibernate</a></li> <li><a href = "#">Java</a> <ul> <li><a href = "#">Java IO</a></li> <li><a href = "#">Swing</a></li> <li><a href = "#">Jaspr Reports</a></li> </ul> </li> <li><a href = "#">JSF</a></li> <li><a href = "#">HTML5</a></li> </ul> </body> </html> Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − Spring Hibernate Java Java IO Swing Jaspr Reports Java IO Swing Jaspr Reports JSF HTML5 In the above example, you can see a themeable menu with mouse and keyboard interactions for navigation. The following example demonstrates the usage of two options icons, and position in the menu function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Menu functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-menu { width: 200px; } </style> <!-- Javascript --> <script> $(function() { $( "#menu-2" ).menu({ icons: { submenu: "ui-icon-circle-triangle-e"}, position: { my: "right top", at: "right-10 top+5" } }); }); </script> </head> <body> <!-- HTML --> <ul id = "menu-2"> <li><a href = "#">Spring</a></li> <li><a href = "#">Hibernate</a></li> <li><a href = "#">Java</a> <ul> <li><a href = "#">Java IO</a></li> <li><a href = "#">Swing</a></li> <li><a href = "#">Jaspr Reports</a></li> </ul> </li> <li><a href = "#">JSF</a></li> <li><a href = "#">HTML5</a></li> </ul> </body> </html> Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − Spring Hibernate Java Java IO Swing Jaspr Reports Java IO Swing Jaspr Reports JSF HTML5 In the above example, you can see we have applied an icon image for the submenu list and also changed the submenu position. The menu ("action", params) method can perform an action on menu elements, such as enabling/disabling the menu. The action is specified as a string in the first argument (e.g., "disable" disables the menu). Check out the actions that can be passed, in the following table. $(selector, context).menu ("action", params);; The following table lists the different actions that can be used with this method − This action removes the focus from a menu. It triggers the menu's blur event by resetting any active element style. Where event is of type Event and represents what triggered the menu to blur. Action - blur( [event ] ) This action removes the focus from a menu. It triggers the menu's blur event by resetting any active element style. Where event is of type Event and represents what triggered the menu to blur. Syntax $(".selector").menu( "blur" ); This action closes the current active sub-menu. Where event is of type Event and represents what triggered the menu to collapse. Action - collapse( [event ] ) This action closes the current active sub-menu. Where event is of type Event and represents what triggered the menu to collapse. Syntax $(".selector").menu( "collapse" ); This action closes all the open submenus. Action - collapseAll( [event ] [, all ] ) This action closes all the open submenus. Where − event is of type Event and represents what triggered the menu to collapse event is of type Event and represents what triggered the menu to collapse all is of type Boolean Indicates whether all sub-menus should be closed or only sub-menus below and including the menu that is or contains the target of the triggering event. all is of type Boolean Indicates whether all sub-menus should be closed or only sub-menus below and including the menu that is or contains the target of the triggering event. Syntax $(".selector").menu( "collapseAll", null, true ); This action removes menu functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments. Action - destroy() This action removes menu functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments. Syntax $(".selector").menu( "destroy" ); This action disables the menu. This method does not accept any arguments. Action - disable() This action disables the menu. This method does not accept any arguments. Syntax $(".selector").menu( "disable" ); This action enables the the menu. This method does not accept any arguments. Action - enable() This action enables the the menu. This method does not accept any arguments. Syntax $(".selector").menu( "enable" ); This action opens the sub-menu below the currently active item, if one exists. Where event is of type Event and represents what triggered the menu to expand. Action - expand( [event ] ) This action opens the sub-menu below the currently active item, if one exists. Where event is of type Event and represents what triggered the menu to expand. Syntax $(".selector").menu( "expand" ); This action activates a particular menu item, begins opening any sub-menu if present and triggers the menu's focus event. Where event is of type Event and represents what triggered the menu to gain focus. and item is a jQuery object representing the menu item to focus/activate. Action - focus( [event ], item ) This action activates a particular menu item, begins opening any sub-menu if present and triggers the menu's focus event. Where event is of type Event and represents what triggered the menu to gain focus. and item is a jQuery object representing the menu item to focus/activate. Syntax $(".selector").menu( "focus", null, menu.find( ".ui-menu-item:last" ) ); This action returns a boolean value, which states if the current active menu item is the first menu item. This method does not accept any arguments. Action - isFirstItem() This action returns a boolean value, which states if the current active menu item is the first menu item. This method does not accept any arguments. Syntax $(".selector").menu( "isFirstItem" ); This action returns a boolean value, which states if the current active menu item is the last menu item. This method does not accept any arguments. Action - isLastItem() This action returns a boolean value, which states if the current active menu item is the last menu item. This method does not accept any arguments. Syntax $(".selector").menu( "isLastItem" ); This action delegates the active state to the next menu item. Where event is of type Event and represents what triggered the focus to move. Action - next( [event ] ) This action delegates the active state to the next menu item. Where event is of type Event and represents what triggered the focus to move. Syntax $(".selector").menu( "next" ); This action moves active state to first menu item below the bottom of a scrollable menu or the last item if not scrollable. Where event is of type Event and represents what triggered the focus to move. Action - nextPage( [event ] ) This action moves active state to first menu item below the bottom of a scrollable menu or the last item if not scrollable. Where event is of type Event and represents what triggered the focus to move. Syntax $(".selector").menu( "nextPage" ); This action gets the value currently associated with the specified optionName. Where optionName is of type String and represents the name of the option to get. Action - option( optionName ) This action gets the value currently associated with the specified optionName. Where optionName is of type String and represents the name of the option to get. Syntax var isDisabled = $( ".selector" ).menu( "option", "disabled" ); This action gets an object containing key/value pairs representing the current menu options hash. Action - option() This action gets an object containing key/value pairs representing the current menu options hash. Syntax var options = $( ".selector" ).menu( "option" ); This action sets the value of the menu option associated with the specified optionName. Where optionName is of type String and represents name of option to set and value is of type Object and represents value to set for the option. Action - option( optionName, value ) This action sets the value of the menu option associated with the specified optionName. Where optionName is of type String and represents name of option to set and value is of type Object and represents value to set for the option. Syntax $(".selector").menu( "option", "disabled", true ); This action sets one or more options for the menu. Where options is of type Object and represents a map of option-value pairs to set. Action - option( options ) This action sets one or more options for the menu. Where options is of type Object and represents a map of option-value pairs to set. Syntax $(".selector").menu( "option", { disabled: true } ); This action moves active state to previous menu item. Where event is of type Event and represents what triggered the focus to move. Action - previous( [event ] ) This action moves active state to previous menu item. Where event is of type Event and represents what triggered the focus to move. Syntax $(".selector").menu( "previous" ); This action moves active state to first menu item above the top of a scrollable menu or the first item if not scrollable. Where event is of type Event and represents what triggered the focus to move. Action - previousPage( [event ] ) This action moves active state to first menu item above the top of a scrollable menu or the first item if not scrollable. Where event is of type Event and represents what triggered the focus to move. Syntax $(".selector").menu( "previousPage" ); This action initializes sub-menus and menu items that have not already been initialized. This method does not accept any arguments. Action - refresh() This action initializes sub-menus and menu items that have not already been initialized. This method does not accept any arguments. Syntax $(".selector").menu( "refresh" ); This action selects the currently active menu item, collapses all sub-menus and triggers the menu's select event. Where event is of type Event and represents what triggered the selection. Action - select( [event ] ) This action selects the currently active menu item, collapses all sub-menus and triggers the menu's select event. Where event is of type Event and represents what triggered the selection. Syntax $(".selector").menu( "select" ); This action returns a jQuery object containing the menu. This method does not accept any arguments. Action - widget() This action returns a jQuery object containing the menu. This method does not accept any arguments. Syntax $(".selector").menu( "widget" ); The following examples demonstrate how to use the actions given in the above table. The following example demonstrates the use of disable() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Menu functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-menu { width: 200px; } </style> <!-- Javascript --> <script> $(function() { $( "#menu-3" ).menu(); $( "#menu-3" ).menu("disable"); }); </script> </head> <body> <!-- HTML --> <ul id = "menu-3"> <li><a href = "#">Spring</a></li> <li><a href = "#">Hibernate</a></li> <li><a href = "#">Java</a> <ul> <li><a href = "#">Java IO</a></li> <li><a href = "#">Swing</a></li> <li><a href = "#">Jaspr Reports</a></li> </ul> </li> <li><a href = "#">JSF</a></li> <li><a href = "#">HTML5</a></li> </ul> </body> </html> Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output − Spring Hibernate Java Java IO Swing Jaspr Reports Java IO Swing Jaspr Reports JSF HTML5 In the above example, you can see the menu is disabled. The following example demonstrates the use of focus() and collapseAll methods. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Menu functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-menu { width: 200px; } </style> <!-- Javascript --> <script> $(function() { var menu = $("#menu-4").menu(); $( "#menu-4" ).menu( "focus", null, $( "#menu-4" ).menu().find( ".ui-menu-item:last" )); $(menu).mouseleave(function () { menu.menu('collapseAll'); }); }); </script> </head> <body> <!-- HTML --> <ul id = "menu-4"> <li><a href = "#">Spring</a></li> <li><a href = "#">Hibernate</a></li> <li><a href = "#">JSF</a></li> <li><a href = "#">HTML5</a></li> <li><a href = "#">Java</a> <ul> <li><a href = "#">Java IO</a></li> <li><a href = "#">Swing</a></li> <li><a href = "#">Jaspr Reports</a></li> </ul> </li> </ul> </body> </html> Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output − Spring Hibernate JSF HTML5 Java Java IO Swing Jaspr Reports Java IO Swing Jaspr Reports In the above example, you can see the focus is on the last menu item. Now expand the submenu and when the mouse leaves the submenu, the submenu is closed. In addition to the menu (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below − This event is triggered when a menu loses focus. Event - blur(event, ui) This event is triggered when a menu loses focus. Where event is of type Event, and ui is of type Object and represents the currently active menu item. Syntax $( ".selector" ).menu({ blur: function( event, ui ) {} }); This event is triggered when a menu is created. Event - create(event, ui) This event is triggered when a menu is created. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).menu({ create: function( event, ui ) {} }); This event is triggered when a menu gains focus or when any menu item is activated. Event - focus(event, ui) This event is triggered when a menu gains focus or when any menu item is activated. Where event is of type Event, and ui is of type Object and represents the currently active menu item. Syntax $( ".selector" ).menu({ focus: function( event, ui ) {} }); This event is triggered when a menu item is selected. Event - select(event, ui) This event is triggered when a menu item is selected. Where event is of type Event, and ui is of type Object and represents the currently active menu item. Syntax $( ".selector" ).menu({ select: function( event, ui ) {} }); The following example demonstrates the event method usage for menu widget functionality. This example demonstrates the use of event create, blur and focus. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Menu functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- CSS --> <style> .ui-menu { width: 200px; } </style> <!-- Javascript --> <script> $(function() { $( "#menu-5" ).menu({ create: function( event, ui ) { var result = $( "#result" ); result.append( "Create event<br>" ); }, blur: function( event, ui ) { var result = $( "#result" ); result.append( "Blur event<br>" ); }, focus: function( event, ui ) { var result = $( "#result" ); result.append( "focus event<br>" ); } }); }); </script> </head> <body> <!-- HTML --> <ul id = "menu-5"> <li><a href = "#">Spring</a></li> <li><a href = "#">Hibernate</a></li> <li><a href = "#">JSF</a></li> <li><a href = "#">HTML5</a></li> <li><a href = "#">Java</a> <ul> <li><a href = "#">Java IO</a></li> <li><a href = "#">Swing</a></li> <li><a href = "#">Jaspr Reports</a></li> </ul> </li> </ul> <span id = "result"></span> </body> </html> Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output − Spring Hibernate JSF HTML5 Java Java IO Swing Jaspr Reports Java IO Swing Jaspr Reports In the above example, we are printing the messages based on the events triggered. Print Add Notes Bookmark this page
[ { "code": null, "e": 2543, "s": 2264, "text": "A menu widget usually consists of a main menu bar with pop up menus. Items in pop up menus often have sub pop up menus. A menu can be created using the markup elements as long as the parent-child relation is maintained (using <ul> or <ol>). Each menu item has an anchor element." }, { "code": null, "e": 2730, "s": 2543, "text": "The Menu Widget in jQueryUI can be used for inline and popup menus, or as a base for building more complex menu systems. For example, you can create nested menus with custom positioning." }, { "code": null, "e": 2781, "s": 2730, "text": "jQueryUI provides menu() methods to create a menu." }, { "code": null, "e": 2826, "s": 2781, "text": "The menu() method can be used in two forms −" }, { "code": null, "e": 2869, "s": 2826, "text": "$(selector, context).menu (options) Method" }, { "code": null, "e": 2912, "s": 2869, "text": "$(selector, context).menu (options) Method" }, { "code": null, "e": 2964, "s": 2912, "text": "$(selector, context).menu (\"action\", params) Method" }, { "code": null, "e": 3016, "s": 2964, "text": "$(selector, context).menu (\"action\", params) Method" }, { "code": null, "e": 3235, "s": 3016, "text": "The menu (options) method declares that an HTML element and its contents should be treated and managed as menus. The options parameter is an object that specifies the appearance and behavior of the menu items involved." }, { "code": null, "e": 3273, "s": 3235, "text": "$(selector, context).menu (options);\n" }, { "code": null, "e": 3449, "s": 3273, "text": "You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows −" }, { "code": null, "e": 3518, "s": 3449, "text": "$(selector, context).menu({option1: value1, option2: value2..... });" }, { "code": null, "e": 3602, "s": 3518, "text": "The following table lists the different options that can be used with this method −" }, { "code": null, "e": 3679, "s": 3602, "text": "This option if set to true disables the menu. By default its value is false." }, { "code": null, "e": 3697, "s": 3679, "text": "Option - disabled" }, { "code": null, "e": 3774, "s": 3697, "text": "This option if set to true disables the menu. By default its value is false." }, { "code": null, "e": 3781, "s": 3774, "text": "Syntax" }, { "code": null, "e": 3831, "s": 3781, "text": "$( \".selector\" ).menu (\n { disabled: true }\n);\n" }, { "code": null, "e": 3930, "s": 3831, "text": "This option sets the icons for submenus. By default its value is { submenu: \"ui-icon-carat-1-e\" }." }, { "code": null, "e": 3945, "s": 3930, "text": "Option - icons" }, { "code": null, "e": 4044, "s": 3945, "text": "This option sets the icons for submenus. By default its value is { submenu: \"ui-icon-carat-1-e\" }." }, { "code": null, "e": 4051, "s": 4044, "text": "Syntax" }, { "code": null, "e": 4134, "s": 4051, "text": "$( \".selector\" ).menu (\n { icons: { submenu: \"ui-icon-circle-triangle-e\" } }\n);\n" }, { "code": null, "e": 4260, "s": 4134, "text": "This option is a selector for the elements that serve as the menu container, including sub-menus. By default its value is ul." }, { "code": null, "e": 4275, "s": 4260, "text": "Option - menus" }, { "code": null, "e": 4401, "s": 4275, "text": "This option is a selector for the elements that serve as the menu container, including sub-menus. By default its value is ul." }, { "code": null, "e": 4408, "s": 4401, "text": "Syntax" }, { "code": null, "e": 4456, "s": 4408, "text": "$( \".selector\" ).menu (\n { menus: \"div\" }\n);\n" }, { "code": null, "e": 4607, "s": 4456, "text": "This option sets the position of submenus in relation to the associated parent menu item. By default its value is { my: \"left top\", at: \"right top\" }." }, { "code": null, "e": 4626, "s": 4607, "text": "Option - position\t" }, { "code": null, "e": 4777, "s": 4626, "text": "This option sets the position of submenus in relation to the associated parent menu item. By default its value is { my: \"left top\", at: \"right top\" }." }, { "code": null, "e": 4784, "s": 4777, "text": "Syntax" }, { "code": null, "e": 4869, "s": 4784, "text": "$( \".selector\" ).menu (\n { position: { my: \"left top\", at: \"right-5 top+5\" } }\n);\n" }, { "code": null, "e": 4981, "s": 4869, "text": "This option is used to customize the ARIA roles used for the menu and menu items. By default its value is menu." }, { "code": null, "e": 4995, "s": 4981, "text": "Option - role" }, { "code": null, "e": 5107, "s": 4995, "text": "This option is used to customize the ARIA roles used for the menu and menu items. By default its value is menu." }, { "code": null, "e": 5114, "s": 5107, "text": "Syntax" }, { "code": null, "e": 5160, "s": 5114, "text": "$( \".selector\" ).menu (\n { role: null }\n);\n" }, { "code": null, "e": 5286, "s": 5160, "text": "The following example demonstrates a simple example of menu widget functionality, passing no parameters to the menu() method." }, { "code": null, "e": 6443, "s": 5286, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Menu functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-menu {\n width: 200px;\n }\n </style>\n <!-- Javascript -->\n \n <script>\n $(function() {\n $( \"#menu-1\" ).menu();\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <ul id = \"menu-1\">\n <li><a href = \"#\">Spring</a></li>\n <li><a href = \"#\">Hibernate</a></li>\n <li><a href = \"#\">Java</a>\n <ul>\n <li><a href = \"#\">Java IO</a></li>\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">Jaspr Reports</a></li>\n </ul>\n </li>\n <li><a href = \"#\">JSF</a></li>\n <li><a href = \"#\">HTML5</a></li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 6639, "s": 6443, "text": "Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 6646, "s": 6639, "text": "Spring" }, { "code": null, "e": 6656, "s": 6646, "text": "Hibernate" }, { "code": null, "e": 6692, "s": 6656, "text": "Java\n\nJava IO\nSwing\nJaspr Reports\n\n" }, { "code": null, "e": 6700, "s": 6692, "text": "Java IO" }, { "code": null, "e": 6706, "s": 6700, "text": "Swing" }, { "code": null, "e": 6720, "s": 6706, "text": "Jaspr Reports" }, { "code": null, "e": 6724, "s": 6720, "text": "JSF" }, { "code": null, "e": 6730, "s": 6724, "text": "HTML5" }, { "code": null, "e": 6834, "s": 6730, "text": "In the above example, you can see a themeable menu with mouse and keyboard interactions for navigation." }, { "code": null, "e": 6948, "s": 6834, "text": "The following example demonstrates the usage of two options icons, and position in the menu function of JqueryUI." }, { "code": null, "e": 8250, "s": 6948, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Menu functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-menu {\n width: 200px;\n }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#menu-2\" ).menu({\n icons: { submenu: \"ui-icon-circle-triangle-e\"},\n position: { my: \"right top\", at: \"right-10 top+5\" }\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <ul id = \"menu-2\">\n <li><a href = \"#\">Spring</a></li>\n <li><a href = \"#\">Hibernate</a></li>\n <li><a href = \"#\">Java</a>\n <ul>\n <li><a href = \"#\">Java IO</a></li>\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">Jaspr Reports</a></li>\n </ul>\n </li>\n <li><a href = \"#\">JSF</a></li>\n <li><a href = \"#\">HTML5</a></li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 8446, "s": 8250, "text": "Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 8453, "s": 8446, "text": "Spring" }, { "code": null, "e": 8463, "s": 8453, "text": "Hibernate" }, { "code": null, "e": 8499, "s": 8463, "text": "Java\n\nJava IO\nSwing\nJaspr Reports\n\n" }, { "code": null, "e": 8507, "s": 8499, "text": "Java IO" }, { "code": null, "e": 8513, "s": 8507, "text": "Swing" }, { "code": null, "e": 8527, "s": 8513, "text": "Jaspr Reports" }, { "code": null, "e": 8531, "s": 8527, "text": "JSF" }, { "code": null, "e": 8537, "s": 8531, "text": "HTML5" }, { "code": null, "e": 8661, "s": 8537, "text": "In the above example, you can see we have applied an icon image for the submenu list and also changed the submenu position." }, { "code": null, "e": 8934, "s": 8661, "text": "The menu (\"action\", params) method can perform an action on menu elements, such as enabling/disabling the menu. The action is specified as a string in the first argument (e.g., \"disable\" disables the menu). Check out the actions that can be passed, in the following table." }, { "code": null, "e": 8982, "s": 8934, "text": "$(selector, context).menu (\"action\", params);;\n" }, { "code": null, "e": 9066, "s": 8982, "text": "The following table lists the different actions that can be used with this method −" }, { "code": null, "e": 9259, "s": 9066, "text": "This action removes the focus from a menu. It triggers the menu's blur event by resetting any active element style. Where event is of type Event and represents what triggered the menu to blur." }, { "code": null, "e": 9285, "s": 9259, "text": "Action - blur( [event ] )" }, { "code": null, "e": 9478, "s": 9285, "text": "This action removes the focus from a menu. It triggers the menu's blur event by resetting any active element style. Where event is of type Event and represents what triggered the menu to blur." }, { "code": null, "e": 9485, "s": 9478, "text": "Syntax" }, { "code": null, "e": 9517, "s": 9485, "text": "$(\".selector\").menu( \"blur\" );\n" }, { "code": null, "e": 9646, "s": 9517, "text": "This action closes the current active sub-menu. Where event is of type Event and represents what triggered the menu to collapse." }, { "code": null, "e": 9676, "s": 9646, "text": "Action - collapse( [event ] )" }, { "code": null, "e": 9805, "s": 9676, "text": "This action closes the current active sub-menu. Where event is of type Event and represents what triggered the menu to collapse." }, { "code": null, "e": 9812, "s": 9805, "text": "Syntax" }, { "code": null, "e": 9848, "s": 9812, "text": "$(\".selector\").menu( \"collapse\" );\n" }, { "code": null, "e": 9890, "s": 9848, "text": "This action closes all the open submenus." }, { "code": null, "e": 9932, "s": 9890, "text": "Action - collapseAll( [event ] [, all ] )" }, { "code": null, "e": 9982, "s": 9932, "text": "This action closes all the open submenus. Where −" }, { "code": null, "e": 10056, "s": 9982, "text": "event is of type Event and represents what triggered the menu to collapse" }, { "code": null, "e": 10130, "s": 10056, "text": "event is of type Event and represents what triggered the menu to collapse" }, { "code": null, "e": 10305, "s": 10130, "text": "all is of type Boolean Indicates whether all sub-menus should be closed or only sub-menus below and including the menu that is or contains the target of the triggering event." }, { "code": null, "e": 10480, "s": 10305, "text": "all is of type Boolean Indicates whether all sub-menus should be closed or only sub-menus below and including the menu that is or contains the target of the triggering event." }, { "code": null, "e": 10487, "s": 10480, "text": "Syntax" }, { "code": null, "e": 10538, "s": 10487, "text": "$(\".selector\").menu( \"collapseAll\", null, true );\n" }, { "code": null, "e": 10689, "s": 10538, "text": "This action removes menu functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments." }, { "code": null, "e": 10708, "s": 10689, "text": "Action - destroy()" }, { "code": null, "e": 10859, "s": 10708, "text": "This action removes menu functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments." }, { "code": null, "e": 10866, "s": 10859, "text": "Syntax" }, { "code": null, "e": 10901, "s": 10866, "text": "$(\".selector\").menu( \"destroy\" );\n" }, { "code": null, "e": 10975, "s": 10901, "text": "This action disables the menu. This method does not accept any arguments." }, { "code": null, "e": 10994, "s": 10975, "text": "Action - disable()" }, { "code": null, "e": 11068, "s": 10994, "text": "This action disables the menu. This method does not accept any arguments." }, { "code": null, "e": 11075, "s": 11068, "text": "Syntax" }, { "code": null, "e": 11110, "s": 11075, "text": "$(\".selector\").menu( \"disable\" );\n" }, { "code": null, "e": 11187, "s": 11110, "text": "This action enables the the menu. This method does not accept any arguments." }, { "code": null, "e": 11205, "s": 11187, "text": "Action - enable()" }, { "code": null, "e": 11282, "s": 11205, "text": "This action enables the the menu. This method does not accept any arguments." }, { "code": null, "e": 11289, "s": 11282, "text": "Syntax" }, { "code": null, "e": 11323, "s": 11289, "text": "$(\".selector\").menu( \"enable\" );\n" }, { "code": null, "e": 11481, "s": 11323, "text": "This action opens the sub-menu below the currently active item, if one exists. Where event is of type Event and represents what triggered the menu to expand." }, { "code": null, "e": 11509, "s": 11481, "text": "Action - expand( [event ] )" }, { "code": null, "e": 11667, "s": 11509, "text": "This action opens the sub-menu below the currently active item, if one exists. Where event is of type Event and represents what triggered the menu to expand." }, { "code": null, "e": 11674, "s": 11667, "text": "Syntax" }, { "code": null, "e": 11708, "s": 11674, "text": "$(\".selector\").menu( \"expand\" );\n" }, { "code": null, "e": 11987, "s": 11708, "text": "This action activates a particular menu item, begins opening any sub-menu if present and triggers the menu's focus event. Where event is of type Event and represents what triggered the menu to gain focus. and item is a jQuery object representing the menu item to focus/activate." }, { "code": null, "e": 12020, "s": 11987, "text": "Action - focus( [event ], item )" }, { "code": null, "e": 12299, "s": 12020, "text": "This action activates a particular menu item, begins opening any sub-menu if present and triggers the menu's focus event. Where event is of type Event and represents what triggered the menu to gain focus. and item is a jQuery object representing the menu item to focus/activate." }, { "code": null, "e": 12306, "s": 12299, "text": "Syntax" }, { "code": null, "e": 12380, "s": 12306, "text": "$(\".selector\").menu( \"focus\", null, menu.find( \".ui-menu-item:last\" ) );\n" }, { "code": null, "e": 12529, "s": 12380, "text": "This action returns a boolean value, which states if the current active menu item is the first menu item. This method does not accept any arguments." }, { "code": null, "e": 12552, "s": 12529, "text": "Action - isFirstItem()" }, { "code": null, "e": 12701, "s": 12552, "text": "This action returns a boolean value, which states if the current active menu item is the first menu item. This method does not accept any arguments." }, { "code": null, "e": 12708, "s": 12701, "text": "Syntax" }, { "code": null, "e": 12747, "s": 12708, "text": "$(\".selector\").menu( \"isFirstItem\" );\n" }, { "code": null, "e": 12895, "s": 12747, "text": "This action returns a boolean value, which states if the current active menu item is the last menu item. This method does not accept any arguments." }, { "code": null, "e": 12917, "s": 12895, "text": "Action - isLastItem()" }, { "code": null, "e": 13065, "s": 12917, "text": "This action returns a boolean value, which states if the current active menu item is the last menu item. This method does not accept any arguments." }, { "code": null, "e": 13072, "s": 13065, "text": "Syntax" }, { "code": null, "e": 13110, "s": 13072, "text": "$(\".selector\").menu( \"isLastItem\" );\n" }, { "code": null, "e": 13250, "s": 13110, "text": "This action delegates the active state to the next menu item. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 13276, "s": 13250, "text": "Action - next( [event ] )" }, { "code": null, "e": 13416, "s": 13276, "text": "This action delegates the active state to the next menu item. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 13423, "s": 13416, "text": "Syntax" }, { "code": null, "e": 13455, "s": 13423, "text": "$(\".selector\").menu( \"next\" );\n" }, { "code": null, "e": 13657, "s": 13455, "text": "This action moves active state to first menu item below the bottom of a scrollable menu or the last item if not scrollable. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 13687, "s": 13657, "text": "Action - nextPage( [event ] )" }, { "code": null, "e": 13889, "s": 13687, "text": "This action moves active state to first menu item below the bottom of a scrollable menu or the last item if not scrollable. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 13896, "s": 13889, "text": "Syntax" }, { "code": null, "e": 13932, "s": 13896, "text": "$(\".selector\").menu( \"nextPage\" );\n" }, { "code": null, "e": 14092, "s": 13932, "text": "This action gets the value currently associated with the specified optionName. Where optionName is of type String and represents the name of the option to get." }, { "code": null, "e": 14122, "s": 14092, "text": "Action - option( optionName )" }, { "code": null, "e": 14282, "s": 14122, "text": "This action gets the value currently associated with the specified optionName. Where optionName is of type String and represents the name of the option to get." }, { "code": null, "e": 14289, "s": 14282, "text": "Syntax" }, { "code": null, "e": 14354, "s": 14289, "text": "var isDisabled = $( \".selector\" ).menu( \"option\", \"disabled\" );\n" }, { "code": null, "e": 14452, "s": 14354, "text": "This action gets an object containing key/value pairs representing the current menu options hash." }, { "code": null, "e": 14470, "s": 14452, "text": "Action - option()" }, { "code": null, "e": 14568, "s": 14470, "text": "This action gets an object containing key/value pairs representing the current menu options hash." }, { "code": null, "e": 14575, "s": 14568, "text": "Syntax" }, { "code": null, "e": 14625, "s": 14575, "text": "var options = $( \".selector\" ).menu( \"option\" );\n" }, { "code": null, "e": 14857, "s": 14625, "text": "This action sets the value of the menu option associated with the specified optionName. Where optionName is of type String and represents name of option to set and value is of type Object and represents value to set for the option." }, { "code": null, "e": 14894, "s": 14857, "text": "Action - option( optionName, value )" }, { "code": null, "e": 15126, "s": 14894, "text": "This action sets the value of the menu option associated with the specified optionName. Where optionName is of type String and represents name of option to set and value is of type Object and represents value to set for the option." }, { "code": null, "e": 15133, "s": 15126, "text": "Syntax" }, { "code": null, "e": 15185, "s": 15133, "text": "$(\".selector\").menu( \"option\", \"disabled\", true );\n" }, { "code": null, "e": 15319, "s": 15185, "text": "This action sets one or more options for the menu. Where options is of type Object and represents a map of option-value pairs to set." }, { "code": null, "e": 15346, "s": 15319, "text": "Action - option( options )" }, { "code": null, "e": 15480, "s": 15346, "text": "This action sets one or more options for the menu. Where options is of type Object and represents a map of option-value pairs to set." }, { "code": null, "e": 15487, "s": 15480, "text": "Syntax" }, { "code": null, "e": 15541, "s": 15487, "text": "$(\".selector\").menu( \"option\", { disabled: true } );\n" }, { "code": null, "e": 15673, "s": 15541, "text": "This action moves active state to previous menu item. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 15703, "s": 15673, "text": "Action - previous( [event ] )" }, { "code": null, "e": 15835, "s": 15703, "text": "This action moves active state to previous menu item. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 15842, "s": 15835, "text": "Syntax" }, { "code": null, "e": 15878, "s": 15842, "text": "$(\".selector\").menu( \"previous\" );\n" }, { "code": null, "e": 16078, "s": 15878, "text": "This action moves active state to first menu item above the top of a scrollable menu or the first item if not scrollable. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 16112, "s": 16078, "text": "Action - previousPage( [event ] )" }, { "code": null, "e": 16312, "s": 16112, "text": "This action moves active state to first menu item above the top of a scrollable menu or the first item if not scrollable. Where event is of type Event and represents what triggered the focus to move." }, { "code": null, "e": 16319, "s": 16312, "text": "Syntax" }, { "code": null, "e": 16359, "s": 16319, "text": "$(\".selector\").menu( \"previousPage\" );\n" }, { "code": null, "e": 16491, "s": 16359, "text": "This action initializes sub-menus and menu items that have not already been initialized. This method does not accept any arguments." }, { "code": null, "e": 16510, "s": 16491, "text": "Action - refresh()" }, { "code": null, "e": 16642, "s": 16510, "text": "This action initializes sub-menus and menu items that have not already been initialized. This method does not accept any arguments." }, { "code": null, "e": 16649, "s": 16642, "text": "Syntax" }, { "code": null, "e": 16684, "s": 16649, "text": "$(\".selector\").menu( \"refresh\" );\n" }, { "code": null, "e": 16872, "s": 16684, "text": "This action selects the currently active menu item, collapses all sub-menus and triggers the menu's select event. Where event is of type Event and represents what triggered the selection." }, { "code": null, "e": 16900, "s": 16872, "text": "Action - select( [event ] )" }, { "code": null, "e": 17088, "s": 16900, "text": "This action selects the currently active menu item, collapses all sub-menus and triggers the menu's select event. Where event is of type Event and represents what triggered the selection." }, { "code": null, "e": 17095, "s": 17088, "text": "Syntax" }, { "code": null, "e": 17129, "s": 17095, "text": "$(\".selector\").menu( \"select\" );\n" }, { "code": null, "e": 17229, "s": 17129, "text": "This action returns a jQuery object containing the menu. This method does not accept any arguments." }, { "code": null, "e": 17247, "s": 17229, "text": "Action - widget()" }, { "code": null, "e": 17347, "s": 17247, "text": "This action returns a jQuery object containing the menu. This method does not accept any arguments." }, { "code": null, "e": 17354, "s": 17347, "text": "Syntax" }, { "code": null, "e": 17388, "s": 17354, "text": "$(\".selector\").menu( \"widget\" );\n" }, { "code": null, "e": 17472, "s": 17388, "text": "The following examples demonstrate how to use the actions given in the above table." }, { "code": null, "e": 17536, "s": 17472, "text": "The following example demonstrates the use of disable() method." }, { "code": null, "e": 18737, "s": 17536, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Menu functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-menu {\n width: 200px;\n }\n </style>\n <!-- Javascript -->\n \n <script>\n $(function() {\n $( \"#menu-3\" ).menu();\n $( \"#menu-3\" ).menu(\"disable\");\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <ul id = \"menu-3\">\n <li><a href = \"#\">Spring</a></li>\n <li><a href = \"#\">Hibernate</a></li>\n <li><a href = \"#\">Java</a>\n <ul>\n <li><a href = \"#\">Java IO</a></li>\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">Jaspr Reports</a></li>\n </ul>\n </li>\n <li><a href = \"#\">JSF</a></li>\n <li><a href = \"#\">HTML5</a></li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 18898, "s": 18737, "text": "Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 18905, "s": 18898, "text": "Spring" }, { "code": null, "e": 18915, "s": 18905, "text": "Hibernate" }, { "code": null, "e": 18951, "s": 18915, "text": "Java\n\nJava IO\nSwing\nJaspr Reports\n\n" }, { "code": null, "e": 18959, "s": 18951, "text": "Java IO" }, { "code": null, "e": 18965, "s": 18959, "text": "Swing" }, { "code": null, "e": 18979, "s": 18965, "text": "Jaspr Reports" }, { "code": null, "e": 18983, "s": 18979, "text": "JSF" }, { "code": null, "e": 18989, "s": 18983, "text": "HTML5" }, { "code": null, "e": 19045, "s": 18989, "text": "In the above example, you can see the menu is disabled." }, { "code": null, "e": 19124, "s": 19045, "text": "The following example demonstrates the use of focus() and collapseAll methods." }, { "code": null, "e": 20508, "s": 19124, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Menu functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-menu {\n width: 200px;\n }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n var menu = $(\"#menu-4\").menu();\n $( \"#menu-4\" ).menu(\n \"focus\", null, $( \"#menu-4\" ).menu().find( \".ui-menu-item:last\" ));\n $(menu).mouseleave(function () {\n menu.menu('collapseAll');\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <ul id = \"menu-4\">\n <li><a href = \"#\">Spring</a></li>\n <li><a href = \"#\">Hibernate</a></li>\n <li><a href = \"#\">JSF</a></li>\n <li><a href = \"#\">HTML5</a></li>\n <li><a href = \"#\">Java</a>\n <ul>\n <li><a href = \"#\">Java IO</a></li>\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">Jaspr Reports</a></li>\n </ul>\n </li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 20669, "s": 20508, "text": "Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 20676, "s": 20669, "text": "Spring" }, { "code": null, "e": 20686, "s": 20676, "text": "Hibernate" }, { "code": null, "e": 20690, "s": 20686, "text": "JSF" }, { "code": null, "e": 20696, "s": 20690, "text": "HTML5" }, { "code": null, "e": 20732, "s": 20696, "text": "Java\n\nJava IO\nSwing\nJaspr Reports\n\n" }, { "code": null, "e": 20740, "s": 20732, "text": "Java IO" }, { "code": null, "e": 20746, "s": 20740, "text": "Swing" }, { "code": null, "e": 20760, "s": 20746, "text": "Jaspr Reports" }, { "code": null, "e": 20915, "s": 20760, "text": "In the above example, you can see the focus is on the last menu item. Now expand the submenu and when the mouse leaves the submenu, the submenu is closed." }, { "code": null, "e": 21111, "s": 20915, "text": "In addition to the menu (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below −" }, { "code": null, "e": 21160, "s": 21111, "text": "This event is triggered when a menu loses focus." }, { "code": null, "e": 21184, "s": 21160, "text": "Event - blur(event, ui)" }, { "code": null, "e": 21335, "s": 21184, "text": "This event is triggered when a menu loses focus. Where event is of type Event, and ui is of type Object and represents the currently active menu item." }, { "code": null, "e": 21342, "s": 21335, "text": "Syntax" }, { "code": null, "e": 21405, "s": 21342, "text": "$( \".selector\" ).menu({\n blur: function( event, ui ) {}\n});\n" }, { "code": null, "e": 21453, "s": 21405, "text": "This event is triggered when a menu is created." }, { "code": null, "e": 21479, "s": 21453, "text": "Event - create(event, ui)" }, { "code": null, "e": 21583, "s": 21479, "text": "This event is triggered when a menu is created. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 21590, "s": 21583, "text": "Syntax" }, { "code": null, "e": 21655, "s": 21590, "text": "$( \".selector\" ).menu({\n create: function( event, ui ) {}\n});\n" }, { "code": null, "e": 21739, "s": 21655, "text": "This event is triggered when a menu gains focus or when any menu item is activated." }, { "code": null, "e": 21764, "s": 21739, "text": "Event - focus(event, ui)" }, { "code": null, "e": 21950, "s": 21764, "text": "This event is triggered when a menu gains focus or when any menu item is activated. Where event is of type Event, and ui is of type Object and represents the currently active menu item." }, { "code": null, "e": 21957, "s": 21950, "text": "Syntax" }, { "code": null, "e": 22021, "s": 21957, "text": "$( \".selector\" ).menu({\n focus: function( event, ui ) {}\n});\n" }, { "code": null, "e": 22075, "s": 22021, "text": "This event is triggered when a menu item is selected." }, { "code": null, "e": 22101, "s": 22075, "text": "Event - select(event, ui)" }, { "code": null, "e": 22257, "s": 22101, "text": "This event is triggered when a menu item is selected. Where event is of type Event, and ui is of type Object and represents the currently active menu item." }, { "code": null, "e": 22264, "s": 22257, "text": "Syntax" }, { "code": null, "e": 22329, "s": 22264, "text": "$( \".selector\" ).menu({\n select: function( event, ui ) {}\n});\n" }, { "code": null, "e": 22485, "s": 22329, "text": "The following example demonstrates the event method usage for menu widget functionality. This example demonstrates the use of event create, blur and focus." }, { "code": null, "e": 24185, "s": 22485, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Menu functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- CSS -->\n <style>\n .ui-menu {\n width: 200px;\n }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#menu-5\" ).menu({\n create: function( event, ui ) {\n var result = $( \"#result\" );\n result.append( \"Create event<br>\" );\n },\n blur: function( event, ui ) {\n var result = $( \"#result\" );\n result.append( \"Blur event<br>\" );\n },\n focus: function( event, ui ) {\n var result = $( \"#result\" );\n result.append( \"focus event<br>\" );\n }\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <ul id = \"menu-5\">\n <li><a href = \"#\">Spring</a></li>\n <li><a href = \"#\">Hibernate</a></li>\n <li><a href = \"#\">JSF</a></li>\n <li><a href = \"#\">HTML5</a></li>\n <li><a href = \"#\">Java</a>\n <ul>\n <li><a href = \"#\">Java IO</a></li>\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">Jaspr Reports</a></li>\n </ul>\n </li>\n </ul>\n <span id = \"result\"></span>\n </body>\n</html>" }, { "code": null, "e": 24346, "s": 24185, "text": "Let us save the above code in an HTML file menuexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 24353, "s": 24346, "text": "Spring" }, { "code": null, "e": 24363, "s": 24353, "text": "Hibernate" }, { "code": null, "e": 24367, "s": 24363, "text": "JSF" }, { "code": null, "e": 24373, "s": 24367, "text": "HTML5" }, { "code": null, "e": 24409, "s": 24373, "text": "Java\n\nJava IO\nSwing\nJaspr Reports\n\n" }, { "code": null, "e": 24417, "s": 24409, "text": "Java IO" }, { "code": null, "e": 24423, "s": 24417, "text": "Swing" }, { "code": null, "e": 24437, "s": 24423, "text": "Jaspr Reports" }, { "code": null, "e": 24519, "s": 24437, "text": "In the above example, we are printing the messages based on the events triggered." }, { "code": null, "e": 24526, "s": 24519, "text": " Print" }, { "code": null, "e": 24537, "s": 24526, "text": " Add Notes" } ]
R - If...Else Statement
An if statement can be followed by an optional else statement which executes when the boolean expression is false. The basic syntax for creating an if...else statement in R is − if(boolean_expression) { // statement(s) will execute if the boolean expression is true. } else { // statement(s) will execute if the boolean expression is false. } If the Boolean expression evaluates to be true, then the if block of code will be executed, otherwise else block of code will be executed. x <- c("what","is","truth") if("Truth" %in% x) { print("Truth is found") } else { print("Truth is not found") } When the above code is compiled and executed, it produces the following result − [1] "Truth is not found" Here "Truth" and "truth" are two different strings. An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if, else if, else statements there are few points to keep in mind. An if can have zero or one else and it must come after any else if's. An if can have zero or one else and it must come after any else if's. An if can have zero to many else if's and they must come before the else. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Once an else if succeeds, none of the remaining else if's or else's will be tested. The basic syntax for creating an if...else if...else statement in R is − if(boolean_expression 1) { // Executes when the boolean expression 1 is true. } else if( boolean_expression 2) { // Executes when the boolean expression 2 is true. } else if( boolean_expression 3) { // Executes when the boolean expression 3 is true. } else { // executes when none of the above condition is true. } x <- c("what","is","truth") if("Truth" %in% x) { print("Truth is found the first time") } else if ("truth" %in% x) { print("truth is found the second time") } else { print("No truth found") } When the above code is compiled and executed, it produces the following result − [1] "truth is found the second time" 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2517, "s": 2402, "text": "An if statement can be followed by an optional else statement which executes when the boolean expression is false." }, { "code": null, "e": 2580, "s": 2517, "text": "The basic syntax for creating an if...else statement in R is −" }, { "code": null, "e": 2752, "s": 2580, "text": "if(boolean_expression) {\n // statement(s) will execute if the boolean expression is true.\n} else {\n // statement(s) will execute if the boolean expression is false.\n}\n" }, { "code": null, "e": 2891, "s": 2752, "text": "If the Boolean expression evaluates to be true, then the if block of code will be executed, otherwise else block of code will be executed." }, { "code": null, "e": 3010, "s": 2891, "text": "x <- c(\"what\",\"is\",\"truth\")\n\nif(\"Truth\" %in% x) {\n print(\"Truth is found\")\n} else {\n print(\"Truth is not found\")\n}" }, { "code": null, "e": 3091, "s": 3010, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3117, "s": 3091, "text": "[1] \"Truth is not found\"\n" }, { "code": null, "e": 3169, "s": 3117, "text": "Here \"Truth\" and \"truth\" are two different strings." }, { "code": null, "e": 3327, "s": 3169, "text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 3405, "s": 3327, "text": "When using if, else if, else statements there are few points to keep in mind." }, { "code": null, "e": 3475, "s": 3405, "text": "An if can have zero or one else and it must come after any else if's." }, { "code": null, "e": 3545, "s": 3475, "text": "An if can have zero or one else and it must come after any else if's." }, { "code": null, "e": 3619, "s": 3545, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 3693, "s": 3619, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 3777, "s": 3693, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 3861, "s": 3777, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 3934, "s": 3861, "text": "The basic syntax for creating an if...else if...else statement in R is −" }, { "code": null, "e": 4262, "s": 3934, "text": "if(boolean_expression 1) {\n // Executes when the boolean expression 1 is true.\n} else if( boolean_expression 2) {\n // Executes when the boolean expression 2 is true.\n} else if( boolean_expression 3) {\n // Executes when the boolean expression 3 is true.\n} else {\n // executes when none of the above condition is true.\n}\n" }, { "code": null, "e": 4464, "s": 4262, "text": "x <- c(\"what\",\"is\",\"truth\")\n\nif(\"Truth\" %in% x) {\n print(\"Truth is found the first time\")\n} else if (\"truth\" %in% x) {\n print(\"truth is found the second time\")\n} else {\n print(\"No truth found\")\n}" }, { "code": null, "e": 4545, "s": 4464, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4583, "s": 4545, "text": "[1] \"truth is found the second time\"\n" }, { "code": null, "e": 4616, "s": 4583, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4631, "s": 4616, "text": " Nishant Malik" }, { "code": null, "e": 4666, "s": 4631, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4681, "s": 4666, "text": " Nishant Malik" }, { "code": null, "e": 4716, "s": 4681, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4731, "s": 4716, "text": " Nishant Malik" }, { "code": null, "e": 4764, "s": 4731, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 4778, "s": 4764, "text": " Asif Hussain" }, { "code": null, "e": 4813, "s": 4778, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4828, "s": 4813, "text": " Nishant Malik" }, { "code": null, "e": 4863, "s": 4828, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4877, "s": 4863, "text": " Asif Hussain" }, { "code": null, "e": 4884, "s": 4877, "text": " Print" }, { "code": null, "e": 4895, "s": 4884, "text": " Add Notes" } ]
BigInteger doubleValue() Method in Java - GeeksforGeeks
04 Dec, 2018 The java.math.BigInteger.doubleValue() converts this BigInteger to a double value. If the value return by this function is too big for a magnitude to represent as a double then it will be converted to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate. There is a chance that this conversion can lose information about the precision of the BigInteger value. Syntax: public double doubleValue() Return Value: The method returns a double value which represents double value for this BigInteger. Examples: Input: BigInteger1=32145 Output: 32145.0 Explanation: BigInteger1.doubleValue()=32145.0. Input: BigInteger1=32145535361361525377 Output: 3.2145535E19 Explanation: BigInteger1.doubleValue()=3.2145535E19. This BigInteger is too big for a magnitude to represent as a double then it will be converted to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate. Below programs illustrate doubleValue() method of BigInteger class: Example 1: // Java program to demonstrate doubleValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("32145"); b2 = new BigInteger("7613721"); // apply doubleValue() method double doubleValueOfb1 = b1.doubleValue(); double doubleValueOfb2 = b2.doubleValue(); // print doubleValue System.out.println("doubleValue of " + b1 + " : " + doubleValueOfb1); System.out.println("doubleValue of " + b2 + " : " + doubleValueOfb2); }} doubleValue of 32145 : 32145.0 doubleValue of 7613721 : 7613721.0 Example 2: When returned double value is too big for a magnitude to represent as a double. // Java program to demonstrate doubleValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("32145535361361525377"); b2 = new BigInteger("7613721535372632367351"); // apply doubleValue() method double doubleValueOfb1 = b1.doubleValue(); double doubleValueOfb2 = b2.doubleValue(); // print doubleValue System.out.println("doubleValue of " + b1 + " : " + doubleValueOfb1); System.out.println("doubleValue of " + b2 + " : " + doubleValueOfb2); }} doubleValue of 32145535361361525377 : 3.2145535361361527E19 doubleValue of 7613721535372632367351 : 7.613721535372632E21 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#doubleValue() java-basics Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24323, "s": 23948, "text": "The java.math.BigInteger.doubleValue() converts this BigInteger to a double value. If the value return by this function is too big for a magnitude to represent as a double then it will be converted to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate. There is a chance that this conversion can lose information about the precision of the BigInteger value." }, { "code": null, "e": 24331, "s": 24323, "text": "Syntax:" }, { "code": null, "e": 24359, "s": 24331, "text": "public double doubleValue()" }, { "code": null, "e": 24458, "s": 24359, "text": "Return Value: The method returns a double value which represents double value for this BigInteger." }, { "code": null, "e": 24468, "s": 24458, "text": "Examples:" }, { "code": null, "e": 24841, "s": 24468, "text": "Input: BigInteger1=32145\nOutput: 32145.0\nExplanation: BigInteger1.doubleValue()=32145.0.\n\nInput: BigInteger1=32145535361361525377\nOutput: 3.2145535E19\nExplanation: BigInteger1.doubleValue()=3.2145535E19. This BigInteger is too big for \na magnitude to represent as a double then it will be converted to Double.NEGATIVE_INFINITY \nor Double.POSITIVE_INFINITY as appropriate.\n" }, { "code": null, "e": 24909, "s": 24841, "text": "Below programs illustrate doubleValue() method of BigInteger class:" }, { "code": null, "e": 24920, "s": 24909, "text": "Example 1:" }, { "code": "// Java program to demonstrate doubleValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"32145\"); b2 = new BigInteger(\"7613721\"); // apply doubleValue() method double doubleValueOfb1 = b1.doubleValue(); double doubleValueOfb2 = b2.doubleValue(); // print doubleValue System.out.println(\"doubleValue of \" + b1 + \" : \" + doubleValueOfb1); System.out.println(\"doubleValue of \" + b2 + \" : \" + doubleValueOfb2); }}", "e": 25560, "s": 24920, "text": null }, { "code": null, "e": 25627, "s": 25560, "text": "doubleValue of 32145 : 32145.0\ndoubleValue of 7613721 : 7613721.0\n" }, { "code": null, "e": 25718, "s": 25627, "text": "Example 2: When returned double value is too big for a magnitude to represent as a double." }, { "code": "// Java program to demonstrate doubleValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"32145535361361525377\"); b2 = new BigInteger(\"7613721535372632367351\"); // apply doubleValue() method double doubleValueOfb1 = b1.doubleValue(); double doubleValueOfb2 = b2.doubleValue(); // print doubleValue System.out.println(\"doubleValue of \" + b1 + \" : \" + doubleValueOfb1); System.out.println(\"doubleValue of \" + b2 + \" : \" + doubleValueOfb2); }}", "e": 26388, "s": 25718, "text": null }, { "code": null, "e": 26510, "s": 26388, "text": "doubleValue of 32145535361361525377 : 3.2145535361361527E19\ndoubleValue of 7613721535372632367351 : 7.613721535372632E21\n" }, { "code": null, "e": 26603, "s": 26510, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#doubleValue()" }, { "code": null, "e": 26615, "s": 26603, "text": "java-basics" }, { "code": null, "e": 26631, "s": 26615, "text": "Java-BigInteger" }, { "code": null, "e": 26646, "s": 26631, "text": "Java-Functions" }, { "code": null, "e": 26656, "s": 26646, "text": "java-math" }, { "code": null, "e": 26674, "s": 26656, "text": "Java-math-package" }, { "code": null, "e": 26679, "s": 26674, "text": "Java" }, { "code": null, "e": 26695, "s": 26679, "text": "Java-BigInteger" }, { "code": null, "e": 26700, "s": 26695, "text": "Java" }, { "code": null, "e": 26798, "s": 26700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26813, "s": 26798, "text": "Stream In Java" }, { "code": null, "e": 26859, "s": 26813, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26880, "s": 26859, "text": "Constructors in Java" }, { "code": null, "e": 26899, "s": 26880, "text": "Exceptions in Java" }, { "code": null, "e": 26929, "s": 26899, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26946, "s": 26929, "text": "Generics in Java" }, { "code": null, "e": 26989, "s": 26946, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27018, "s": 26989, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27039, "s": 27018, "text": "Introduction to Java" } ]
How to Get Local IP Address of System using PHP ? - GeeksforGeeks
02 Mar, 2020 IP (Internet Protocol) Address is an address of your network hardware. It helps in connecting your computer to other devices on your network and all over the world. An IP Address is made up of numbers or characters combined by ‘.’ symbol. Example: It is an example of IP address. 506.457.14.512 All devices that are connected to an internet connection have a unique IP address which literally gives the idea that a large number of IP addresses had to be created for every system. Local IP address: It is the IP address of your computer system which is meant to be kept private and thus is also known as private IP addresses. This article focuses on how to extract the IP address. A private IP address is the address of your device connected to the home or business network. If you have a few different devices connected to one ISP (Internet Service Provider), then all your devices will have a unique private IP address. This IP address cannot be accessed from devices outside your home or business network. Private IP addresses are not unique because there is a limited number of devices on your network. There are some other types of IP addresses that exist like, public IP addresses, static IP addresses and dynamic IP addresses that follow the same format for representation. IPv4 address: The IPv4 version used to configure IP addresses in numerical value and it uses the hexadecimal number system to complete its job i.e. what makes it possible to get millions of IP, different for every system. Example: In this example, we are trying to get the local IP address without using terminal and its commands. Instead, we are using a PHP program to get the same job done. We will be required two methods that are mentioned below: getHostByName() Function: It gets the IPv4 address corresponding to a given Internet host name. getHostName() Function: It gets the standard host name for the local machine. Program: Here, first we get the name of the local machine as the string and then by using that we will get the corresponding address to that name.<?php // Declaring a variable to hold the IP// address getHostName() gets the name// of the local machine getHostByName()// gets the corresponding IP$localIP = getHostByName(getHostName()); // Displaying the address echo $localIP; ?> <?php // Declaring a variable to hold the IP// address getHostName() gets the name// of the local machine getHostByName()// gets the corresponding IP$localIP = getHostByName(getHostName()); // Displaying the address echo $localIP; ?> The fact that no output is provided with this program because of security reasons. Sharing of IP addresses can lead to security breaches and one should be careful not to share it. Any unethical access can cost you theft of personal space and even identity. PHP-Misc Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to 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 How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to run JavaScript from PHP? How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP
[ { "code": null, "e": 24874, "s": 24846, "text": "\n02 Mar, 2020" }, { "code": null, "e": 25113, "s": 24874, "text": "IP (Internet Protocol) Address is an address of your network hardware. It helps in connecting your computer to other devices on your network and all over the world. An IP Address is made up of numbers or characters combined by ‘.’ symbol." }, { "code": null, "e": 25154, "s": 25113, "text": "Example: It is an example of IP address." }, { "code": null, "e": 25169, "s": 25154, "text": "506.457.14.512" }, { "code": null, "e": 25354, "s": 25169, "text": "All devices that are connected to an internet connection have a unique IP address which literally gives the idea that a large number of IP addresses had to be created for every system." }, { "code": null, "e": 26154, "s": 25354, "text": "Local IP address: It is the IP address of your computer system which is meant to be kept private and thus is also known as private IP addresses. This article focuses on how to extract the IP address. A private IP address is the address of your device connected to the home or business network. If you have a few different devices connected to one ISP (Internet Service Provider), then all your devices will have a unique private IP address. This IP address cannot be accessed from devices outside your home or business network. Private IP addresses are not unique because there is a limited number of devices on your network. There are some other types of IP addresses that exist like, public IP addresses, static IP addresses and dynamic IP addresses that follow the same format for representation." }, { "code": null, "e": 26376, "s": 26154, "text": "IPv4 address: The IPv4 version used to configure IP addresses in numerical value and it uses the hexadecimal number system to complete its job i.e. what makes it possible to get millions of IP, different for every system." }, { "code": null, "e": 26605, "s": 26376, "text": "Example: In this example, we are trying to get the local IP address without using terminal and its commands. Instead, we are using a PHP program to get the same job done. We will be required two methods that are mentioned below:" }, { "code": null, "e": 26701, "s": 26605, "text": "getHostByName() Function: It gets the IPv4 address corresponding to a given Internet host name." }, { "code": null, "e": 26779, "s": 26701, "text": "getHostName() Function: It gets the standard host name for the local machine." }, { "code": null, "e": 27162, "s": 26779, "text": "Program: Here, first we get the name of the local machine as the string and then by using that we will get the corresponding address to that name.<?php // Declaring a variable to hold the IP// address getHostName() gets the name// of the local machine getHostByName()// gets the corresponding IP$localIP = getHostByName(getHostName()); // Displaying the address echo $localIP; ?>" }, { "code": "<?php // Declaring a variable to hold the IP// address getHostName() gets the name// of the local machine getHostByName()// gets the corresponding IP$localIP = getHostByName(getHostName()); // Displaying the address echo $localIP; ?>", "e": 27399, "s": 27162, "text": null }, { "code": null, "e": 27656, "s": 27399, "text": "The fact that no output is provided with this program because of security reasons. Sharing of IP addresses can lead to security breaches and one should be careful not to share it. Any unethical access can cost you theft of personal space and even identity." }, { "code": null, "e": 27665, "s": 27656, "text": "PHP-Misc" }, { "code": null, "e": 27672, "s": 27665, "text": "Picked" }, { "code": null, "e": 27676, "s": 27672, "text": "PHP" }, { "code": null, "e": 27689, "s": 27676, "text": "PHP Programs" }, { "code": null, "e": 27706, "s": 27689, "text": "Web Technologies" }, { "code": null, "e": 27733, "s": 27706, "text": "Web technologies Questions" }, { "code": null, "e": 27737, "s": 27733, "text": "PHP" }, { "code": null, "e": 27835, "s": 27737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27875, "s": 27835, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27920, "s": 27875, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27962, "s": 27920, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27994, "s": 27962, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 28027, "s": 27994, "text": "Download file from URL using PHP" }, { "code": null, "e": 28067, "s": 28027, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28119, "s": 28067, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28151, "s": 28119, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 28193, "s": 28151, "text": "How to pass JavaScript variables to PHP ?" } ]
Version control your database Part 1: creating migrations and seeding | by Mike Huls | Towards Data Science
If you are not working with migrations in your database you’re missing out. Like Git manages changes to source code, you can use migrations to keep track of changes to your database. Execute and revert changes and get your database back into a previous state. Setting up migrations is easier than you think and the advantages are huge. Migrations are database-independent, offer one source of the truth, track changes and can even seed your database with some data. When you’ve read this article you’ll be able to: Create tables with indices and foreign keys Easily plan, validate, and safely apply changes in a dev database and then sync all the changes to your production database reset your development database (undo all, migrate again) Create all specified tables in your database, including indices and associations Seed a database (insert data) Execute a migration to any database (e.g. both PostgreSQL and SQL Server) I will try to showcase all of these features with examples that use real code that you can re-use. I’ve cut this process in 4 steps: Setting up, Creating Migrations, Executing and undoing and, lastly, Seeding. Don’t be discouraged by the length of this article, you’ll breeze through using the easy-to-follow steps. Lets go! At the end of this step Sequelize is installed and ready for use. If you are an experienced programmer then skip the ‘Explanation’-parts. At the bottom of this part you’ll find a summary of all commands. Install NPM. Verify with npm -v Explanation:For this project you need to install NPM the JavaScript package management system. It resembles pip in Python and you can use it to install packages. Download NPM here and follow the installation-instructions. Once the installation is finished you should be able to open a terminal (like command prompt) and run nmp -v. If you se a version (like v14.15.4 then node is correctly installed. Open a terminal, navigate to your project folder and execute npm init Explanation:Create a folder you want to create this project in for example c:/migrationtool. Open a terminal and navigate to this folder: cd c:/migrationtoolCreate a new project by calling npm init. NPM will ask you some questions about the project name, version, description and the author name. These are all not required, can be skipped and can also be filled out later. When finished a file appears in the project folder called ‘package.json’. In here all of our project metadata will be registered. In the root folder execute # installing packagesnpm install --save sequelize sequelize-clinpm install --save pg pg-hstore # for PostgreSQLnpm install --save tedious # for SQL Server Explanation:Our project is prepared, let’s install our packages! First we need Sequelize and Sequelize-cli. These packages allow us to start making and executing migrations: npm install --save sequelize sequelize-cli. This is the main package that will allow us to create migrations. To actually execute these migrations (e.g. create a database, table or new column) Sequelize needs to know a little more about the database. For demonstration purposes we’re going to use two kinds of databases in our project: PostgreSQL and SQL Server. In order for Sequelize to work with these databases we need to install some extra packages: npm install — save pg pgh-store tedious. If you use another database, like mysql sqllite or many others, you can which package to use here. You’ll notice that a new folder has appeared; node_modules. All of our packages are installed in here. Also our package.json file has expanded, keeping track of all of our installed packages. In your root folder execute npx sequelize-cli init and run through the steps Explanation:All of our packages are installed. Initialize Sequelize: npx sequelize-cli init. Notice that we are using NPX here, not NPM. NPX is used to execute the packages we’ve installed with NPM.When the command has finished you’ll notice that three more folders have appeared: config: holds files like databasecredentials models: holds files that respresent out database tables as models seeders: files that insert into and delete data from tables Sequelize is ready for use. Before we dig in we’re going to make working with Sequelize a bit easier for ourselvesWe are going to make it a bit easier to work with our configs. JS files are a bit easier to work with than JSON in my experience. Go to the config folder and change config.json to config.js. Then adjust the content from { "development": { to module.exports: { "development": { We’ve made this change to we need to tell Sequelize how to handle the new situation. Go to the root of your project (c:/migrationtool/) and create a new file. Name this file .sequelizerc. Notice that this file does not have a name, only an extension. Open the file and add the content below. This tells Sequelize that we’re now using config.js instead of config.json. const path = require('path'); module.exports = { "config": path.resolve('./config', 'config.js'), "models-path": path.resolve('./models'), "migrations-path": path.resolve('./migrations'), "seeders-path": path.resolve('./seeders') } Last step before the fun starts: Go to the models folder (c://migrationtool/models) and open the index.js file. On line 8 replace config.json to config.js. We’re ready to go! Check out the commands we’ve use before we go to the next step. #Creating foldercd c:/mkdir migrationtoolcd migrationtool#Setting up projectnpm init# installing packagesnpm install --save sequelize sequelize-clinpm install --save pg pg-hstore # for PostgreSQLnpm install --save tedious # for SQL Server# Initialize Sequelizenpx sequelize-cli init In Sequelize a migration is a JavaScript file. It’s content describe what should happen on executing and undoing, for example “create a schema named ‘persondata’. Lets create one! In your root folder execute the following command.npx sequelize-cli migration:create -- name create_schemas. This will tell sequelize to create a new migration. Executing this command will generate a file in our migrations-folder called something like this: ‘20210519183705-create_schemas.js’. Inside you’ll find the code below. As you can see the migration contains two function ‘up’ and ‘down’. The first function will contain all the code to achieve what we want to do; create schema. The second function will undo the ‘up’ function; it is it’s opposite. Let’s finish our first migration: This code tells the queryInterface to create a schema called “app”. Lets speed it up a bit; we’ll create new migration with npx sequelize-cli migration:create -- name create_country_table. Give the newly created migration the following content: This migration is a bit fancier. First it creates a transaction in which it defines the table with a few columns. It then adds a we indices to the table and then commits it. The transaction is for ensuring that either everything succeeds or nothing. If creating one of the indices fails then it rolls back creating the table. The down-function just drops the newly created table. Also notice that the Created and Modified columns have default values. Nothing yet happened in our database. We’ve just generated some instructions that we now have to execute. We want to migrate the instructions to the database. First we’re going to define our database connection, then we’ll use that connection to tell the database how to perform the migration Edit the contents of our config.js file (in root/config folder). I’ve created two database connections: module.exports = { development: { username: "mike", password: "my_secret_password", database: "country_db_dev", host: "localhost", port: "5432", dialect: "postgres" }, production: { username: "mike", password: "my_secret_password", database: "country_db", host: "localhost", port: "1433", dialect: "mssql" }} Explanation:I’ve made two connections: dev and production. These file allow our migration tool to connect to a database to execute the migrations. When we tell Sequelize to execute a migration it needs to know to which database to connect. We do this by setting NODE_ENV to the name of one of our database connections. We have “development” and “production”. Lets connect with “development”. Open a terminal in your root folder and execute on of the lines below (match your OS): # On windowsSET NODE_ENV=development# On OSXexport NODE_ENV=development#On powershell$env:NODE_ENV="development" Now that Sequelize knows where to write to we can execute our migrations. Notice that in the previous step we’ve defined our database. We can execute our migrations to any database we’ve downloaded packages for in step 1.3 in this article. This way we can test our migrations in PostgreSQL and then migrate everything to our SQL Server production database! Lets execute: npx sequelize-cli db:migrate This code will execute all of the migrations, creating our schema and a table inside, check it out: Wait go back! Call the code below to drop the table and schema. npx sequelize-cli db:migrate:undo:all. Look inside your database, it’s all clean! You can also undo untill a specific migration by specifying the file name in the command belownpx sequelize-cli db:migrate:undo:all — to XXXXXXXXXXXXXX-create_country_table.js Seeding a database is a lot like creating a migration. Lets quickly run through the code. Step 1: generate a seed filenpx sequelize-cli seed:generate --name seed_country_tableAnd the content: Execute it with: npx sequelize-cli db:seed:all Like with a migration undo seeds withnpx sequelize-cli db:seed:undo`Or up untill a specific seed likenpx sequelize-cli db:seed:undo — seed XXXXXX-seed_country_table.js We’ve accomplished quite a bit today! We have accomplished the following: Installed Node Installed Sequelize and all necessary packages Configured Sequelize Created some migrations Executed and undid the migrations Created some seeds Executed and undid seeds Click here for the next part which we’ll focus on the more advanced stuff; we’ll get into creating associations between tables and strategies on how records should act once a record it depends on gets deleted. Follow me to stay tuned!
[ { "code": null, "e": 432, "s": 172, "text": "If you are not working with migrations in your database you’re missing out. Like Git manages changes to source code, you can use migrations to keep track of changes to your database. Execute and revert changes and get your database back into a previous state." }, { "code": null, "e": 687, "s": 432, "text": "Setting up migrations is easier than you think and the advantages are huge. Migrations are database-independent, offer one source of the truth, track changes and can even seed your database with some data. When you’ve read this article you’ll be able to:" }, { "code": null, "e": 731, "s": 687, "text": "Create tables with indices and foreign keys" }, { "code": null, "e": 855, "s": 731, "text": "Easily plan, validate, and safely apply changes in a dev database and then sync all the changes to your production database" }, { "code": null, "e": 913, "s": 855, "text": "reset your development database (undo all, migrate again)" }, { "code": null, "e": 994, "s": 913, "text": "Create all specified tables in your database, including indices and associations" }, { "code": null, "e": 1024, "s": 994, "text": "Seed a database (insert data)" }, { "code": null, "e": 1098, "s": 1024, "text": "Execute a migration to any database (e.g. both PostgreSQL and SQL Server)" }, { "code": null, "e": 1423, "s": 1098, "text": "I will try to showcase all of these features with examples that use real code that you can re-use. I’ve cut this process in 4 steps: Setting up, Creating Migrations, Executing and undoing and, lastly, Seeding. Don’t be discouraged by the length of this article, you’ll breeze through using the easy-to-follow steps. Lets go!" }, { "code": null, "e": 1627, "s": 1423, "text": "At the end of this step Sequelize is installed and ready for use. If you are an experienced programmer then skip the ‘Explanation’-parts. At the bottom of this part you’ll find a summary of all commands." }, { "code": null, "e": 1659, "s": 1627, "text": "Install NPM. Verify with npm -v" }, { "code": null, "e": 2060, "s": 1659, "text": "Explanation:For this project you need to install NPM the JavaScript package management system. It resembles pip in Python and you can use it to install packages. Download NPM here and follow the installation-instructions. Once the installation is finished you should be able to open a terminal (like command prompt) and run nmp -v. If you se a version (like v14.15.4 then node is correctly installed." }, { "code": null, "e": 2130, "s": 2060, "text": "Open a terminal, navigate to your project folder and execute npm init" }, { "code": null, "e": 2634, "s": 2130, "text": "Explanation:Create a folder you want to create this project in for example c:/migrationtool. Open a terminal and navigate to this folder: cd c:/migrationtoolCreate a new project by calling npm init. NPM will ask you some questions about the project name, version, description and the author name. These are all not required, can be skipped and can also be filled out later. When finished a file appears in the project folder called ‘package.json’. In here all of our project metadata will be registered." }, { "code": null, "e": 2661, "s": 2634, "text": "In the root folder execute" }, { "code": null, "e": 2825, "s": 2661, "text": "# installing packagesnpm install --save sequelize sequelize-clinpm install --save pg pg-hstore # for PostgreSQLnpm install --save tedious # for SQL Server" }, { "code": null, "e": 3786, "s": 2825, "text": "Explanation:Our project is prepared, let’s install our packages! First we need Sequelize and Sequelize-cli. These packages allow us to start making and executing migrations: npm install --save sequelize sequelize-cli. This is the main package that will allow us to create migrations. To actually execute these migrations (e.g. create a database, table or new column) Sequelize needs to know a little more about the database. For demonstration purposes we’re going to use two kinds of databases in our project: PostgreSQL and SQL Server. In order for Sequelize to work with these databases we need to install some extra packages: npm install — save pg pgh-store tedious. If you use another database, like mysql sqllite or many others, you can which package to use here. You’ll notice that a new folder has appeared; node_modules. All of our packages are installed in here. Also our package.json file has expanded, keeping track of all of our installed packages." }, { "code": null, "e": 3863, "s": 3786, "text": "In your root folder execute npx sequelize-cli init and run through the steps" }, { "code": null, "e": 4144, "s": 3863, "text": "Explanation:All of our packages are installed. Initialize Sequelize: npx sequelize-cli init. Notice that we are using NPX here, not NPM. NPX is used to execute the packages we’ve installed with NPM.When the command has finished you’ll notice that three more folders have appeared:" }, { "code": null, "e": 4189, "s": 4144, "text": "config: holds files like databasecredentials" }, { "code": null, "e": 4255, "s": 4189, "text": "models: holds files that respresent out database tables as models" }, { "code": null, "e": 4315, "s": 4255, "text": "seeders: files that insert into and delete data from tables" }, { "code": null, "e": 4649, "s": 4315, "text": "Sequelize is ready for use. Before we dig in we’re going to make working with Sequelize a bit easier for ourselvesWe are going to make it a bit easier to work with our configs. JS files are a bit easier to work with than JSON in my experience. Go to the config folder and change config.json to config.js. Then adjust the content from" }, { "code": null, "e": 4669, "s": 4649, "text": "{ \"development\": {" }, { "code": null, "e": 4672, "s": 4669, "text": "to" }, { "code": null, "e": 4710, "s": 4672, "text": "module.exports: { \"development\": {" }, { "code": null, "e": 5078, "s": 4710, "text": "We’ve made this change to we need to tell Sequelize how to handle the new situation. Go to the root of your project (c:/migrationtool/) and create a new file. Name this file .sequelizerc. Notice that this file does not have a name, only an extension. Open the file and add the content below. This tells Sequelize that we’re now using config.js instead of config.json." }, { "code": null, "e": 5321, "s": 5078, "text": "const path = require('path'); module.exports = { \"config\": path.resolve('./config', 'config.js'), \"models-path\": path.resolve('./models'), \"migrations-path\": path.resolve('./migrations'), \"seeders-path\": path.resolve('./seeders') }" }, { "code": null, "e": 5477, "s": 5321, "text": "Last step before the fun starts: Go to the models folder (c://migrationtool/models) and open the index.js file. On line 8 replace config.json to config.js." }, { "code": null, "e": 5560, "s": 5477, "text": "We’re ready to go! Check out the commands we’ve use before we go to the next step." }, { "code": null, "e": 5852, "s": 5560, "text": "#Creating foldercd c:/mkdir migrationtoolcd migrationtool#Setting up projectnpm init# installing packagesnpm install --save sequelize sequelize-clinpm install --save pg pg-hstore # for PostgreSQLnpm install --save tedious # for SQL Server# Initialize Sequelizenpx sequelize-cli init" }, { "code": null, "e": 6032, "s": 5852, "text": "In Sequelize a migration is a JavaScript file. It’s content describe what should happen on executing and undoing, for example “create a schema named ‘persondata’. Lets create one!" }, { "code": null, "e": 6361, "s": 6032, "text": "In your root folder execute the following command.npx sequelize-cli migration:create -- name create_schemas. This will tell sequelize to create a new migration. Executing this command will generate a file in our migrations-folder called something like this: ‘20210519183705-create_schemas.js’. Inside you’ll find the code below." }, { "code": null, "e": 6624, "s": 6361, "text": "As you can see the migration contains two function ‘up’ and ‘down’. The first function will contain all the code to achieve what we want to do; create schema. The second function will undo the ‘up’ function; it is it’s opposite. Let’s finish our first migration:" }, { "code": null, "e": 6692, "s": 6624, "text": "This code tells the queryInterface to create a schema called “app”." }, { "code": null, "e": 6869, "s": 6692, "text": "Lets speed it up a bit; we’ll create new migration with npx sequelize-cli migration:create -- name create_country_table. Give the newly created migration the following content:" }, { "code": null, "e": 7249, "s": 6869, "text": "This migration is a bit fancier. First it creates a transaction in which it defines the table with a few columns. It then adds a we indices to the table and then commits it. The transaction is for ensuring that either everything succeeds or nothing. If creating one of the indices fails then it rolls back creating the table. The down-function just drops the newly created table." }, { "code": null, "e": 7320, "s": 7249, "text": "Also notice that the Created and Modified columns have default values." }, { "code": null, "e": 7613, "s": 7320, "text": "Nothing yet happened in our database. We’ve just generated some instructions that we now have to execute. We want to migrate the instructions to the database. First we’re going to define our database connection, then we’ll use that connection to tell the database how to perform the migration" }, { "code": null, "e": 7717, "s": 7613, "text": "Edit the contents of our config.js file (in root/config folder). I’ve created two database connections:" }, { "code": null, "e": 8066, "s": 7717, "text": "module.exports = { development: { username: \"mike\", password: \"my_secret_password\", database: \"country_db_dev\", host: \"localhost\", port: \"5432\", dialect: \"postgres\" }, production: { username: \"mike\", password: \"my_secret_password\", database: \"country_db\", host: \"localhost\", port: \"1433\", dialect: \"mssql\" }}" }, { "code": null, "e": 8213, "s": 8066, "text": "Explanation:I’ve made two connections: dev and production. These file allow our migration tool to connect to a database to execute the migrations." }, { "code": null, "e": 8545, "s": 8213, "text": "When we tell Sequelize to execute a migration it needs to know to which database to connect. We do this by setting NODE_ENV to the name of one of our database connections. We have “development” and “production”. Lets connect with “development”. Open a terminal in your root folder and execute on of the lines below (match your OS):" }, { "code": null, "e": 8658, "s": 8545, "text": "# On windowsSET NODE_ENV=development# On OSXexport NODE_ENV=development#On powershell$env:NODE_ENV=\"development\"" }, { "code": null, "e": 9029, "s": 8658, "text": "Now that Sequelize knows where to write to we can execute our migrations. Notice that in the previous step we’ve defined our database. We can execute our migrations to any database we’ve downloaded packages for in step 1.3 in this article. This way we can test our migrations in PostgreSQL and then migrate everything to our SQL Server production database! Lets execute:" }, { "code": null, "e": 9058, "s": 9029, "text": "npx sequelize-cli db:migrate" }, { "code": null, "e": 9158, "s": 9058, "text": "This code will execute all of the migrations, creating our schema and a table inside, check it out:" }, { "code": null, "e": 9480, "s": 9158, "text": "Wait go back! Call the code below to drop the table and schema. npx sequelize-cli db:migrate:undo:all. Look inside your database, it’s all clean! You can also undo untill a specific migration by specifying the file name in the command belownpx sequelize-cli db:migrate:undo:all — to XXXXXXXXXXXXXX-create_country_table.js" }, { "code": null, "e": 9570, "s": 9480, "text": "Seeding a database is a lot like creating a migration. Lets quickly run through the code." }, { "code": null, "e": 9672, "s": 9570, "text": "Step 1: generate a seed filenpx sequelize-cli seed:generate --name seed_country_tableAnd the content:" }, { "code": null, "e": 9719, "s": 9672, "text": "Execute it with: npx sequelize-cli db:seed:all" }, { "code": null, "e": 9887, "s": 9719, "text": "Like with a migration undo seeds withnpx sequelize-cli db:seed:undo`Or up untill a specific seed likenpx sequelize-cli db:seed:undo — seed XXXXXX-seed_country_table.js" }, { "code": null, "e": 9961, "s": 9887, "text": "We’ve accomplished quite a bit today! We have accomplished the following:" }, { "code": null, "e": 9976, "s": 9961, "text": "Installed Node" }, { "code": null, "e": 10023, "s": 9976, "text": "Installed Sequelize and all necessary packages" }, { "code": null, "e": 10044, "s": 10023, "text": "Configured Sequelize" }, { "code": null, "e": 10068, "s": 10044, "text": "Created some migrations" }, { "code": null, "e": 10102, "s": 10068, "text": "Executed and undid the migrations" }, { "code": null, "e": 10121, "s": 10102, "text": "Created some seeds" }, { "code": null, "e": 10146, "s": 10121, "text": "Executed and undid seeds" } ]
PyTorch – torch.linalg.solve() Method
To solve a square system of linear equations with unique solution, we could apply the torch.linalg.solve() method. This method takes two parameters − first, the coefficient matrix A, and first, the coefficient matrix A, and second, the right-hand tensor b. second, the right-hand tensor b. Where A is a square matrix and b is a vector. The solution is unique if A invertible. We can solve a number of systems of linear equations. In this case, A is a batch of square matrices and b is a batch of vectors. torch.linalg.solve(A, b) A – Square matrix or batch of square matrices. It is the coefficient matrix of system of linear equations. A – Square matrix or batch of square matrices. It is the coefficient matrix of system of linear equations. b – Vector or a batch of vectors. It's the right-hand tensor of the linear system. b – Vector or a batch of vectors. It's the right-hand tensor of the linear system. It returns a tensor of the solution of the system of linear equations. Note − This method assumes that the coefficient matrix A is invertible. If it is not invertible, a Runtime Error will be raised. We could use the following steps to solve a square system of linear equations. Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it. Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it. import torch Define a Coefficient matrix and the right-hand side tensor for the given square system of linear equations. Define a Coefficient matrix and the right-hand side tensor for the given square system of linear equations. A = torch.tensor([[2., 3.],[1., -2.]]) b = torch.tensor([3., 0.]) Compute the unique solution using torch.linalg.solve(A,b). Coefficient matrix A must be invertible. Compute the unique solution using torch.linalg.solve(A,b). Coefficient matrix A must be invertible. X = torch.linalg.solve(A, b) Display the solution. Display the solution. print("Solution:\n", X) Check if the calculated solution is correct or not. Check if the calculated solution is correct or not. print(torch.allclose(A @ X, b)) # True for correct solution Take a look at the following example − # import required library import torch ''' Let's suppose our square system of linear equations is: 2x + 3y = 3 x - 2y = 0 ''' print("Linear equation:") print("2x + 3y = 3") print("x - 2y = 0") # define the coefficient matrix A A = torch.tensor([[2., 3.],[1., -2.]]) # define right hand side tensor b b = torch.tensor([3., 0.]) # Solve the linear equation X = torch.linalg.solve(A, b) # print the solution of above linear equation print("Solution:\n", X) # check above solution to be true print(torch.allclose(A @ X, b)) It will produce the following output − Linear equation: 2x + 3y = 3 x - 2y = 0 Solution: tensor([0.8571, 0.4286]) True Let's take another example − # import required library import torch # define the coefficient matrix A for a 3x3 # square system of linear equations A = torch.randn(3,3) # define right hand side tensor b b = torch.randn(3) # Solve the linear equation X = torch.linalg.solve(A, b) # print the solution of above linear equation print("Solution:\n", X) # check above solution to be true print(torch.allclose(A @ X, b)) It will produce the following output − Solution: tensor([-0.2867, -0.9850, 0.9938]) True
[ { "code": null, "e": 1212, "s": 1062, "text": "To solve a square system of linear equations with unique solution, we could apply the torch.linalg.solve() method. This method takes two parameters −" }, { "code": null, "e": 1249, "s": 1212, "text": "first, the coefficient matrix A, and" }, { "code": null, "e": 1286, "s": 1249, "text": "first, the coefficient matrix A, and" }, { "code": null, "e": 1319, "s": 1286, "text": "second, the right-hand tensor b." }, { "code": null, "e": 1352, "s": 1319, "text": "second, the right-hand tensor b." }, { "code": null, "e": 1567, "s": 1352, "text": "Where A is a square matrix and b is a vector. The solution is unique if A invertible. We can solve a number of systems of linear equations. In this case, A is a batch of square matrices and b is a batch of vectors." }, { "code": null, "e": 1592, "s": 1567, "text": "torch.linalg.solve(A, b)" }, { "code": null, "e": 1699, "s": 1592, "text": "A – Square matrix or batch of square matrices. It is the coefficient matrix of system of linear equations." }, { "code": null, "e": 1806, "s": 1699, "text": "A – Square matrix or batch of square matrices. It is the coefficient matrix of system of linear equations." }, { "code": null, "e": 1889, "s": 1806, "text": "b – Vector or a batch of vectors. It's the right-hand tensor of the linear system." }, { "code": null, "e": 1972, "s": 1889, "text": "b – Vector or a batch of vectors. It's the right-hand tensor of the linear system." }, { "code": null, "e": 2043, "s": 1972, "text": "It returns a tensor of the solution of the system of linear equations." }, { "code": null, "e": 2172, "s": 2043, "text": "Note − This method assumes that the coefficient matrix A is invertible. If it is not invertible, a Runtime Error will be raised." }, { "code": null, "e": 2251, "s": 2172, "text": "We could use the following steps to solve a square system of linear equations." }, { "code": null, "e": 2390, "s": 2251, "text": "Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it." }, { "code": null, "e": 2529, "s": 2390, "text": "Import the required library. In all the following examples, the required Python library is torch. Make sure you have already installed it." }, { "code": null, "e": 2542, "s": 2529, "text": "import torch" }, { "code": null, "e": 2650, "s": 2542, "text": "Define a Coefficient matrix and the right-hand side tensor for the given square system of linear equations." }, { "code": null, "e": 2758, "s": 2650, "text": "Define a Coefficient matrix and the right-hand side tensor for the given square system of linear equations." }, { "code": null, "e": 2824, "s": 2758, "text": "A = torch.tensor([[2., 3.],[1., -2.]])\nb = torch.tensor([3., 0.])" }, { "code": null, "e": 2924, "s": 2824, "text": "Compute the unique solution using torch.linalg.solve(A,b).\nCoefficient matrix A must be invertible." }, { "code": null, "e": 3024, "s": 2924, "text": "Compute the unique solution using torch.linalg.solve(A,b).\nCoefficient matrix A must be invertible." }, { "code": null, "e": 3053, "s": 3024, "text": "X = torch.linalg.solve(A, b)" }, { "code": null, "e": 3075, "s": 3053, "text": "Display the solution." }, { "code": null, "e": 3097, "s": 3075, "text": "Display the solution." }, { "code": null, "e": 3121, "s": 3097, "text": "print(\"Solution:\\n\", X)" }, { "code": null, "e": 3173, "s": 3121, "text": "Check if the calculated solution is correct or not." }, { "code": null, "e": 3225, "s": 3173, "text": "Check if the calculated solution is correct or not." }, { "code": null, "e": 3285, "s": 3225, "text": "print(torch.allclose(A @ X, b))\n# True for correct solution" }, { "code": null, "e": 3324, "s": 3285, "text": "Take a look at the following example −" }, { "code": null, "e": 3850, "s": 3324, "text": "# import required library\nimport torch\n\n'''\nLet's suppose our square system of linear equations is:\n2x + 3y = 3\nx - 2y = 0\n'''\n\nprint(\"Linear equation:\")\nprint(\"2x + 3y = 3\")\nprint(\"x - 2y = 0\")\n\n# define the coefficient matrix A\nA = torch.tensor([[2., 3.],[1., -2.]])\n# define right hand side tensor b\nb = torch.tensor([3., 0.])\n\n# Solve the linear equation\nX = torch.linalg.solve(A, b)\n\n# print the solution of above linear equation\nprint(\"Solution:\\n\", X)\n\n# check above solution to be true\nprint(torch.allclose(A @ X, b))" }, { "code": null, "e": 3889, "s": 3850, "text": "It will produce the following output −" }, { "code": null, "e": 3972, "s": 3889, "text": "Linear equation:\n2x + 3y = 3\nx - 2y = 0\nSolution:\n tensor([0.8571, 0.4286])\nTrue" }, { "code": null, "e": 4001, "s": 3972, "text": "Let's take another example −" }, { "code": null, "e": 4392, "s": 4001, "text": "# import required library\nimport torch\n\n# define the coefficient matrix A for a 3x3\n# square system of linear equations\nA = torch.randn(3,3)\n\n# define right hand side tensor b\nb = torch.randn(3)\n\n# Solve the linear equation\nX = torch.linalg.solve(A, b)\n\n# print the solution of above linear equation\nprint(\"Solution:\\n\", X)\n\n# check above solution to be true\nprint(torch.allclose(A @ X, b))" }, { "code": null, "e": 4431, "s": 4392, "text": "It will produce the following output −" }, { "code": null, "e": 4484, "s": 4431, "text": "Solution:\n tensor([-0.2867, -0.9850, 0.9938])\nTrue" } ]
13 ways to access data in Python. How to get data from local files... | by John Micah Reid | Towards Data Science
Most Python analysis starts by importing data into your environment. But what if that data is stuck in a database? Or behind an API? Or in a bunch of tiny files? Luckily, Python is incredibly flexible and has a lot of open-source libraries for accessing and processing data. In this tutorial we’ll look at 13 methods for getting data into a pandas Dataframe, after which it can be cleaned, analysed and visualized. We can group the methods into 4 main categories: Local filesDatabasesAPIsDataset access libraries Local files Databases APIs Dataset access libraries The only major requirement is installing the pandas library: $ pip install pandas With that, let’s get cracking! Often the data you need is stored in a local file on your computer. Depending on where you’re running your Python environment, you can either specify the filename as a relative or absolute path: # Absolute pathfile1 = "~/Users/johnreid/Documents/my_project/data/example.csv"# Relative path, assuming current working directory is my_projectfile2 = "./data/example.csv" CSVs are a popular choice for storing tabular data, and the simplest way to get started. Let’s assume you’ve downloaded this population dataset from Our World in Data: import pandas as pdcsv_file = "/Users/johnreid/Downloads/population-by-country.csv"df_from_csv = pd.read_csv(csv_file)df_from_csv.info() After importing the data, it’s helpful to run df.info() to understand how your data is structured e.g. how many rows, columns and non-null values you have. Running that code gives us the following output: This method also works for files accessible by URLs, like a public Google Sheet or CSV file in a public Github repo. Also, if you keep getting aFileNotFoundError then try renaming your filename to replace spaces with underscores e.g. "Financial Sample.xlsx" becomes "Financial_Sample.xlsx". You need to be a bit more cautious with Excel files, because they may contain more than one sheet of data and complex visual formatting e.g. extra header rows. Otherwise the syntax is pretty similar — here’s a financial data example: import pandas as pdexcel_file = "/Users/johnreid/Downloads/Financial_Sample.xlsx"df_from_excel = pd.read_excel(excel_file, sheet_name = "Sheet1")df_from_excel.info() Text files often need more data processing — start by looking at how the data is stored and how you’d like to represent it in Python. From there, you can write code to transform textual input into a dataframe. Let’s use a shopping list example, with each line containing an item and a quantity: To convert that to a dataframe, you can run the following: shopping_list = "/Users/johnreid/Downloads/shopping_list.txt"results = []with open(shopping_list) as f: line = f.readline() while line: results.append(line.strip().split(" ")) line = f.readline()f.close()df_from_textfile = pd.DataFrame(results, columns = ["Item", "Quantity"]) We read the lines one-by-one, strip extra whitespaces and split the line into two parts. When we create a dataframe, we also need to assign column names. What happens if you need to extract data from multiple stored files? Let’s combine a couple of things that we’ve learned to extract data from the BBC Sport text dataset. We have 5 subfolders, each with around 100 files. Each file starts with a headline, followed by the body of the article. Our goal will be to combine all these files into a single dataframe with ‘Title’, ‘Subtitle’, ‘Body’ and ‘Genre’ columns. The glob library comes really in handy here to list all possible filenames: import globimport pandas as pdbase_path = "/Users/johnreid/Downloads/bbcsport/"genres = ["athletics", "cricket", "football", "rugby", "tennis"]def read_and_split_file(filename): with open(filename, 'r', encoding="latin-1") as f: lines = f.readlines() # Get lines as a list of strings lines = list(map(str.strip, lines)) # Remove /n characters lines = list(filter(None, lines)) # Remove empty strings return linesdef get_df_from_genre(path, genre): files = glob.glob(path + genre + "/*.txt") titles = [] subtitles = [] bodies = [] for f in files: lines = read_and_split_file(f) titles.append(lines[0]) # First line is the title subtitles.append(lines[1]) # Second line is the subtitle bodies.append(' '.join(lines[2:])) # Combine all the rest return(pd.DataFrame({ 'genre': genre, 'title': titles, 'subtitle': subtitles, 'body': bodies }) )final_df = pd.concat([get_df_from_genre(base_path, g) for g in genres])final_df We use the * operator with glob to get all possible filenames ending in .txt. Note that you can concatenate multiple dataframes together using pd.concat. Running that code gives us the following output: Most organizations store their business-critical data in a relational database like Postgres or MySQL, and you’ll need to know Structured Query Language (SQL) to access or update the data stored there. Databases have a number of advantages, like data normaliza SQLite is an embedded database that is stored as a single file, so it’s a great place to start testing out queries. Here we’ll show an example of connecting to a SQLite file of the Chinook database: import pandas as pdimport sqlite3 as sqlconn = sql.connect('/Users/johnreid/Downloads/chinook.db')# First pattern - turn query directly into dataframe:df1 = pd.read_sql_query("SELECT * FROM invoice", conn)# Second pattern - get row-level data, but no column namescur = conn.cursor()results = cur.execute("SELECT * FROM invoice LIMIT 5").fetchall()df2 = pd.DataFrame(results) If you’re curious, read my full tutorial on building an interactive dashboard using SQL here: towardsdatascience.com Connecting to a remote database like Postgres, Redshift, or SQLServer uses mostly the same syntax but requires access credentials. For security reasons, it’s best to store these credentials in a config file and load them into your Python script. You can create a separate .py file with the following info: host = "localhost"database= "suppliers"user = "postgres"password = "SecurePas$1" and then import it into your Python script as follows (you’ll also need the psychopg2 library): import psycopg2import configconn = psycopg2.connect( host=config.host, database=config.database, user=config.user, password=config.password)df1 = pd.read_sql_query("SELECT * FROM invoice", conn) Make sure to keep your config.py file safe and don't upload it elsewhere - you can add it to your .gitignore to make sure it doesn't get included in git commits. If you want a more ‘pythonic’ way of querying a database, try the SQLAlchemy library, which is an Object-Relational-Mapper. It’s typically used for applications so that developers don’t have to write pure SQL to update their database, but you can use it for querying data too! Here’s an example using the same Chinook music store database: import sqlalchemy as dbengine = db.create_engine('sqlite:///chinook.db')connection = engine.connect()metadata = db.MetaData()invoice = db.Table('invoice', metadata, autoload=True, autoload_with=engine)# Get the first 10 invoices from the USAquery = (db.select([invoice]) .filter_by(billing_country = 'USA') .limit(10) )df = pd.read_sql(query, engine) In this code we connect to the database, then set up some tables & metadata in SQLAlchemy. Once that’s defined, we can write a query in a more ‘pythonic’ way and read the results directly to a Pandas dataframe. Running that code gives the following output: Sometimes you’ll need to access data from a particular platform your company uses, like Hubspot, Twitter or Trello. These platforms often have a public API that you can pull data from, directly inside your Python environment. The basic idea is you send a request (which may include query parameters and access credentials) to an endpoint. That endpoint will return a response code plus the data you asked for (hopefully). You’ll need to look at the API documentation to understand what data fields are available. The data will usually be returned in JSON format, which allows for deeply-nested data. Let’s do a minimal example using the OpenNotify API, which tracks all the people currently in space: import requestsresponse = requests.get("http://api.open-notify.org/astros.json")print(response.status_code)print(response.json())res = pd.DataFrame(response.json()["people"])res.head() Running that code gives us the following output: The response code tells you the result of your API call — according to Dataquest the most common are: 200: Everything went okay, and the result has been returned (if any). 301: The server is redirecting you to a different endpoint. This can happen when a company switches domain names, or an endpoint name is changed. 400: The server thinks you made a bad request. This can happen when you don’t send along the right data, among other things. 403: The resource you’re trying to access is forbidden: you don’t have the right permissions to see it. 404: The resource you tried to access wasn’t found on the server. 503: The server is not ready to handle the request. Sometimes you may need more specific information from the API, or have to authenticate. There are several ways to do this, however one of the most common is adding URL parameters to your request. Let’s assume we have a config.pyfile with our API key in it: personal_api_key = "wouldntyouliketoknow" Then we create a dictionary for all the parameters (this is a made-up example) and pass it in: import configimport pandas as pdimport requestsparameters = { "personal_api_key": config.personal_api_key, "date": "2021-09-22"}response = requests.get(url, params = parameters) print(response.status_code)print(response.json()) res = pd.DataFrame(response.json()["people"])res.head() If you don’t want to deal with JSON you can try searching for a Python library for that API — these are usually open-source and maintained by the company or third parties. What if you need some reference data for a comparison or adding context? There are a bunch of libraries for downloading public datasets straight into your environment — think of it as pulling from APIs without having to manage all the extra complexity. Pandas_datareader is a great way to pull data from the internet into your Python environment. It is particularly suited to financial data, but also has some World Bank datasources. To get Zoom’s daily share price over the past few years, try the following: from pandas_datareader import dataimport datetime as dtzm = data.DataReader( "ZM", start='2019-1-1', end=dt.datetime.today(), data_source='yahoo').reset_index()zm.head() Running that code gives us the following output: Datacommons is a project by Google providing access to standardized and cleaned public datasets. The underlying data is represented in a graph format, making it really easy to query and join data from many different datasources e.g. the US Census, World Bank, Wikipedia, Centre for Disease Control and more. Here’s a basic example: !pip install datacommons datacommons_pandas --upgrade --quietimport datacommons_pandas as dcimport pandas as pdcity_dcids = dc.get_property_values(["CDC500_City"], "member", limit=500)["CDC500_City"]cdc500_df = dc.build_multivariate_dataframe( city_dcids, ["Percent_Person_Obesity", # Prevalence of obesity from CDC "Median_Income_Person", "Median_Age_Person", "UnemploymentRate_Person", # Unemployment rate from BLS "Count_Person_BelowPovertyLevelInThePast12Months", # Persons living below the poverty line from Census "Count_Person", # Total population from Census ],)cdc500_df.info() Running that code gives us the following: If you want to learn how to use DataCommons, read my full tutorial here: towardsdatascience.com PyTrends is an unofficial but useful library for querying Google Trends data — here’s a simple example: import pandas as pdfrom pytrends.request import TrendReqpytrends = TrendReq()keywords = ["oat milk", "soy milk", "almond milk"]pytrends.build_payload(keywords, cat=0, geo='', gprop='') # Get data from the last 5 yearstop_queries = pytrends.interest_over_time()[keywords]top_queries.head() Running that code gives us the following output: Kaggle is a data science community that hosts a lot of datasets and competitions for learning Python. You can download some of these datasets to play around with through their command-line interface (note: you’ll need to sign up for a Kaggle account). For example, say we want to download some Zillow economics data, we can run the following commands in our terminal (Jupyter users: replace the $ with ! in your Python code: $ pip install kaggle$ export KAGGLE_USERNAME=datadinosaur$ export KAGGLE_KEY=xxxxxxxxxxxxxx$ kaggle datasets download zillow/zecon$ unzip zecon.zip This will download a zipped file of the datasets, and then uncompress them. From there, you can open them as local files with Pandas: import pandas as pdcsv_file = "/Users/johnreid/Downloads/Zip_time_series.csv"df_from_csv = pd.read_csv(csv_file)df_from_csv.info() To learn more, check out the Kaggle API documentation. You made it! Now you can use your newfound powers to access multiple datasources and join them together withpd.merge or pd.concat, then visualize them with an interactive library like Altair, Pandas or Folium. Are there any methods I missed? Let me know in the comments.
[ { "code": null, "e": 334, "s": 172, "text": "Most Python analysis starts by importing data into your environment. But what if that data is stuck in a database? Or behind an API? Or in a bunch of tiny files?" }, { "code": null, "e": 636, "s": 334, "text": "Luckily, Python is incredibly flexible and has a lot of open-source libraries for accessing and processing data. In this tutorial we’ll look at 13 methods for getting data into a pandas Dataframe, after which it can be cleaned, analysed and visualized. We can group the methods into 4 main categories:" }, { "code": null, "e": 685, "s": 636, "text": "Local filesDatabasesAPIsDataset access libraries" }, { "code": null, "e": 697, "s": 685, "text": "Local files" }, { "code": null, "e": 707, "s": 697, "text": "Databases" }, { "code": null, "e": 712, "s": 707, "text": "APIs" }, { "code": null, "e": 737, "s": 712, "text": "Dataset access libraries" }, { "code": null, "e": 798, "s": 737, "text": "The only major requirement is installing the pandas library:" }, { "code": null, "e": 819, "s": 798, "text": "$ pip install pandas" }, { "code": null, "e": 850, "s": 819, "text": "With that, let’s get cracking!" }, { "code": null, "e": 1045, "s": 850, "text": "Often the data you need is stored in a local file on your computer. Depending on where you’re running your Python environment, you can either specify the filename as a relative or absolute path:" }, { "code": null, "e": 1218, "s": 1045, "text": "# Absolute pathfile1 = \"~/Users/johnreid/Documents/my_project/data/example.csv\"# Relative path, assuming current working directory is my_projectfile2 = \"./data/example.csv\"" }, { "code": null, "e": 1386, "s": 1218, "text": "CSVs are a popular choice for storing tabular data, and the simplest way to get started. Let’s assume you’ve downloaded this population dataset from Our World in Data:" }, { "code": null, "e": 1523, "s": 1386, "text": "import pandas as pdcsv_file = \"/Users/johnreid/Downloads/population-by-country.csv\"df_from_csv = pd.read_csv(csv_file)df_from_csv.info()" }, { "code": null, "e": 1728, "s": 1523, "text": "After importing the data, it’s helpful to run df.info() to understand how your data is structured e.g. how many rows, columns and non-null values you have. Running that code gives us the following output:" }, { "code": null, "e": 2019, "s": 1728, "text": "This method also works for files accessible by URLs, like a public Google Sheet or CSV file in a public Github repo. Also, if you keep getting aFileNotFoundError then try renaming your filename to replace spaces with underscores e.g. \"Financial Sample.xlsx\" becomes \"Financial_Sample.xlsx\"." }, { "code": null, "e": 2253, "s": 2019, "text": "You need to be a bit more cautious with Excel files, because they may contain more than one sheet of data and complex visual formatting e.g. extra header rows. Otherwise the syntax is pretty similar — here’s a financial data example:" }, { "code": null, "e": 2419, "s": 2253, "text": "import pandas as pdexcel_file = \"/Users/johnreid/Downloads/Financial_Sample.xlsx\"df_from_excel = pd.read_excel(excel_file, sheet_name = \"Sheet1\")df_from_excel.info()" }, { "code": null, "e": 2714, "s": 2419, "text": "Text files often need more data processing — start by looking at how the data is stored and how you’d like to represent it in Python. From there, you can write code to transform textual input into a dataframe. Let’s use a shopping list example, with each line containing an item and a quantity:" }, { "code": null, "e": 2773, "s": 2714, "text": "To convert that to a dataframe, you can run the following:" }, { "code": null, "e": 3070, "s": 2773, "text": "shopping_list = \"/Users/johnreid/Downloads/shopping_list.txt\"results = []with open(shopping_list) as f: line = f.readline() while line: results.append(line.strip().split(\" \")) line = f.readline()f.close()df_from_textfile = pd.DataFrame(results, columns = [\"Item\", \"Quantity\"])" }, { "code": null, "e": 3224, "s": 3070, "text": "We read the lines one-by-one, strip extra whitespaces and split the line into two parts. When we create a dataframe, we also need to assign column names." }, { "code": null, "e": 3394, "s": 3224, "text": "What happens if you need to extract data from multiple stored files? Let’s combine a couple of things that we’ve learned to extract data from the BBC Sport text dataset." }, { "code": null, "e": 3713, "s": 3394, "text": "We have 5 subfolders, each with around 100 files. Each file starts with a headline, followed by the body of the article. Our goal will be to combine all these files into a single dataframe with ‘Title’, ‘Subtitle’, ‘Body’ and ‘Genre’ columns. The glob library comes really in handy here to list all possible filenames:" }, { "code": null, "e": 4743, "s": 3713, "text": "import globimport pandas as pdbase_path = \"/Users/johnreid/Downloads/bbcsport/\"genres = [\"athletics\", \"cricket\", \"football\", \"rugby\", \"tennis\"]def read_and_split_file(filename): with open(filename, 'r', encoding=\"latin-1\") as f: lines = f.readlines() # Get lines as a list of strings lines = list(map(str.strip, lines)) # Remove /n characters lines = list(filter(None, lines)) # Remove empty strings return linesdef get_df_from_genre(path, genre): files = glob.glob(path + genre + \"/*.txt\") titles = [] subtitles = [] bodies = [] for f in files: lines = read_and_split_file(f) titles.append(lines[0]) # First line is the title subtitles.append(lines[1]) # Second line is the subtitle bodies.append(' '.join(lines[2:])) # Combine all the rest return(pd.DataFrame({ 'genre': genre, 'title': titles, 'subtitle': subtitles, 'body': bodies }) )final_df = pd.concat([get_df_from_genre(base_path, g) for g in genres])final_df" }, { "code": null, "e": 4946, "s": 4743, "text": "We use the * operator with glob to get all possible filenames ending in .txt. Note that you can concatenate multiple dataframes together using pd.concat. Running that code gives us the following output:" }, { "code": null, "e": 5207, "s": 4946, "text": "Most organizations store their business-critical data in a relational database like Postgres or MySQL, and you’ll need to know Structured Query Language (SQL) to access or update the data stored there. Databases have a number of advantages, like data normaliza" }, { "code": null, "e": 5406, "s": 5207, "text": "SQLite is an embedded database that is stored as a single file, so it’s a great place to start testing out queries. Here we’ll show an example of connecting to a SQLite file of the Chinook database:" }, { "code": null, "e": 5781, "s": 5406, "text": "import pandas as pdimport sqlite3 as sqlconn = sql.connect('/Users/johnreid/Downloads/chinook.db')# First pattern - turn query directly into dataframe:df1 = pd.read_sql_query(\"SELECT * FROM invoice\", conn)# Second pattern - get row-level data, but no column namescur = conn.cursor()results = cur.execute(\"SELECT * FROM invoice LIMIT 5\").fetchall()df2 = pd.DataFrame(results)" }, { "code": null, "e": 5875, "s": 5781, "text": "If you’re curious, read my full tutorial on building an interactive dashboard using SQL here:" }, { "code": null, "e": 5898, "s": 5875, "text": "towardsdatascience.com" }, { "code": null, "e": 6204, "s": 5898, "text": "Connecting to a remote database like Postgres, Redshift, or SQLServer uses mostly the same syntax but requires access credentials. For security reasons, it’s best to store these credentials in a config file and load them into your Python script. You can create a separate .py file with the following info:" }, { "code": null, "e": 6285, "s": 6204, "text": "host = \"localhost\"database= \"suppliers\"user = \"postgres\"password = \"SecurePas$1\"" }, { "code": null, "e": 6381, "s": 6285, "text": "and then import it into your Python script as follows (you’ll also need the psychopg2 library):" }, { "code": null, "e": 6588, "s": 6381, "text": "import psycopg2import configconn = psycopg2.connect( host=config.host, database=config.database, user=config.user, password=config.password)df1 = pd.read_sql_query(\"SELECT * FROM invoice\", conn)" }, { "code": null, "e": 6750, "s": 6588, "text": "Make sure to keep your config.py file safe and don't upload it elsewhere - you can add it to your .gitignore to make sure it doesn't get included in git commits." }, { "code": null, "e": 7027, "s": 6750, "text": "If you want a more ‘pythonic’ way of querying a database, try the SQLAlchemy library, which is an Object-Relational-Mapper. It’s typically used for applications so that developers don’t have to write pure SQL to update their database, but you can use it for querying data too!" }, { "code": null, "e": 7090, "s": 7027, "text": "Here’s an example using the same Chinook music store database:" }, { "code": null, "e": 7454, "s": 7090, "text": "import sqlalchemy as dbengine = db.create_engine('sqlite:///chinook.db')connection = engine.connect()metadata = db.MetaData()invoice = db.Table('invoice', metadata, autoload=True, autoload_with=engine)# Get the first 10 invoices from the USAquery = (db.select([invoice]) .filter_by(billing_country = 'USA') .limit(10) )df = pd.read_sql(query, engine)" }, { "code": null, "e": 7711, "s": 7454, "text": "In this code we connect to the database, then set up some tables & metadata in SQLAlchemy. Once that’s defined, we can write a query in a more ‘pythonic’ way and read the results directly to a Pandas dataframe. Running that code gives the following output:" }, { "code": null, "e": 7937, "s": 7711, "text": "Sometimes you’ll need to access data from a particular platform your company uses, like Hubspot, Twitter or Trello. These platforms often have a public API that you can pull data from, directly inside your Python environment." }, { "code": null, "e": 8311, "s": 7937, "text": "The basic idea is you send a request (which may include query parameters and access credentials) to an endpoint. That endpoint will return a response code plus the data you asked for (hopefully). You’ll need to look at the API documentation to understand what data fields are available. The data will usually be returned in JSON format, which allows for deeply-nested data." }, { "code": null, "e": 8412, "s": 8311, "text": "Let’s do a minimal example using the OpenNotify API, which tracks all the people currently in space:" }, { "code": null, "e": 8597, "s": 8412, "text": "import requestsresponse = requests.get(\"http://api.open-notify.org/astros.json\")print(response.status_code)print(response.json())res = pd.DataFrame(response.json()[\"people\"])res.head()" }, { "code": null, "e": 8646, "s": 8597, "text": "Running that code gives us the following output:" }, { "code": null, "e": 8748, "s": 8646, "text": "The response code tells you the result of your API call — according to Dataquest the most common are:" }, { "code": null, "e": 8818, "s": 8748, "text": "200: Everything went okay, and the result has been returned (if any)." }, { "code": null, "e": 8964, "s": 8818, "text": "301: The server is redirecting you to a different endpoint. This can happen when a company switches domain names, or an endpoint name is changed." }, { "code": null, "e": 9089, "s": 8964, "text": "400: The server thinks you made a bad request. This can happen when you don’t send along the right data, among other things." }, { "code": null, "e": 9193, "s": 9089, "text": "403: The resource you’re trying to access is forbidden: you don’t have the right permissions to see it." }, { "code": null, "e": 9259, "s": 9193, "text": "404: The resource you tried to access wasn’t found on the server." }, { "code": null, "e": 9311, "s": 9259, "text": "503: The server is not ready to handle the request." }, { "code": null, "e": 9507, "s": 9311, "text": "Sometimes you may need more specific information from the API, or have to authenticate. There are several ways to do this, however one of the most common is adding URL parameters to your request." }, { "code": null, "e": 9568, "s": 9507, "text": "Let’s assume we have a config.pyfile with our API key in it:" }, { "code": null, "e": 9610, "s": 9568, "text": "personal_api_key = \"wouldntyouliketoknow\"" }, { "code": null, "e": 9705, "s": 9610, "text": "Then we create a dictionary for all the parameters (this is a made-up example) and pass it in:" }, { "code": null, "e": 10002, "s": 9705, "text": "import configimport pandas as pdimport requestsparameters = { \"personal_api_key\": config.personal_api_key, \"date\": \"2021-09-22\"}response = requests.get(url, params = parameters) print(response.status_code)print(response.json()) res = pd.DataFrame(response.json()[\"people\"])res.head()" }, { "code": null, "e": 10174, "s": 10002, "text": "If you don’t want to deal with JSON you can try searching for a Python library for that API — these are usually open-source and maintained by the company or third parties." }, { "code": null, "e": 10427, "s": 10174, "text": "What if you need some reference data for a comparison or adding context? There are a bunch of libraries for downloading public datasets straight into your environment — think of it as pulling from APIs without having to manage all the extra complexity." }, { "code": null, "e": 10684, "s": 10427, "text": "Pandas_datareader is a great way to pull data from the internet into your Python environment. It is particularly suited to financial data, but also has some World Bank datasources. To get Zoom’s daily share price over the past few years, try the following:" }, { "code": null, "e": 10866, "s": 10684, "text": "from pandas_datareader import dataimport datetime as dtzm = data.DataReader( \"ZM\", start='2019-1-1', end=dt.datetime.today(), data_source='yahoo').reset_index()zm.head()" }, { "code": null, "e": 10915, "s": 10866, "text": "Running that code gives us the following output:" }, { "code": null, "e": 11247, "s": 10915, "text": "Datacommons is a project by Google providing access to standardized and cleaned public datasets. The underlying data is represented in a graph format, making it really easy to query and join data from many different datasources e.g. the US Census, World Bank, Wikipedia, Centre for Disease Control and more. Here’s a basic example:" }, { "code": null, "e": 11862, "s": 11247, "text": "!pip install datacommons datacommons_pandas --upgrade --quietimport datacommons_pandas as dcimport pandas as pdcity_dcids = dc.get_property_values([\"CDC500_City\"], \"member\", limit=500)[\"CDC500_City\"]cdc500_df = dc.build_multivariate_dataframe( city_dcids, [\"Percent_Person_Obesity\", # Prevalence of obesity from CDC \"Median_Income_Person\", \"Median_Age_Person\", \"UnemploymentRate_Person\", # Unemployment rate from BLS \"Count_Person_BelowPovertyLevelInThePast12Months\", # Persons living below the poverty line from Census \"Count_Person\", # Total population from Census ],)cdc500_df.info()" }, { "code": null, "e": 11904, "s": 11862, "text": "Running that code gives us the following:" }, { "code": null, "e": 11977, "s": 11904, "text": "If you want to learn how to use DataCommons, read my full tutorial here:" }, { "code": null, "e": 12000, "s": 11977, "text": "towardsdatascience.com" }, { "code": null, "e": 12104, "s": 12000, "text": "PyTrends is an unofficial but useful library for querying Google Trends data — here’s a simple example:" }, { "code": null, "e": 12393, "s": 12104, "text": "import pandas as pdfrom pytrends.request import TrendReqpytrends = TrendReq()keywords = [\"oat milk\", \"soy milk\", \"almond milk\"]pytrends.build_payload(keywords, cat=0, geo='', gprop='') # Get data from the last 5 yearstop_queries = pytrends.interest_over_time()[keywords]top_queries.head()" }, { "code": null, "e": 12442, "s": 12393, "text": "Running that code gives us the following output:" }, { "code": null, "e": 12867, "s": 12442, "text": "Kaggle is a data science community that hosts a lot of datasets and competitions for learning Python. You can download some of these datasets to play around with through their command-line interface (note: you’ll need to sign up for a Kaggle account). For example, say we want to download some Zillow economics data, we can run the following commands in our terminal (Jupyter users: replace the $ with ! in your Python code:" }, { "code": null, "e": 13015, "s": 12867, "text": "$ pip install kaggle$ export KAGGLE_USERNAME=datadinosaur$ export KAGGLE_KEY=xxxxxxxxxxxxxx$ kaggle datasets download zillow/zecon$ unzip zecon.zip" }, { "code": null, "e": 13149, "s": 13015, "text": "This will download a zipped file of the datasets, and then uncompress them. From there, you can open them as local files with Pandas:" }, { "code": null, "e": 13280, "s": 13149, "text": "import pandas as pdcsv_file = \"/Users/johnreid/Downloads/Zip_time_series.csv\"df_from_csv = pd.read_csv(csv_file)df_from_csv.info()" }, { "code": null, "e": 13335, "s": 13280, "text": "To learn more, check out the Kaggle API documentation." }, { "code": null, "e": 13545, "s": 13335, "text": "You made it! Now you can use your newfound powers to access multiple datasources and join them together withpd.merge or pd.concat, then visualize them with an interactive library like Altair, Pandas or Folium." } ]
Ways to write n as sum of two or more positive integers
24 Jan, 2022 For a given number n > 0, find the number of different ways in which n can be written as a sum of at two or more positive integers.Examples: Input : n = 5 Output : 6 Explanation : All possible six ways are : 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 Input : 4 Output : 4 Explanation : All possible four ways are : 3 + 1 2 + 2 2 + 1 + 1 1 + 1 + 1 + 1 This problem can be solved in the similar fashion as coin change problem, the difference is only that in this case we should iterate for 1 to n-1 instead of particular values of coin as in coin-change problem. C++ Java Python3 C# PHP Javascript // Program to find the number of ways, n can be// written as sum of two or more positive integers.#include <bits/stdc++.h>using namespace std; // Returns number of ways to write n as sum of// two or more positive integersint countWays(int n){ // table[i] will be storing the number of // solutions for value i. We need n+1 rows // as the table is constructed in bottom up // manner using the base case (n = 0) int table[n+1]; // Initialize all table values as 0 memset(table, 0, sizeof(table)); // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and update the // table[] values after the index greater // than or equal to n for (int i=1; i<n; i++) for (int j=i; j<=n; j++) table[j] += table[j-i]; return table[n];} // Driver programint main(){ int n = 7; cout << countWays(n); return 0;} // Program to find the number of ways,// n can be written as sum of two or// more positive integers.import java.util.Arrays; class GFG { // Returns number of ways to write // n as sum of two or more positive // integers static int countWays(int n) { // table[i] will be storing the // number of solutions for value // i. We need n+1 rows as the // table is constructed in bottom // up manner using the base case // (n = 0) int table[] = new int[n + 1]; // Initialize all table values as 0 Arrays.fill(table, 0); // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and // update the table[] values after // the index greater than or equal // to n for (int i = 1; i < n; i++) for (int j = i; j <= n; j++) table[j] += table[j - i]; return table[n]; } //driver code public static void main (String[] args) { int n = 7; System.out.print(countWays(n)); }} // This code is contributed by Anant Agarwal. # Program to find the number of ways, n can be# written as sum of two or more positive integers. # Returns number of ways to write n as sum of# two or more positive integersdef CountWays(n): # table[i] will be storing the number of # solutions for value i. We need n+1 rows # as the table is constructed in bottom up # manner using the base case (n = 0) # Initialize all table values as 0 table =[0] * (n + 1) # Base case (If given value is 0) # Only 1 way to get 0 (select no integer) table[0] = 1 # Pick all integer one by one and update the # table[] values after the index greater # than or equal to n for i in range(1, n ): for j in range(i , n + 1): table[j] += table[j - i] return table[n] # driver programdef main(): n = 7 print (CountWays(n)) if __name__ == '__main__': main() #This code is contributed by Neelam Yadav // Program to find the number of ways, n can be// written as sum of two or more positive integers.using System; class GFG { // Returns number of ways to write n as sum of // two or more positive integers static int countWays(int n) { // table[i] will be storing the number of // solutions for value i. We need n+1 rows // as the table is constructed in bottom up // manner using the base case (n = 0) int []table = new int[n+1]; // Initialize all table values as 0 for(int i = 0; i < table.Length; i++) table[i] = 0; // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and update the // table[] values after the index greater // than or equal to n for (int i = 1; i < n; i++) for (int j = i; j <= n; j++) table[j] += table[j-i]; return table[n]; } //driver code public static void Main() { int n = 7; Console.Write(countWays(n)); }} // This code is contributed by Anant Agarwal. <?php// Program to find the number of ways, n can be// written as sum of two or more positive integers. // Returns number of ways to write n as sum// of two or more positive integersfunction countWays($n){ // table[i] will be storing the number of // solutions for value i. We need n+1 rows // as the table is constructed in bottom up // manner using the base case (n = 0) $table = array_fill(0, $n + 1, NULL); // Base case (If given value is 0) $table[0] = 1; // Pick all integer one by one and update // the table[] values after the index // greater than or equal to n for ($i = 1; $i < $n; $i++) for ($j = $i; $j <= $n; $j++) $table[$j] += $table[$j - $i]; return $table[$n];} // Driver Code$n = 7;echo countWays($n); // This code is contributed by ita_c?> <script> function countWays(n) { // table[i] will be storing the // number of solutions for value // i. We need n+1 rows as the // table is constructed in bottom // up manner using the base case // (n = 0) let table = new Array(n + 1); // Initialize all table values as 0 for(let i = 0; i < n + 1; i++) { table[i]=0; } // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and // update the table[] values after // the index greater than or equal // to n for (let i = 1; i < n; i++) for (let j = i; j <= n; j++) table[j] += table[j - i]; return table[n]; } let n = 7; document.write(countWays(n)); // This code is contributed by avanitrachhadiya2155</script> Output: 14 Time complexity O(n2)This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. ukasp avanitrachhadiya2155 kk9826225 amartyaghoshgfg Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Find if there is a path between two vertices in an undirected graph Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Sieve of Eratosthenes Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Minimum number of jumps to reach end Tabulation vs Memoization Longest Common Substring | DP-29
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jan, 2022" }, { "code": null, "e": 197, "s": 54, "text": "For a given number n > 0, find the number of different ways in which n can be written as a sum of at two or more positive integers.Examples: " }, { "code": null, "e": 429, "s": 197, "text": "Input : n = 5\nOutput : 6\nExplanation : All possible six ways are :\n4 + 1\n3 + 2\n3 + 1 + 1\n2 + 2 + 1\n2 + 1 + 1 + 1\n1 + 1 + 1 + 1 + 1\n\nInput : 4\nOutput : 4\nExplanation : All possible four ways are :\n3 + 1\n2 + 2\n2 + 1 + 1\n1 + 1 + 1 + 1" }, { "code": null, "e": 641, "s": 431, "text": "This problem can be solved in the similar fashion as coin change problem, the difference is only that in this case we should iterate for 1 to n-1 instead of particular values of coin as in coin-change problem." }, { "code": null, "e": 647, "s": 643, "text": "C++" }, { "code": null, "e": 652, "s": 647, "text": "Java" }, { "code": null, "e": 660, "s": 652, "text": "Python3" }, { "code": null, "e": 663, "s": 660, "text": "C#" }, { "code": null, "e": 667, "s": 663, "text": "PHP" }, { "code": null, "e": 678, "s": 667, "text": "Javascript" }, { "code": "// Program to find the number of ways, n can be// written as sum of two or more positive integers.#include <bits/stdc++.h>using namespace std; // Returns number of ways to write n as sum of// two or more positive integersint countWays(int n){ // table[i] will be storing the number of // solutions for value i. We need n+1 rows // as the table is constructed in bottom up // manner using the base case (n = 0) int table[n+1]; // Initialize all table values as 0 memset(table, 0, sizeof(table)); // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and update the // table[] values after the index greater // than or equal to n for (int i=1; i<n; i++) for (int j=i; j<=n; j++) table[j] += table[j-i]; return table[n];} // Driver programint main(){ int n = 7; cout << countWays(n); return 0;}", "e": 1569, "s": 678, "text": null }, { "code": "// Program to find the number of ways,// n can be written as sum of two or// more positive integers.import java.util.Arrays; class GFG { // Returns number of ways to write // n as sum of two or more positive // integers static int countWays(int n) { // table[i] will be storing the // number of solutions for value // i. We need n+1 rows as the // table is constructed in bottom // up manner using the base case // (n = 0) int table[] = new int[n + 1]; // Initialize all table values as 0 Arrays.fill(table, 0); // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and // update the table[] values after // the index greater than or equal // to n for (int i = 1; i < n; i++) for (int j = i; j <= n; j++) table[j] += table[j - i]; return table[n]; } //driver code public static void main (String[] args) { int n = 7; System.out.print(countWays(n)); }} // This code is contributed by Anant Agarwal.", "e": 2730, "s": 1569, "text": null }, { "code": "# Program to find the number of ways, n can be# written as sum of two or more positive integers. # Returns number of ways to write n as sum of# two or more positive integersdef CountWays(n): # table[i] will be storing the number of # solutions for value i. We need n+1 rows # as the table is constructed in bottom up # manner using the base case (n = 0) # Initialize all table values as 0 table =[0] * (n + 1) # Base case (If given value is 0) # Only 1 way to get 0 (select no integer) table[0] = 1 # Pick all integer one by one and update the # table[] values after the index greater # than or equal to n for i in range(1, n ): for j in range(i , n + 1): table[j] += table[j - i] return table[n] # driver programdef main(): n = 7 print (CountWays(n)) if __name__ == '__main__': main() #This code is contributed by Neelam Yadav", "e": 3647, "s": 2730, "text": null }, { "code": "// Program to find the number of ways, n can be// written as sum of two or more positive integers.using System; class GFG { // Returns number of ways to write n as sum of // two or more positive integers static int countWays(int n) { // table[i] will be storing the number of // solutions for value i. We need n+1 rows // as the table is constructed in bottom up // manner using the base case (n = 0) int []table = new int[n+1]; // Initialize all table values as 0 for(int i = 0; i < table.Length; i++) table[i] = 0; // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and update the // table[] values after the index greater // than or equal to n for (int i = 1; i < n; i++) for (int j = i; j <= n; j++) table[j] += table[j-i]; return table[n]; } //driver code public static void Main() { int n = 7; Console.Write(countWays(n)); }} // This code is contributed by Anant Agarwal.", "e": 4782, "s": 3647, "text": null }, { "code": "<?php// Program to find the number of ways, n can be// written as sum of two or more positive integers. // Returns number of ways to write n as sum// of two or more positive integersfunction countWays($n){ // table[i] will be storing the number of // solutions for value i. We need n+1 rows // as the table is constructed in bottom up // manner using the base case (n = 0) $table = array_fill(0, $n + 1, NULL); // Base case (If given value is 0) $table[0] = 1; // Pick all integer one by one and update // the table[] values after the index // greater than or equal to n for ($i = 1; $i < $n; $i++) for ($j = $i; $j <= $n; $j++) $table[$j] += $table[$j - $i]; return $table[$n];} // Driver Code$n = 7;echo countWays($n); // This code is contributed by ita_c?>", "e": 5599, "s": 4782, "text": null }, { "code": "<script> function countWays(n) { // table[i] will be storing the // number of solutions for value // i. We need n+1 rows as the // table is constructed in bottom // up manner using the base case // (n = 0) let table = new Array(n + 1); // Initialize all table values as 0 for(let i = 0; i < n + 1; i++) { table[i]=0; } // Base case (If given value is 0) table[0] = 1; // Pick all integer one by one and // update the table[] values after // the index greater than or equal // to n for (let i = 1; i < n; i++) for (let j = i; j <= n; j++) table[j] += table[j - i]; return table[n]; } let n = 7; document.write(countWays(n)); // This code is contributed by avanitrachhadiya2155</script>", "e": 6515, "s": 5599, "text": null }, { "code": null, "e": 6525, "s": 6515, "text": "Output: " }, { "code": null, "e": 6528, "s": 6525, "text": "14" }, { "code": null, "e": 6990, "s": 6528, "text": "Time complexity O(n2)This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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": 6996, "s": 6990, "text": "ukasp" }, { "code": null, "e": 7017, "s": 6996, "text": "avanitrachhadiya2155" }, { "code": null, "e": 7027, "s": 7017, "text": "kk9826225" }, { "code": null, "e": 7043, "s": 7027, "text": "amartyaghoshgfg" }, { "code": null, "e": 7063, "s": 7043, "text": "Dynamic Programming" }, { "code": null, "e": 7083, "s": 7063, "text": "Dynamic Programming" }, { "code": null, "e": 7181, "s": 7083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7219, "s": 7181, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 7252, "s": 7219, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 7320, "s": 7252, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 7355, "s": 7320, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 7386, "s": 7355, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 7408, "s": 7386, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 7476, "s": 7408, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 7513, "s": 7476, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7539, "s": 7513, "text": "Tabulation vs Memoization" } ]
java.lang.reflect.Method Class in Java
10 Mar, 2021 java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method). This class allows broadening of conversions to occur when matching the actual parameters to call the underlying method’s formal parameters, but if narrowing conversion would occur, it throws an IllegalArgumentException. java.lang.Object java.lang.reflect.AccessibleObject java.lang.reflect.Executable java.lang.reflect.Method Methods: getDefaultValue() Method: Java // Java program to show the// Implementation of getDefaultvalue() import java.lang.reflect.Method; public class getDefaultValueExample { public static void main(String[] args) { Method[] methods = Demo.class.getMethods(); // calling method getDefaultValue() System.out.println(methods[0].getDefaultValue()); }} class Demo { private String str; // member function returning string str public String getSampleField() { return str; } public void setSampleField(String str) { this.str = str; }} null toString() Method: Java // Java program to show the// Implementation of toString() import java.lang.reflect.Method; public class MethodDemo { public static void main(String[] args) { Method[] methods = SampleClass.class.getMethods(); // calling method toString() System.out.println(methods[1].toString()); }} class SampleClass { private String str; public String getSampleField() { return str; } public void setSampleField(String str) { this.str = str; }} public void SampleClass.setSampleField(java.lang.String) java-lang-reflect-package Picked Technical Scripter 2020 Java 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 Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Mar, 2021" }, { "code": null, "e": 279, "s": 28, "text": "java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method)." }, { "code": null, "e": 499, "s": 279, "text": "This class allows broadening of conversions to occur when matching the actual parameters to call the underlying method’s formal parameters, but if narrowing conversion would occur, it throws an IllegalArgumentException." }, { "code": null, "e": 516, "s": 499, "text": "java.lang.Object" }, { "code": null, "e": 563, "s": 516, "text": " java.lang.reflect.AccessibleObject" }, { "code": null, "e": 616, "s": 563, "text": " java.lang.reflect.Executable" }, { "code": null, "e": 677, "s": 616, "text": " java.lang.reflect.Method" }, { "code": null, "e": 686, "s": 677, "text": "Methods:" }, { "code": null, "e": 712, "s": 686, "text": "getDefaultValue() Method:" }, { "code": null, "e": 717, "s": 712, "text": "Java" }, { "code": "// Java program to show the// Implementation of getDefaultvalue() import java.lang.reflect.Method; public class getDefaultValueExample { public static void main(String[] args) { Method[] methods = Demo.class.getMethods(); // calling method getDefaultValue() System.out.println(methods[0].getDefaultValue()); }} class Demo { private String str; // member function returning string str public String getSampleField() { return str; } public void setSampleField(String str) { this.str = str; }}", "e": 1276, "s": 717, "text": null }, { "code": null, "e": 1281, "s": 1276, "text": "null" }, { "code": null, "e": 1300, "s": 1281, "text": "toString() Method:" }, { "code": null, "e": 1305, "s": 1300, "text": "Java" }, { "code": "// Java program to show the// Implementation of toString() import java.lang.reflect.Method; public class MethodDemo { public static void main(String[] args) { Method[] methods = SampleClass.class.getMethods(); // calling method toString() System.out.println(methods[1].toString()); }} class SampleClass { private String str; public String getSampleField() { return str; } public void setSampleField(String str) { this.str = str; }}", "e": 1800, "s": 1305, "text": null }, { "code": null, "e": 1857, "s": 1800, "text": "public void SampleClass.setSampleField(java.lang.String)" }, { "code": null, "e": 1883, "s": 1857, "text": "java-lang-reflect-package" }, { "code": null, "e": 1890, "s": 1883, "text": "Picked" }, { "code": null, "e": 1914, "s": 1890, "text": "Technical Scripter 2020" }, { "code": null, "e": 1919, "s": 1914, "text": "Java" }, { "code": null, "e": 1938, "s": 1919, "text": "Technical Scripter" }, { "code": null, "e": 1943, "s": 1938, "text": "Java" }, { "code": null, "e": 2041, "s": 1943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2056, "s": 2041, "text": "Stream In Java" }, { "code": null, "e": 2077, "s": 2056, "text": "Introduction to Java" }, { "code": null, "e": 2098, "s": 2077, "text": "Constructors in Java" }, { "code": null, "e": 2117, "s": 2098, "text": "Exceptions in Java" }, { "code": null, "e": 2134, "s": 2117, "text": "Generics in Java" }, { "code": null, "e": 2164, "s": 2134, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2190, "s": 2164, "text": "Java Programming Examples" }, { "code": null, "e": 2206, "s": 2190, "text": "Strings in Java" }, { "code": null, "e": 2243, "s": 2206, "text": "Differences between JDK, JRE and JVM" } ]
Generate five random numbers from the normal distribution using NumPy
29 Aug, 2020 In Numpy we are provided with the module called random module that allows us to work with random numbers. The random module provides different methods for data distribution. In this article, we have to create an array of specified shape and fill it random numbers or values such that these values are part of a normal distribution or Gaussian distribution. This distribution is also called the Bell Curve this is because of its characteristics shape. To generate five random numbers from the normal distribution we will use numpy.random.normal() method of the random module. Syntax: numpy.random.normal(loc = 0.0, scale = 1.0, size = None) Parameters: loc: Mean of distribution scale: Standard derivation size: Resultant shape.If size argument is empty then by default single value is returned. Example 1: Python3 # importing moduleimport numpy as np # numpy.random.normal() methodr = np.random.normal(size=5) # printing numbersprint(r) Output : [ 0.27491897 -0.18001994 -0.01783066 1.07701319 -0.11356911] Example 2: Python3 # importing moduleimport numpy as np # numpy.random.normal() methodrandom_array = np.random.normal(0.0, 1.0, 5) # printing 1D array with random numbersprint("1D Array with random values : \n", random_array) Output : 1D Array with random values : [ 0.14559212 1.97263406 1.11170937 -0.88192442 0.8249291 ] Python numpy-Random Python-numpy 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 Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Aug, 2020" }, { "code": null, "e": 504, "s": 53, "text": "In Numpy we are provided with the module called random module that allows us to work with random numbers. The random module provides different methods for data distribution. In this article, we have to create an array of specified shape and fill it random numbers or values such that these values are part of a normal distribution or Gaussian distribution. This distribution is also called the Bell Curve this is because of its characteristics shape." }, { "code": null, "e": 630, "s": 504, "text": "To generate five random numbers from the normal distribution we will use numpy.random.normal() method of the random module. " }, { "code": null, "e": 696, "s": 630, "text": "Syntax: numpy.random.normal(loc = 0.0, scale = 1.0, size = None) " }, { "code": null, "e": 708, "s": 696, "text": "Parameters:" }, { "code": null, "e": 734, "s": 708, "text": "loc: Mean of distribution" }, { "code": null, "e": 762, "s": 734, "text": "scale: Standard derivation " }, { "code": null, "e": 852, "s": 762, "text": "size: Resultant shape.If size argument is empty then by default single value is returned." }, { "code": null, "e": 863, "s": 852, "text": "Example 1:" }, { "code": null, "e": 871, "s": 863, "text": "Python3" }, { "code": "# importing moduleimport numpy as np # numpy.random.normal() methodr = np.random.normal(size=5) # printing numbersprint(r)", "e": 998, "s": 871, "text": null }, { "code": null, "e": 1007, "s": 998, "text": "Output :" }, { "code": null, "e": 1070, "s": 1007, "text": "[ 0.27491897 -0.18001994 -0.01783066 1.07701319 -0.11356911]\n" }, { "code": null, "e": 1081, "s": 1070, "text": "Example 2:" }, { "code": null, "e": 1089, "s": 1081, "text": "Python3" }, { "code": "# importing moduleimport numpy as np # numpy.random.normal() methodrandom_array = np.random.normal(0.0, 1.0, 5) # printing 1D array with random numbersprint(\"1D Array with random values : \\n\", random_array)", "e": 1300, "s": 1089, "text": null }, { "code": null, "e": 1309, "s": 1300, "text": "Output :" }, { "code": null, "e": 1402, "s": 1309, "text": "1D Array with random values :\n[ 0.14559212 1.97263406 1.11170937 -0.88192442 0.8249291 ]\n" }, { "code": null, "e": 1422, "s": 1402, "text": "Python numpy-Random" }, { "code": null, "e": 1435, "s": 1422, "text": "Python-numpy" }, { "code": null, "e": 1442, "s": 1435, "text": "Python" }, { "code": null, "e": 1540, "s": 1442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1572, "s": 1540, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1599, "s": 1572, "text": "Python Classes and Objects" }, { "code": null, "e": 1620, "s": 1599, "text": "Python OOPs Concepts" }, { "code": null, "e": 1651, "s": 1620, "text": "Python | os.path.join() method" }, { "code": null, "e": 1707, "s": 1651, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1730, "s": 1707, "text": "Introduction To PYTHON" }, { "code": null, "e": 1772, "s": 1730, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1814, "s": 1772, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1853, "s": 1814, "text": "Python | datetime.timedelta() function" } ]
Weighted Job Scheduling in O(n Log n) time
22 Feb, 2022 Given N jobs where every job is represented by following three elements of it. Start TimeFinish TimeProfit or Value Associated Start Time Finish Time Profit or Value Associated Find the maximum profit subset of jobs such that no two jobs in the subset overlap.Example: Input: Number of Jobs n = 4 Job Details {Start Time, Finish Time, Profit} Job 1: {1, 2, 50} Job 2: {3, 5, 20} Job 3: {6, 19, 100} Job 4: {2, 100, 200} Output: The maximum profit is 250. We can get the maximum profit by scheduling jobs 1 and 4. Note that there is longer schedules possible Jobs 1, 2 and 3 but the profit with this schedule is 20+50+100 which is less than 250. We strongly recommend to refer below article as a prerequisite for this. Weighted Job SchedulingThe above problem can be solved using following recursive solution. 1) First sort jobs according to finish time. 2) Now apply following recursive process. // Here arr[] is array of n jobs findMaximumProfit(arr[], n) { a) if (n == 1) return arr[0]; b) Return the maximum of following two profits. (i) Maximum profit by excluding current job, i.e., findMaximumProfit(arr, n-1) (ii) Maximum profit by including the current job } How to find the profit including current job? The idea is to find the latest job before the current job (in sorted array) that doesn't conflict with current job 'arr[n-1]'. Once we find such a job, we recur for all jobs till that job and add profit of current job to result. In the above example, "job 1" is the latest non-conflicting for "job 4" and "job 2" is the latest non-conflicting for "job 3". We have discussed recursive and Dynamic Programming based approaches in the previous article. The implementations discussed in above post uses linear search to find the previous non-conflicting job. In this post, Binary Search based solution is discussed. The time complexity of Binary Search based solution is O(n Log n).The algorithm is: Sort the jobs by non-decreasing finish times.For each i from 1 to n, determine the maximum value of the schedule from the subsequence of jobs[0..i]. Do this by comparing the inclusion of job[i] to the schedule to the exclusion of job[i] to the schedule, and then taking the max. Sort the jobs by non-decreasing finish times. For each i from 1 to n, determine the maximum value of the schedule from the subsequence of jobs[0..i]. Do this by comparing the inclusion of job[i] to the schedule to the exclusion of job[i] to the schedule, and then taking the max. To find the profit with inclusion of job[i]. we need to find the latest job that doesn’t conflict with job[i]. The idea is to use Binary Search to find the latest non-conflicting job. C++ Java Python Javascript // C++ program for weighted job scheduling using Dynamic // Programming and Binary Search#include <iostream>#include <algorithm>using namespace std; // A job has start time, finish time and profit.struct Job{ int start, finish, profit;}; // A utility function that is used for sorting events// according to finish timebool myfunction(Job s1, Job s2){ return (s1.finish < s2.finish);} // A Binary Search based function to find the latest job// (before current job) that doesn't conflict with current// job. "index" is index of the current job. This function// returns -1 if all jobs before index conflict with it.// The array jobs[] is sorted in increasing order of finish// time.int binarySearch(Job jobs[], int index){ // Initialize 'lo' and 'hi' for Binary Search int lo = 0, hi = index - 1; // Perform binary Search iteratively while (lo <= hi) { int mid = (lo + hi) / 2; if (jobs[mid].finish <= jobs[index].start) { if (jobs[mid + 1].finish <= jobs[index].start) lo = mid + 1; else return mid; } else hi = mid - 1; } return -1;} // The main function that returns the maximum possible// profit from given array of jobsint findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time sort(arr, arr+n, myfunction); // Create an array to store solutions of subproblems. table[i] // stores the profit for jobs till arr[i] (including arr[i]) int *table = new int[n]; table[0] = arr[0].profit; // Fill entries in table[] using recursive property for (int i=1; i<n; i++) { // Find profit including the current job int inclProf = arr[i].profit; int l = binarySearch(arr, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = max(inclProf, table[i-1]); } // Store result and free dynamic memory allocated for table[] int result = table[n-1]; delete[] table; return result;} // Driver programint main(){ Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Optimal profit is " << findMaxProfit(arr, n); return 0;} // Java program for Weighted Job Scheduling in O(nLogn)// timeimport java.util.Arrays;import java.util.Comparator; // Class to represent a jobclass Job{ int start, finish, profit; // Constructor Job(int start, int finish, int profit) { this.start = start; this.finish = finish; this.profit = profit; }} // Used to sort job according to finish timesclass JobComparator implements Comparator<Job>{ public int compare(Job a, Job b) { return a.finish < b.finish ? -1 : a.finish == b.finish ? 0 : 1; }} public class WeightedIntervalScheduling{ /* A Binary Search based function to find the latest job (before current job) that doesn't conflict with current job. "index" is index of the current job. This function returns -1 if all jobs before index conflict with it. The array jobs[] is sorted in increasing order of finish time. */ static public int binarySearch(Job jobs[], int index) { // Initialize 'lo' and 'hi' for Binary Search int lo = 0, hi = index - 1; // Perform binary Search iteratively while (lo <= hi) { int mid = (lo + hi) / 2; if (jobs[mid].finish <= jobs[index].start) { if (jobs[mid + 1].finish <= jobs[index].start) lo = mid + 1; else return mid; } else hi = mid - 1; } return -1; } // The main function that returns the maximum possible // profit from given array of jobs static public int schedule(Job jobs[]) { // Sort jobs according to finish time Arrays.sort(jobs, new JobComparator()); // Create an array to store solutions of subproblems. // table[i] stores the profit for jobs till jobs[i] // (including jobs[i]) int n = jobs.length; int table[] = new int[n]; table[0] = jobs[0].profit; // Fill entries in M[] using recursive property for (int i=1; i<n; i++) { // Find profit including the current job int inclProf = jobs[i].profit; int l = binarySearch(jobs, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i-1]); } return table[n-1]; } // Driver method to test above public static void main(String[] args) { Job jobs[] = {new Job(1, 2, 50), new Job(3, 5, 20), new Job(6, 19, 100), new Job(2, 100, 200)}; System.out.println("Optimal profit is " + schedule(jobs)); }} # Python program for weighted job scheduling using Dynamic# Programming and Binary Search # Class to represent a jobclass Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit # A Binary Search based function to find the latest job# (before current job) that doesn't conflict with current# job. "index" is index of the current job. This function# returns -1 if all jobs before index conflict with it.# The array jobs[] is sorted in increasing order of finish# time.def binarySearch(job, start_index): # Initialize 'lo' and 'hi' for Binary Search lo = 0 hi = start_index - 1 # Perform binary Search iteratively while lo <= hi: mid = (lo + hi) // 2 if job[mid].finish <= job[start_index].start: if job[mid + 1].finish <= job[start_index].start: lo = mid + 1 else: return mid else: hi = mid - 1 return -1 # The main function that returns the maximum possible# profit from given array of jobsdef schedule(job): # Sort jobs according to finish time job = sorted(job, key = lambda j: j.finish) # Create an array to store solutions of subproblems. table[i] # stores the profit for jobs till arr[i] (including arr[i]) n = len(job) table = [0 for _ in range(n)] table[0] = job[0].profit; # Fill entries in table[] using recursive property for i in range(1, n): # Find profit including the current job inclProf = job[i].profit l = binarySearch(job, i) if (l != -1): inclProf += table[l]; # Store maximum of including and excluding table[i] = max(inclProf, table[i - 1]) return table[n-1] # Driver code to test above functionjob = [Job(1, 2, 50), Job(3, 5, 20), Job(6, 19, 100), Job(2, 100, 200)]print("Optimal profit is"),print schedule(job) <script> // JavaScript program for weighted job scheduling using Dynamic// Programming and Binary Search // Class to represent a jobclass Job{ constructor(start, finish, profit){ this.start = start this.finish = finish this.profit = profit }} // A Binary Search based function to find the latest job// (before current job) that doesn't conflict with current// job. "index" is index of the current job. This function// returns -1 if all jobs before index conflict with it.// The array jobs[] is sorted in increasing order of finish// time.function binarySearch(job, start_index){ // Initialize 'lo' and 'hi' for Binary Search let lo = 0 let hi = start_index - 1 // Perform binary Search iteratively while(lo <= hi){ let mid = Math.floor((lo + hi) /2); if (job[mid].finish <= job[start_index].start){ if(job[mid + 1].finish <= job[start_index].start) lo = mid + 1 else return mid } else hi = mid - 1 } return -1 } // The main function that returns the maximum possible// profit from given array of jobsfunction schedule(job){ // Sort jobs according to finish time job.sort((a,b)=>a.finish - b.finish) // Create an array to store solutions of subproblems. table[i] // stores the profit for jobs till arr[i] (including arr[i]) let n = job.length let table = new Array(n).fill(0) table[0] = job[0].profit; // Fill entries in table[] using recursive property for(let i=1;i<n;i++){ // Find profit including the current job inclProf = job[i].profit l = binarySearch(job, i) if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i - 1]) } return table[n-1]} // Driver code to test above functionlet job = [new Job(1, 2, 50), new Job(3, 5, 20), new Job(6, 19, 100), new Job(2, 100, 200)] document.write("Optimal profit is ")document.write(schedule(job),"</br>") // This code is contributed by shinjanpatra.</script> Output: Optimal profit is 250 This article is contributed by Daniel Ray. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shinjanpatra Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Sieve of Eratosthenes Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Minimum number of jumps to reach end Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Find minimum number of coins that make a given value Find if there is a path between two vertices in an undirected graph Tabulation vs Memoization
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Feb, 2022" }, { "code": null, "e": 131, "s": 52, "text": "Given N jobs where every job is represented by following three elements of it." }, { "code": null, "e": 179, "s": 131, "text": "Start TimeFinish TimeProfit or Value Associated" }, { "code": null, "e": 190, "s": 179, "text": "Start Time" }, { "code": null, "e": 202, "s": 190, "text": "Finish Time" }, { "code": null, "e": 229, "s": 202, "text": "Profit or Value Associated" }, { "code": null, "e": 322, "s": 229, "text": "Find the maximum profit subset of jobs such that no two jobs in the subset overlap.Example: " }, { "code": null, "e": 741, "s": 322, "text": "Input: Number of Jobs n = 4\n Job Details {Start Time, Finish Time, Profit}\n Job 1: {1, 2, 50} \n Job 2: {3, 5, 20}\n Job 3: {6, 19, 100}\n Job 4: {2, 100, 200}\nOutput: The maximum profit is 250.\nWe can get the maximum profit by scheduling jobs 1 and 4.\nNote that there is longer schedules possible Jobs 1, 2 and 3 \nbut the profit with this schedule is 20+50+100 which is less than 250. " }, { "code": null, "e": 907, "s": 741, "text": "We strongly recommend to refer below article as a prerequisite for this. Weighted Job SchedulingThe above problem can be solved using following recursive solution. " }, { "code": null, "e": 1737, "s": 907, "text": "1) First sort jobs according to finish time.\n2) Now apply following recursive process. \n // Here arr[] is array of n jobs\n findMaximumProfit(arr[], n)\n {\n a) if (n == 1) return arr[0];\n b) Return the maximum of following two profits.\n (i) Maximum profit by excluding current job, i.e., \n findMaximumProfit(arr, n-1)\n (ii) Maximum profit by including the current job \n }\n\nHow to find the profit including current job?\nThe idea is to find the latest job before the current job (in \nsorted array) that doesn't conflict with current job 'arr[n-1]'. \nOnce we find such a job, we recur for all jobs till that job and\nadd profit of current job to result.\nIn the above example, \"job 1\" is the latest non-conflicting\nfor \"job 4\" and \"job 2\" is the latest non-conflicting for \"job 3\"." }, { "code": null, "e": 2079, "s": 1737, "text": "We have discussed recursive and Dynamic Programming based approaches in the previous article. The implementations discussed in above post uses linear search to find the previous non-conflicting job. In this post, Binary Search based solution is discussed. The time complexity of Binary Search based solution is O(n Log n).The algorithm is: " }, { "code": null, "e": 2358, "s": 2079, "text": "Sort the jobs by non-decreasing finish times.For each i from 1 to n, determine the maximum value of the schedule from the subsequence of jobs[0..i]. Do this by comparing the inclusion of job[i] to the schedule to the exclusion of job[i] to the schedule, and then taking the max." }, { "code": null, "e": 2404, "s": 2358, "text": "Sort the jobs by non-decreasing finish times." }, { "code": null, "e": 2638, "s": 2404, "text": "For each i from 1 to n, determine the maximum value of the schedule from the subsequence of jobs[0..i]. Do this by comparing the inclusion of job[i] to the schedule to the exclusion of job[i] to the schedule, and then taking the max." }, { "code": null, "e": 2823, "s": 2638, "text": "To find the profit with inclusion of job[i]. we need to find the latest job that doesn’t conflict with job[i]. The idea is to use Binary Search to find the latest non-conflicting job. " }, { "code": null, "e": 2829, "s": 2825, "text": "C++" }, { "code": null, "e": 2834, "s": 2829, "text": "Java" }, { "code": null, "e": 2841, "s": 2834, "text": "Python" }, { "code": null, "e": 2852, "s": 2841, "text": "Javascript" }, { "code": "// C++ program for weighted job scheduling using Dynamic // Programming and Binary Search#include <iostream>#include <algorithm>using namespace std; // A job has start time, finish time and profit.struct Job{ int start, finish, profit;}; // A utility function that is used for sorting events// according to finish timebool myfunction(Job s1, Job s2){ return (s1.finish < s2.finish);} // A Binary Search based function to find the latest job// (before current job) that doesn't conflict with current// job. \"index\" is index of the current job. This function// returns -1 if all jobs before index conflict with it.// The array jobs[] is sorted in increasing order of finish// time.int binarySearch(Job jobs[], int index){ // Initialize 'lo' and 'hi' for Binary Search int lo = 0, hi = index - 1; // Perform binary Search iteratively while (lo <= hi) { int mid = (lo + hi) / 2; if (jobs[mid].finish <= jobs[index].start) { if (jobs[mid + 1].finish <= jobs[index].start) lo = mid + 1; else return mid; } else hi = mid - 1; } return -1;} // The main function that returns the maximum possible// profit from given array of jobsint findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time sort(arr, arr+n, myfunction); // Create an array to store solutions of subproblems. table[i] // stores the profit for jobs till arr[i] (including arr[i]) int *table = new int[n]; table[0] = arr[0].profit; // Fill entries in table[] using recursive property for (int i=1; i<n; i++) { // Find profit including the current job int inclProf = arr[i].profit; int l = binarySearch(arr, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = max(inclProf, table[i-1]); } // Store result and free dynamic memory allocated for table[] int result = table[n-1]; delete[] table; return result;} // Driver programint main(){ Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Optimal profit is \" << findMaxProfit(arr, n); return 0;}", "e": 5136, "s": 2852, "text": null }, { "code": "// Java program for Weighted Job Scheduling in O(nLogn)// timeimport java.util.Arrays;import java.util.Comparator; // Class to represent a jobclass Job{ int start, finish, profit; // Constructor Job(int start, int finish, int profit) { this.start = start; this.finish = finish; this.profit = profit; }} // Used to sort job according to finish timesclass JobComparator implements Comparator<Job>{ public int compare(Job a, Job b) { return a.finish < b.finish ? -1 : a.finish == b.finish ? 0 : 1; }} public class WeightedIntervalScheduling{ /* A Binary Search based function to find the latest job (before current job) that doesn't conflict with current job. \"index\" is index of the current job. This function returns -1 if all jobs before index conflict with it. The array jobs[] is sorted in increasing order of finish time. */ static public int binarySearch(Job jobs[], int index) { // Initialize 'lo' and 'hi' for Binary Search int lo = 0, hi = index - 1; // Perform binary Search iteratively while (lo <= hi) { int mid = (lo + hi) / 2; if (jobs[mid].finish <= jobs[index].start) { if (jobs[mid + 1].finish <= jobs[index].start) lo = mid + 1; else return mid; } else hi = mid - 1; } return -1; } // The main function that returns the maximum possible // profit from given array of jobs static public int schedule(Job jobs[]) { // Sort jobs according to finish time Arrays.sort(jobs, new JobComparator()); // Create an array to store solutions of subproblems. // table[i] stores the profit for jobs till jobs[i] // (including jobs[i]) int n = jobs.length; int table[] = new int[n]; table[0] = jobs[0].profit; // Fill entries in M[] using recursive property for (int i=1; i<n; i++) { // Find profit including the current job int inclProf = jobs[i].profit; int l = binarySearch(jobs, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i-1]); } return table[n-1]; } // Driver method to test above public static void main(String[] args) { Job jobs[] = {new Job(1, 2, 50), new Job(3, 5, 20), new Job(6, 19, 100), new Job(2, 100, 200)}; System.out.println(\"Optimal profit is \" + schedule(jobs)); }}", "e": 7820, "s": 5136, "text": null }, { "code": "# Python program for weighted job scheduling using Dynamic# Programming and Binary Search # Class to represent a jobclass Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit # A Binary Search based function to find the latest job# (before current job) that doesn't conflict with current# job. \"index\" is index of the current job. This function# returns -1 if all jobs before index conflict with it.# The array jobs[] is sorted in increasing order of finish# time.def binarySearch(job, start_index): # Initialize 'lo' and 'hi' for Binary Search lo = 0 hi = start_index - 1 # Perform binary Search iteratively while lo <= hi: mid = (lo + hi) // 2 if job[mid].finish <= job[start_index].start: if job[mid + 1].finish <= job[start_index].start: lo = mid + 1 else: return mid else: hi = mid - 1 return -1 # The main function that returns the maximum possible# profit from given array of jobsdef schedule(job): # Sort jobs according to finish time job = sorted(job, key = lambda j: j.finish) # Create an array to store solutions of subproblems. table[i] # stores the profit for jobs till arr[i] (including arr[i]) n = len(job) table = [0 for _ in range(n)] table[0] = job[0].profit; # Fill entries in table[] using recursive property for i in range(1, n): # Find profit including the current job inclProf = job[i].profit l = binarySearch(job, i) if (l != -1): inclProf += table[l]; # Store maximum of including and excluding table[i] = max(inclProf, table[i - 1]) return table[n-1] # Driver code to test above functionjob = [Job(1, 2, 50), Job(3, 5, 20), Job(6, 19, 100), Job(2, 100, 200)]print(\"Optimal profit is\"),print schedule(job)", "e": 9738, "s": 7820, "text": null }, { "code": "<script> // JavaScript program for weighted job scheduling using Dynamic// Programming and Binary Search // Class to represent a jobclass Job{ constructor(start, finish, profit){ this.start = start this.finish = finish this.profit = profit }} // A Binary Search based function to find the latest job// (before current job) that doesn't conflict with current// job. \"index\" is index of the current job. This function// returns -1 if all jobs before index conflict with it.// The array jobs[] is sorted in increasing order of finish// time.function binarySearch(job, start_index){ // Initialize 'lo' and 'hi' for Binary Search let lo = 0 let hi = start_index - 1 // Perform binary Search iteratively while(lo <= hi){ let mid = Math.floor((lo + hi) /2); if (job[mid].finish <= job[start_index].start){ if(job[mid + 1].finish <= job[start_index].start) lo = mid + 1 else return mid } else hi = mid - 1 } return -1 } // The main function that returns the maximum possible// profit from given array of jobsfunction schedule(job){ // Sort jobs according to finish time job.sort((a,b)=>a.finish - b.finish) // Create an array to store solutions of subproblems. table[i] // stores the profit for jobs till arr[i] (including arr[i]) let n = job.length let table = new Array(n).fill(0) table[0] = job[0].profit; // Fill entries in table[] using recursive property for(let i=1;i<n;i++){ // Find profit including the current job inclProf = job[i].profit l = binarySearch(job, i) if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i - 1]) } return table[n-1]} // Driver code to test above functionlet job = [new Job(1, 2, 50), new Job(3, 5, 20), new Job(6, 19, 100), new Job(2, 100, 200)] document.write(\"Optimal profit is \")document.write(schedule(job),\"</br>\") // This code is contributed by shinjanpatra.</script>", "e": 11851, "s": 9738, "text": null }, { "code": null, "e": 11859, "s": 11851, "text": "Output:" }, { "code": null, "e": 11881, "s": 11859, "text": "Optimal profit is 250" }, { "code": null, "e": 12049, "s": 11881, "text": "This article is contributed by Daniel Ray. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 12062, "s": 12049, "text": "shinjanpatra" }, { "code": null, "e": 12082, "s": 12062, "text": "Dynamic Programming" }, { "code": null, "e": 12102, "s": 12082, "text": "Dynamic Programming" }, { "code": null, "e": 12200, "s": 12102, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12238, "s": 12200, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 12271, "s": 12238, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 12293, "s": 12271, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 12328, "s": 12293, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 12359, "s": 12328, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 12396, "s": 12359, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 12464, "s": 12396, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 12517, "s": 12464, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 12585, "s": 12517, "text": "Find if there is a path between two vertices in an undirected graph" } ]
How to take Screenshots in ElectronJS ?
11 Jun, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. Electron supports Generating PDF files and Printing files from within the webpage in desktop applications. Along with these features, Electron also provides a way by which we can take screenshots of the webpage and save it as an image file onto the native System using the Instance methods of the BrowserWindow Object and the webContents property. Electron internally handles images using the NativeImage class, hence we also require the Instance methods of the nativeImage module to convert the respective NativeImage into PNG or JPEG format before they can be saved onto the native System. For Saving the files onto the native system we will use the Instance methods of the dialog module in Electron. This tutorial will demonstrate how to take Screenshots of the webpage in Electron and save them onto the native System. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Example: Follow the Steps given in Generate PDF in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: { "name": "electron-screenshot", "version": "1.0.0", "description": "Screenshot in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Create the assets folder according to the project structure. We will be using the assets folder as the default path to store the screenshot images taken by the application. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. Screenshot in Electron: The BrowserWindow Instance, webContents Property and the dialog module are part of the Main Process. To import and use BrowserWindow object and dialog module in the Renderer Process, we will be using Electron remote module. index.html: Add the following snippet in that file. The Take Screenshot button does not have any functionality associated with it yet. To change this, add the following code in the index.js file. html <h3>Screenshot of Page in Electron</h3><button id="screenshot"> Take Screenshot</button> index.js: Add the following snippet in that file. javascript const electron = require("electron");const BrowserWindow = electron.remote.BrowserWindow;const path = require("path");const fs = require("fs"); // Importing dialog module using remoteconst dialog = electron.remote.dialog; // let win = BrowserWindow.getAllWindows()[0];let win = BrowserWindow.getFocusedWindow(); var screenshot = document.getElementById("screenshot");screenshot.addEventListener("click", (event) => { win.webContents .capturePage({ x: 0, y: 0, width: 800, height: 600, }) .then((img) => { dialog .showSaveDialog({ title: "Select the File Path to save", // Default path to assets folder defaultPath: path.join(__dirname, "../assets/image.png"), // defaultPath: path.join(__dirname, // '../assets/image.jpeg'), buttonLabel: "Save", // Restricting the user to only Image Files. filters: [ { name: "Image Files", extensions: ["png", "jpeg", "jpg"], }, ], properties: [], }) .then((file) => { // Stating whether dialog operation was // cancelled or not. console.log(file.canceled); if (!file.canceled) { console.log(file.filePath.toString()); // Creating and Writing to the image.png file // Can save the File as a jpeg file as well, // by simply using img.toJPEG(100); fs.writeFile(file.filePath.toString(), img.toPNG(), "base64", function (err) { if (err) throw err; console.log("Saved!"); }); } }) .catch((err) => { console.log(err); }); }) .catch((err) => { console.log(err); });}); Explanation: The win.webContents.capturePage(rectangle) Instance method simply captures the screenshot of the webpage specified by the rectangle object. Omitting the rectangle object will capture the whole visible webpage i.e. the entire visible BrowserWindow Instance. It takes in the following parameters. rectangle: Object (Optional) The rectangle object. It consists of the following parameters which are required to define a rectangle and its position on the webpage/screen. x: Integer The X coordinate of the origin of the rectangle. In this case, the X coordinate represents the coordinate of the webpage/screen to be captured.y: Integer The Y coordinate of the origin of the rectangle. In this case, the Y coordinate represents the coordinate of the webpage/screen to be captured.width: Integer The width of the rectangle. In this case, it represents the width of the webpage/screen to be captured.height: Integer The height of the rectangle. In this case, it represents the height of the webpage/screen to be captured. x: Integer The X coordinate of the origin of the rectangle. In this case, the X coordinate represents the coordinate of the webpage/screen to be captured. y: Integer The Y coordinate of the origin of the rectangle. In this case, the Y coordinate represents the coordinate of the webpage/screen to be captured. width: Integer The width of the rectangle. In this case, it represents the width of the webpage/screen to be captured. height: Integer The height of the rectangle. In this case, it represents the height of the webpage/screen to be captured. The win.webContents.capturePage() Instance method returns a Promise and it resolves with a NativeImage instance on successful Screenshot capture. We need to convert this NativeImage Instance to either JPEG or PNG using the Instance methods of the nativeImage module before it can be saved on the native System. image.toPNG(options) This Instance method converts the NativeImage Instance to PNG format by returning a NodeJS Buffer that contains the image’s PNG encoded data. We will use the Buffer returned by this method to write the image to a .png file as shown in the code using the fs module. The default Encoding of the PNG file will be base64. It takes in the following parameters. options: Object (Optional) The options object consists of a single parameter i.e. the scaleFactor: Double (Optional) representing the scale factor (zoom) of the Image. By default, value taken is 1.0. options: Object (Optional) The options object consists of a single parameter i.e. the scaleFactor: Double (Optional) representing the scale factor (zoom) of the Image. By default, value taken is 1.0. image.toJPEG(quality) This Instance method converts the NativeImage Instance to JPEG format by returning a NodeJS BUffer that contains the image’s JPEG encoded data. We will use the Buffer returned by this method to write the image to a .jpeg file as shown in the code using the fs module. The default Encoding of the JPEG file will be base64. It takes in the following parameters.quality: Integer This value cannot be empty. It can take in a value between 0 and 100. This value represents the quality factor of the image, 0 being the lowest quality and 100 being the highest quality image. quality: Integer This value cannot be empty. It can take in a value between 0 and 100. This value represents the quality factor of the image, 0 being the lowest quality and 100 being the highest quality image. The dialog.showSaveDialog(options) Instance method of the dialog module is used to interact with the native File System to open a System dialog for saving files in local by fetching the filepath as specified by the user. By default, we are specifying the filepath to the assets folder and saving the image file in PNG format with the name of image.png. For more information on how to restrict the user to PNG/JPEG formats and properties of the dialog.showSaveDialog() method, Refer to Save Files in ElectronJS.To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code. BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code. Output: ElectronJS CSS HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 ? How to select all child elements recursively using CSS? 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 ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2020" }, { "code": null, "e": 328, "s": 28, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 1151, "s": 328, "text": "Electron supports Generating PDF files and Printing files from within the webpage in desktop applications. Along with these features, Electron also provides a way by which we can take screenshots of the webpage and save it as an image file onto the native System using the Instance methods of the BrowserWindow Object and the webContents property. Electron internally handles images using the NativeImage class, hence we also require the Instance methods of the nativeImage module to convert the respective NativeImage into PNG or JPEG format before they can be saved onto the native System. For Saving the files onto the native system we will use the Instance methods of the dialog module in Electron. This tutorial will demonstrate how to take Screenshots of the webpage in Electron and save them onto the native System." }, { "code": null, "e": 1321, "s": 1151, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 1776, "s": 1321, "text": "Example: Follow the Steps given in Generate PDF in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. " }, { "code": null, "e": 1791, "s": 1776, "text": "package.json: " }, { "code": null, "e": 2097, "s": 1791, "text": "{\n \"name\": \"electron-screenshot\",\n \"version\": \"1.0.0\",\n \"description\": \"Screenshot in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n\n" }, { "code": null, "e": 2404, "s": 2097, "text": "Create the assets folder according to the project structure. We will be using the assets folder as the default path to store the screenshot images taken by the application. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. " }, { "code": null, "e": 2653, "s": 2404, "text": "Screenshot in Electron: The BrowserWindow Instance, webContents Property and the dialog module are part of the Main Process. To import and use BrowserWindow object and dialog module in the Renderer Process, we will be using Electron remote module. " }, { "code": null, "e": 2849, "s": 2653, "text": "index.html: Add the following snippet in that file. The Take Screenshot button does not have any functionality associated with it yet. To change this, add the following code in the index.js file." }, { "code": null, "e": 2854, "s": 2849, "text": "html" }, { "code": "<h3>Screenshot of Page in Electron</h3><button id=\"screenshot\"> Take Screenshot</button>", "e": 2944, "s": 2854, "text": null }, { "code": null, "e": 2995, "s": 2944, "text": "index.js: Add the following snippet in that file. " }, { "code": null, "e": 3006, "s": 2995, "text": "javascript" }, { "code": "const electron = require(\"electron\");const BrowserWindow = electron.remote.BrowserWindow;const path = require(\"path\");const fs = require(\"fs\"); // Importing dialog module using remoteconst dialog = electron.remote.dialog; // let win = BrowserWindow.getAllWindows()[0];let win = BrowserWindow.getFocusedWindow(); var screenshot = document.getElementById(\"screenshot\");screenshot.addEventListener(\"click\", (event) => { win.webContents .capturePage({ x: 0, y: 0, width: 800, height: 600, }) .then((img) => { dialog .showSaveDialog({ title: \"Select the File Path to save\", // Default path to assets folder defaultPath: path.join(__dirname, \"../assets/image.png\"), // defaultPath: path.join(__dirname, // '../assets/image.jpeg'), buttonLabel: \"Save\", // Restricting the user to only Image Files. filters: [ { name: \"Image Files\", extensions: [\"png\", \"jpeg\", \"jpg\"], }, ], properties: [], }) .then((file) => { // Stating whether dialog operation was // cancelled or not. console.log(file.canceled); if (!file.canceled) { console.log(file.filePath.toString()); // Creating and Writing to the image.png file // Can save the File as a jpeg file as well, // by simply using img.toJPEG(100); fs.writeFile(file.filePath.toString(), img.toPNG(), \"base64\", function (err) { if (err) throw err; console.log(\"Saved!\"); }); } }) .catch((err) => { console.log(err); }); }) .catch((err) => { console.log(err); });});", "e": 5336, "s": 3006, "text": null }, { "code": null, "e": 5645, "s": 5336, "text": "Explanation: The win.webContents.capturePage(rectangle) Instance method simply captures the screenshot of the webpage specified by the rectangle object. Omitting the rectangle object will capture the whole visible webpage i.e. the entire visible BrowserWindow Instance. It takes in the following parameters. " }, { "code": null, "e": 6365, "s": 5645, "text": "rectangle: Object (Optional) The rectangle object. It consists of the following parameters which are required to define a rectangle and its position on the webpage/screen. x: Integer The X coordinate of the origin of the rectangle. In this case, the X coordinate represents the coordinate of the webpage/screen to be captured.y: Integer The Y coordinate of the origin of the rectangle. In this case, the Y coordinate represents the coordinate of the webpage/screen to be captured.width: Integer The width of the rectangle. In this case, it represents the width of the webpage/screen to be captured.height: Integer The height of the rectangle. In this case, it represents the height of the webpage/screen to be captured." }, { "code": null, "e": 6520, "s": 6365, "text": "x: Integer The X coordinate of the origin of the rectangle. In this case, the X coordinate represents the coordinate of the webpage/screen to be captured." }, { "code": null, "e": 6675, "s": 6520, "text": "y: Integer The Y coordinate of the origin of the rectangle. In this case, the Y coordinate represents the coordinate of the webpage/screen to be captured." }, { "code": null, "e": 6794, "s": 6675, "text": "width: Integer The width of the rectangle. In this case, it represents the width of the webpage/screen to be captured." }, { "code": null, "e": 6916, "s": 6794, "text": "height: Integer The height of the rectangle. In this case, it represents the height of the webpage/screen to be captured." }, { "code": null, "e": 7228, "s": 6916, "text": "The win.webContents.capturePage() Instance method returns a Promise and it resolves with a NativeImage instance on successful Screenshot capture. We need to convert this NativeImage Instance to either JPEG or PNG using the Instance methods of the nativeImage module before it can be saved on the native System. " }, { "code": null, "e": 7805, "s": 7228, "text": "image.toPNG(options) This Instance method converts the NativeImage Instance to PNG format by returning a NodeJS Buffer that contains the image’s PNG encoded data. We will use the Buffer returned by this method to write the image to a .png file as shown in the code using the fs module. The default Encoding of the PNG file will be base64. It takes in the following parameters. options: Object (Optional) The options object consists of a single parameter i.e. the scaleFactor: Double (Optional) representing the scale factor (zoom) of the Image. By default, value taken is 1.0." }, { "code": null, "e": 8005, "s": 7805, "text": "options: Object (Optional) The options object consists of a single parameter i.e. the scaleFactor: Double (Optional) representing the scale factor (zoom) of the Image. By default, value taken is 1.0." }, { "code": null, "e": 8596, "s": 8005, "text": "image.toJPEG(quality) This Instance method converts the NativeImage Instance to JPEG format by returning a NodeJS BUffer that contains the image’s JPEG encoded data. We will use the Buffer returned by this method to write the image to a .jpeg file as shown in the code using the fs module. The default Encoding of the JPEG file will be base64. It takes in the following parameters.quality: Integer This value cannot be empty. It can take in a value between 0 and 100. This value represents the quality factor of the image, 0 being the lowest quality and 100 being the highest quality image." }, { "code": null, "e": 8806, "s": 8596, "text": "quality: Integer This value cannot be empty. It can take in a value between 0 and 100. This value represents the quality factor of the image, 0 being the lowest quality and 100 being the highest quality image." }, { "code": null, "e": 9460, "s": 8806, "text": "The dialog.showSaveDialog(options) Instance method of the dialog module is used to interact with the native File System to open a System dialog for saving files in local by fetching the filepath as specified by the user. By default, we are specifying the filepath to the assets folder and saving the image file in PNG format with the name of image.png. For more information on how to restrict the user to PNG/JPEG formats and properties of the dialog.showSaveDialog() method, Refer to Save Files in ElectronJS.To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. " }, { "code": null, "e": 9698, "s": 9460, "text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code." }, { "code": null, "e": 10022, "s": 9698, "text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code. " }, { "code": null, "e": 10030, "s": 10022, "text": "Output:" }, { "code": null, "e": 10041, "s": 10030, "text": "ElectronJS" }, { "code": null, "e": 10045, "s": 10041, "text": "CSS" }, { "code": null, "e": 10050, "s": 10045, "text": "HTML" }, { "code": null, "e": 10061, "s": 10050, "text": "JavaScript" }, { "code": null, "e": 10069, "s": 10061, "text": "Node.js" }, { "code": null, "e": 10086, "s": 10069, "text": "Web Technologies" }, { "code": null, "e": 10091, "s": 10086, "text": "HTML" }, { "code": null, "e": 10189, "s": 10091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10228, "s": 10189, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 10267, "s": 10228, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 10331, "s": 10267, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 10392, "s": 10331, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 10448, "s": 10392, "text": "How to select all child elements recursively using CSS?" }, { "code": null, "e": 10472, "s": 10448, "text": "REST API (Introduction)" }, { "code": null, "e": 10525, "s": 10472, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 10585, "s": 10525, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 10646, "s": 10585, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
isocalendar() Function Of Datetime.date Class In Python
28 Jul, 2021 The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week. Therefore, ISO years always start with Monday. ISO years can have either 52 full weeks or 53 full weeks. ISO years do not have any fractional weeks during the beginning of the year or at the end of the year. Syntax: isocalendar() Parameters: This function does not accept any parameter. Return values: This function returns a tuple of ISO Year, ISO Week Number and ISO Weekday. Example 1: Get ISO Year, ISO Week Number, and ISO Weekday. Python3 # Python3 code to demonstrate# Getting a tuple of ISO Year, # ISO Week Number and ISO Weekday # Importing date module from datetimefrom datetime import date # Calling the today() function# to return todays dateTodays_date = date.today() # Printing today's dateprint(Todays_date) # Calling the isocalendar() function# over the above today's date to return# its ISO Year, ISO Week Number# and ISO Weekdayprint(Todays_date.isocalendar()) Output: 2021-07-25 (2021, 29, 7) Example 2: Get ISO Year, ISO Week Number, and ISO Weekday with a specific date. Python3 # Python3 code to demonstrate# Getting a tuple of ISO Year, # ISO Week Number and ISO Weekday # Importing date module from datetimefrom datetime import date # Creating an instance for # different datesA = date(2020, 10, 11) # Calling the isocalendar() function# over the above specified dateDate = A.isocalendar() # Printing Original date and its # ISO Year, ISO Week Number# and ISO Weekdayprint("Original date:",A)print("Date in isocalendar is:", Date) Output: Original date: 2020-10-11 Date in isocalendar is: (2020, 41, 7) Picked Python-datetime 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 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": "\n28 Jul, 2021" }, { "code": null, "e": 136, "s": 28, "text": "The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday." }, { "code": null, "e": 142, "s": 136, "text": "Note:" }, { "code": null, "e": 234, "s": 142, "text": "According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week." }, { "code": null, "e": 281, "s": 234, "text": "Therefore, ISO years always start with Monday." }, { "code": null, "e": 339, "s": 281, "text": "ISO years can have either 52 full weeks or 53 full weeks." }, { "code": null, "e": 442, "s": 339, "text": "ISO years do not have any fractional weeks during the beginning of the year or at the end of the year." }, { "code": null, "e": 464, "s": 442, "text": "Syntax: isocalendar()" }, { "code": null, "e": 521, "s": 464, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 612, "s": 521, "text": "Return values: This function returns a tuple of ISO Year, ISO Week Number and ISO Weekday." }, { "code": null, "e": 672, "s": 612, "text": "Example 1: Get ISO Year, ISO Week Number, and ISO Weekday." }, { "code": null, "e": 680, "s": 672, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Getting a tuple of ISO Year, # ISO Week Number and ISO Weekday # Importing date module from datetimefrom datetime import date # Calling the today() function# to return todays dateTodays_date = date.today() # Printing today's dateprint(Todays_date) # Calling the isocalendar() function# over the above today's date to return# its ISO Year, ISO Week Number# and ISO Weekdayprint(Todays_date.isocalendar())", "e": 1120, "s": 680, "text": null }, { "code": null, "e": 1128, "s": 1120, "text": "Output:" }, { "code": null, "e": 1153, "s": 1128, "text": "2021-07-25\n(2021, 29, 7)" }, { "code": null, "e": 1234, "s": 1153, "text": "Example 2: Get ISO Year, ISO Week Number, and ISO Weekday with a specific date." }, { "code": null, "e": 1242, "s": 1234, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Getting a tuple of ISO Year, # ISO Week Number and ISO Weekday # Importing date module from datetimefrom datetime import date # Creating an instance for # different datesA = date(2020, 10, 11) # Calling the isocalendar() function# over the above specified dateDate = A.isocalendar() # Printing Original date and its # ISO Year, ISO Week Number# and ISO Weekdayprint(\"Original date:\",A)print(\"Date in isocalendar is:\", Date)", "e": 1702, "s": 1242, "text": null }, { "code": null, "e": 1710, "s": 1702, "text": "Output:" }, { "code": null, "e": 1774, "s": 1710, "text": "Original date: 2020-10-11\nDate in isocalendar is: (2020, 41, 7)" }, { "code": null, "e": 1781, "s": 1774, "text": "Picked" }, { "code": null, "e": 1797, "s": 1781, "text": "Python-datetime" }, { "code": null, "e": 1804, "s": 1797, "text": "Python" }, { "code": null, "e": 1902, "s": 1804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1934, "s": 1902, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1961, "s": 1934, "text": "Python Classes and Objects" }, { "code": null, "e": 1982, "s": 1961, "text": "Python OOPs Concepts" }, { "code": null, "e": 2005, "s": 1982, "text": "Introduction To PYTHON" }, { "code": null, "e": 2036, "s": 2005, "text": "Python | os.path.join() method" }, { "code": null, "e": 2092, "s": 2036, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2134, "s": 2092, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2176, "s": 2134, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2215, "s": 2176, "text": "Python | Get unique values from a list" } ]
Subset array sum by generating all the subsets
04 Feb, 2022 Given an array of size N and a sum, the task is to check whether some array elements can be added to sum to N . Note: At least one element should be included to form the sum.(i.e. sum cant be zero) Examples: Input: array = -1, 2, 4, 121, N = 5 Output: YES The array elements 2, 4, -1 can be added to sum to N Input: array = 1, 3, 7, 121, N = 5 Output:NO Approach: The idea is to generate all subsets using Generate all subsequences of array and correspondingly check if any subsequence has the sum equal to the given sum.Below is the implementation of the above approach: CPP Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Find way to sum to N using array elements atmost oncevoid find(int arr[], int length, int s){ // loop for all 2^n combinations for (int i = 1; i < (pow(2, length)); i++) { // sum of a combination int sum = 0; for (int j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1)) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { cout << "YES" << endl; return; } } // else print no cout << "NO" << endl;} // driver codeint main(){ int sum = 5; int array[] = { -1, 2, 4, 121 }; int length = sizeof(array) / sizeof(int); // find whether it is possible to sum to n find(array, length, sum); return 0;} // Java implementation of the above approachclass GFG{ // Find way to sum to N using array elements atmost once static void find(int [] arr, int length, int s) { // loop for all 2^n combinations for (int i = 1; i <= (Math.pow(2, length)); i++) { // sum of a combination int sum = 0; for (int j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1) % 2 == 1) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { System.out.println("YES"); return; } } // else print no System.out.println("NO"); } // driver code public static void main(String[] args) { int sum = 5; int []array = { -1, 2, 4, 121 }; int length = array.length; // find whether it is possible to sum to n find(array, length, sum); } } // This code is contributed by ihritik # Python3 implementationfrom itertools import combinations def find(lst, n): print('YES' if [1 for r in range(1, len(lst) + 1) for subset in combinations(lst, r) if sum(subset) == n] else 'NO') find([-1, 2, 4, 121], 5) #This code is contributed by signi dimitri // C# implementation of the above approachusing System;public class GFG{ // Find way to sum to N using array elements atmost once static void find(int [] arr, int length, int s) { // loop for all 2^n combinations for (int i = 1; i <= (Math.Pow(2, length)); i++) { // sum of a combination int sum = 0; for (int j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1) % 2 == 1) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { Console.Write("YES"); return; } } // else print no Console.Write("NO"); } // driver code public static void Main() { int sum = 5; int []array = { -1, 2, 4, 121 }; int length = array.Length; // find whether it is possible to sum to n find(array, length, sum); } } // This code is contributed by PrinciRaj19992 <?php// PHP implementation of the above approach // Find way to sum to N using array elements atmost once function find($arr, $length, $s){ // loop for all 2^n combinations for ( $i = 1; $i < (pow(2, $length)); $i++) { // sum of a combination $sum = 0; for ($j = 0; $j < $length; $j++) // if the bit is 1 then add the element if ((($i >> $j) & 1)) $sum += $arr[$j]; // if the sum is equal to given sum print yes if ($sum == $s) { echo "YES","\n"; return; } } // else print no echo "NO","\n";} // Driver code $sum = 5; $array = array(-1, 2, 4, 121 ); $length = sizeof($array) / sizeof($array[0]); // find whether it is possible to sum to n find($array, $length, $sum); // This code is contributed by ajit.?> <script> // Javascript implementation of the above approach // Find way to sum to N using array// elements atmost oncefunction find(arr, length, s){ // loop for all 2^n combinations for (var i = 1; i < (Math.pow(2, length)); i++) { // sum of a combination var sum = 0; for (var j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1)) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { document.write( "YES" + "<br>"); return; } } // else print no document.write( "NO" + "<br>");} var sum = 5;var array = [ -1, 2, 4, 121 ];var length = array.length; // find whether it is possible to sum to nfind(array, length, sum); // This code is contributed by SoumikMondal </script> YES Note: This program would not run for the large size of the array. ihritik signidimitri princiraj1992 akashaditya00 jit_t SoumikMondal sumitgumber28 subsequence subset Bit Magic Competitive Programming Bit Magic subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find whether a given number is power of 2 Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Feb, 2022" }, { "code": null, "e": 264, "s": 54, "text": "Given an array of size N and a sum, the task is to check whether some array elements can be added to sum to N . Note: At least one element should be included to form the sum.(i.e. sum cant be zero) Examples: " }, { "code": null, "e": 412, "s": 264, "text": "Input: array = -1, 2, 4, 121, N = 5\nOutput: YES\nThe array elements 2, 4, -1 can be added to sum to N\n\nInput: array = 1, 3, 7, 121, N = 5\nOutput:NO " }, { "code": null, "e": 634, "s": 414, "text": "Approach: The idea is to generate all subsets using Generate all subsequences of array and correspondingly check if any subsequence has the sum equal to the given sum.Below is the implementation of the above approach: " }, { "code": null, "e": 638, "s": 634, "text": "CPP" }, { "code": null, "e": 643, "s": 638, "text": "Java" }, { "code": null, "e": 651, "s": 643, "text": "Python3" }, { "code": null, "e": 654, "s": 651, "text": "C#" }, { "code": null, "e": 658, "s": 654, "text": "PHP" }, { "code": null, "e": 669, "s": 658, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Find way to sum to N using array elements atmost oncevoid find(int arr[], int length, int s){ // loop for all 2^n combinations for (int i = 1; i < (pow(2, length)); i++) { // sum of a combination int sum = 0; for (int j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1)) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { cout << \"YES\" << endl; return; } } // else print no cout << \"NO\" << endl;} // driver codeint main(){ int sum = 5; int array[] = { -1, 2, 4, 121 }; int length = sizeof(array) / sizeof(int); // find whether it is possible to sum to n find(array, length, sum); return 0;}", "e": 1549, "s": 669, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Find way to sum to N using array elements atmost once static void find(int [] arr, int length, int s) { // loop for all 2^n combinations for (int i = 1; i <= (Math.pow(2, length)); i++) { // sum of a combination int sum = 0; for (int j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1) % 2 == 1) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { System.out.println(\"YES\"); return; } } // else print no System.out.println(\"NO\"); } // driver code public static void main(String[] args) { int sum = 5; int []array = { -1, 2, 4, 121 }; int length = array.length; // find whether it is possible to sum to n find(array, length, sum); } } // This code is contributed by ihritik", "e": 2768, "s": 1549, "text": null }, { "code": "# Python3 implementationfrom itertools import combinations def find(lst, n): print('YES' if [1 for r in range(1, len(lst) + 1) for subset in combinations(lst, r) if sum(subset) == n] else 'NO') find([-1, 2, 4, 121], 5) #This code is contributed by signi dimitri", "e": 3077, "s": 2768, "text": null }, { "code": " // C# implementation of the above approachusing System;public class GFG{ // Find way to sum to N using array elements atmost once static void find(int [] arr, int length, int s) { // loop for all 2^n combinations for (int i = 1; i <= (Math.Pow(2, length)); i++) { // sum of a combination int sum = 0; for (int j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1) % 2 == 1) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { Console.Write(\"YES\"); return; } } // else print no Console.Write(\"NO\"); } // driver code public static void Main() { int sum = 5; int []array = { -1, 2, 4, 121 }; int length = array.Length; // find whether it is possible to sum to n find(array, length, sum); } } // This code is contributed by PrinciRaj19992", "e": 4313, "s": 3077, "text": null }, { "code": "<?php// PHP implementation of the above approach // Find way to sum to N using array elements atmost once function find($arr, $length, $s){ // loop for all 2^n combinations for ( $i = 1; $i < (pow(2, $length)); $i++) { // sum of a combination $sum = 0; for ($j = 0; $j < $length; $j++) // if the bit is 1 then add the element if ((($i >> $j) & 1)) $sum += $arr[$j]; // if the sum is equal to given sum print yes if ($sum == $s) { echo \"YES\",\"\\n\"; return; } } // else print no echo \"NO\",\"\\n\";} // Driver code $sum = 5; $array = array(-1, 2, 4, 121 ); $length = sizeof($array) / sizeof($array[0]); // find whether it is possible to sum to n find($array, $length, $sum); // This code is contributed by ajit.?>", "e": 5172, "s": 4313, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Find way to sum to N using array// elements atmost oncefunction find(arr, length, s){ // loop for all 2^n combinations for (var i = 1; i < (Math.pow(2, length)); i++) { // sum of a combination var sum = 0; for (var j = 0; j < length; j++) // if the bit is 1 then add the element if (((i >> j) & 1)) sum += arr[j]; // if the sum is equal to given sum print yes if (sum == s) { document.write( \"YES\" + \"<br>\"); return; } } // else print no document.write( \"NO\" + \"<br>\");} var sum = 5;var array = [ -1, 2, 4, 121 ];var length = array.length; // find whether it is possible to sum to nfind(array, length, sum); // This code is contributed by SoumikMondal </script>", "e": 6022, "s": 5172, "text": null }, { "code": null, "e": 6026, "s": 6022, "text": "YES" }, { "code": null, "e": 6095, "s": 6028, "text": "Note: This program would not run for the large size of the array. " }, { "code": null, "e": 6103, "s": 6095, "text": "ihritik" }, { "code": null, "e": 6116, "s": 6103, "text": "signidimitri" }, { "code": null, "e": 6130, "s": 6116, "text": "princiraj1992" }, { "code": null, "e": 6144, "s": 6130, "text": "akashaditya00" }, { "code": null, "e": 6150, "s": 6144, "text": "jit_t" }, { "code": null, "e": 6163, "s": 6150, "text": "SoumikMondal" }, { "code": null, "e": 6177, "s": 6163, "text": "sumitgumber28" }, { "code": null, "e": 6189, "s": 6177, "text": "subsequence" }, { "code": null, "e": 6196, "s": 6189, "text": "subset" }, { "code": null, "e": 6206, "s": 6196, "text": "Bit Magic" }, { "code": null, "e": 6230, "s": 6206, "text": "Competitive Programming" }, { "code": null, "e": 6240, "s": 6230, "text": "Bit Magic" }, { "code": null, "e": 6247, "s": 6240, "text": "subset" }, { "code": null, "e": 6345, "s": 6247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6398, "s": 6345, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 6428, "s": 6398, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 6466, "s": 6428, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 6506, "s": 6466, "text": "Binary representation of a given number" }, { "code": null, "e": 6549, "s": 6506, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 6592, "s": 6549, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 6635, "s": 6592, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 6676, "s": 6635, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 6703, "s": 6676, "text": "Modulo 10^9+7 (1000000007)" } ]
R program to find prime and composite numbers in an interval
03 Mar, 2021 A natural number (1, 2, 3, 4, 5 and so on) is called a prime number if it is greater than 1 and cannot be written as the product of two smaller natural numbers. The numbers greater than 1 that are not prime are called composite numbers. A composite number is a positive integer that can be formed by multiplying two smaller positive integers. Equivalently, it is a positive integer that has at least one divisor other than 1 and itself. Example: Input: 2 Output: Prime Explanation: it is divisible by only 2 so prime. Input: 4 Output: Composite Explanation: it is divisible by 2 and 4 so composite. Input: 5 Output: Prime Explanation: it is divisible by only 5 so prime. Algorithm: Initialize the range till where prime and composite numbers to be displayed. Create a separate empty lists to store prime and composite numbers. Since 1 is neither prime nor composite, We start checking condition for prime from 2 as i. Starting from 2 checks each and every digit that divides i exactly If No number divides i except that i then number gets stored in prime number list, Else gets stored in composite number list. It executes till n(given by us) limit reaches. Once it exits from loop, it prints both prime and composite numbers as separate list. Example: R # R code for Finding composite and prime numbers upto 100# initialize number nn=100 # arranging sequencex = seq(1, n) # creating an empty place to store the numbersprime_numbers=c() composite_numbers = c()for (i in seq(2, n)) { if (any(x == i)) { # prime numbers gets stored in a sequence order prime_numbers = c(prime_numbers, i) x = c(x[(x %% i) != 0], i) } else{ # composite numbers gets stored in a sequence order composite_numbers = c(composite_numbers, i) }} # printing the seriesprint("prime_numbers")print(prime_numbers) print("composite_numbers")print(composite_numbers) Output: [1] “prime_numbers” [1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 [1] “composite_numbers” [1] 4 6 8 9 10 12 14 15 16 18 20 21 22 24 25 26 27 28 30 [20] 32 33 34 35 36 38 39 40 42 44 45 46 48 49 50 51 52 54 55 [39] 56 57 58 60 62 63 64 65 66 68 69 70 72 74 75 76 77 78 80 [58] 81 82 84 85 86 87 88 90 91 92 93 94 95 96 98 99 100 Prime Number R Language Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Mar, 2021" }, { "code": null, "e": 265, "s": 28, "text": "A natural number (1, 2, 3, 4, 5 and so on) is called a prime number if it is greater than 1 and cannot be written as the product of two smaller natural numbers. The numbers greater than 1 that are not prime are called composite numbers." }, { "code": null, "e": 465, "s": 265, "text": "A composite number is a positive integer that can be formed by multiplying two smaller positive integers. Equivalently, it is a positive integer that has at least one divisor other than 1 and itself." }, { "code": null, "e": 474, "s": 465, "text": "Example:" }, { "code": null, "e": 483, "s": 474, "text": "Input: 2" }, { "code": null, "e": 497, "s": 483, "text": "Output: Prime" }, { "code": null, "e": 546, "s": 497, "text": "Explanation: it is divisible by only 2 so prime." }, { "code": null, "e": 556, "s": 546, "text": "Input: 4 " }, { "code": null, "e": 574, "s": 556, "text": "Output: Composite" }, { "code": null, "e": 628, "s": 574, "text": "Explanation: it is divisible by 2 and 4 so composite." }, { "code": null, "e": 637, "s": 628, "text": "Input: 5" }, { "code": null, "e": 651, "s": 637, "text": "Output: Prime" }, { "code": null, "e": 700, "s": 651, "text": "Explanation: it is divisible by only 5 so prime." }, { "code": null, "e": 711, "s": 700, "text": "Algorithm:" }, { "code": null, "e": 788, "s": 711, "text": "Initialize the range till where prime and composite numbers to be displayed." }, { "code": null, "e": 856, "s": 788, "text": "Create a separate empty lists to store prime and composite numbers." }, { "code": null, "e": 896, "s": 856, "text": "Since 1 is neither prime nor composite," }, { "code": null, "e": 947, "s": 896, "text": "We start checking condition for prime from 2 as i." }, { "code": null, "e": 1014, "s": 947, "text": "Starting from 2 checks each and every digit that divides i exactly" }, { "code": null, "e": 1097, "s": 1014, "text": "If No number divides i except that i then number gets stored in prime number list," }, { "code": null, "e": 1140, "s": 1097, "text": "Else gets stored in composite number list." }, { "code": null, "e": 1187, "s": 1140, "text": "It executes till n(given by us) limit reaches." }, { "code": null, "e": 1273, "s": 1187, "text": "Once it exits from loop, it prints both prime and composite numbers as separate list." }, { "code": null, "e": 1282, "s": 1273, "text": "Example:" }, { "code": null, "e": 1284, "s": 1282, "text": "R" }, { "code": "# R code for Finding composite and prime numbers upto 100# initialize number nn=100 # arranging sequencex = seq(1, n) # creating an empty place to store the numbersprime_numbers=c() composite_numbers = c()for (i in seq(2, n)) { if (any(x == i)) { # prime numbers gets stored in a sequence order prime_numbers = c(prime_numbers, i) x = c(x[(x %% i) != 0], i) } else{ # composite numbers gets stored in a sequence order composite_numbers = c(composite_numbers, i) }} # printing the seriesprint(\"prime_numbers\")print(prime_numbers) print(\"composite_numbers\")print(composite_numbers)", "e": 1898, "s": 1284, "text": null }, { "code": null, "e": 1906, "s": 1898, "text": "Output:" }, { "code": null, "e": 1926, "s": 1906, "text": "[1] “prime_numbers”" }, { "code": null, "e": 2006, "s": 1926, "text": " [1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97" }, { "code": null, "e": 2030, "s": 2006, "text": "[1] “composite_numbers”" }, { "code": null, "e": 2111, "s": 2030, "text": " [1] 4 6 8 9 10 12 14 15 16 18 20 21 22 24 25 26 27 28 30" }, { "code": null, "e": 2192, "s": 2111, "text": "[20] 32 33 34 35 36 38 39 40 42 44 45 46 48 49 50 51 52 54 55" }, { "code": null, "e": 2273, "s": 2192, "text": "[39] 56 57 58 60 62 63 64 65 66 68 69 70 72 74 75 76 77 78 80" }, { "code": null, "e": 2346, "s": 2273, "text": "[58] 81 82 84 85 86 87 88 90 91 92 93 94 95 96 98 99 100" }, { "code": null, "e": 2359, "s": 2346, "text": "Prime Number" }, { "code": null, "e": 2370, "s": 2359, "text": "R Language" }, { "code": null, "e": 2383, "s": 2370, "text": "Prime Number" }, { "code": null, "e": 2481, "s": 2383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2533, "s": 2481, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2591, "s": 2533, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2626, "s": 2591, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2664, "s": 2626, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2713, "s": 2664, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2730, "s": 2713, "text": "R - if statement" }, { "code": null, "e": 2767, "s": 2730, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2810, "s": 2767, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2847, "s": 2810, "text": "How to import an Excel File into R ?" } ]
Stack add(int, Object) method in Java with Example
24 Dec, 2018 The add(int, Object) method of Stack Class inserts an element at a specified index in the Stack. It shifts the element currently at that position (if any) and any subsequent elements to the right (will change their indices by adding one). Syntax: void add(int index, Object element) Parameters: This method accepts two parameters as described below. index: The index at which the specified element is to be inserted. element: The element which is needed to be inserted. Return Value: This method does not return any value. Exception: The method throws IndexOutOfBoundsException if the specified index is out of range of the size of the Stack. Below program illustrates the working of java.util.Stack.add(int index, Object element) method: Example: // Java code to illustrate boolean add(Object element)import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements in the Stack stack.add("Geeks"); stack.add("for"); stack.add("Geeks"); stack.add("10"); stack.add("20"); // Output the present Stack System.out.println("The Stack is: " + stack); // Adding new elements stack.add(2, "Last"); stack.add(4, "Element"); // Printing the new Stack System.out.println("The new Stack is: " + stack); }} The Stack is: [Geeks, for, Geeks, 10, 20] The new Stack is: [Geeks, for, Last, Geeks, Element, 10, 20] Example 2: // Java code to illustrate// boolean add(Object element) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method // to add elements in the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Output the present Stack System.out.println("The Stack is: " + stack); // Adding new elements stack.add(0, 100); stack.add(3, 200); // Printing the new Stack System.out.println("The new Stack is: " + stack); }} The Stack is: [10, 20, 30, 40, 50] The new Stack is: [100, 10, 20, 200, 30, 40, 50] Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 267, "s": 28, "text": "The add(int, Object) method of Stack Class inserts an element at a specified index in the Stack. It shifts the element currently at that position (if any) and any subsequent elements to the right (will change their indices by adding one)." }, { "code": null, "e": 275, "s": 267, "text": "Syntax:" }, { "code": null, "e": 311, "s": 275, "text": "void add(int index, Object element)" }, { "code": null, "e": 378, "s": 311, "text": "Parameters: This method accepts two parameters as described below." }, { "code": null, "e": 445, "s": 378, "text": "index: The index at which the specified element is to be inserted." }, { "code": null, "e": 498, "s": 445, "text": "element: The element which is needed to be inserted." }, { "code": null, "e": 551, "s": 498, "text": "Return Value: This method does not return any value." }, { "code": null, "e": 671, "s": 551, "text": "Exception: The method throws IndexOutOfBoundsException if the specified index is out of range of the size of the Stack." }, { "code": null, "e": 767, "s": 671, "text": "Below program illustrates the working of java.util.Stack.add(int index, Object element) method:" }, { "code": null, "e": 776, "s": 767, "text": "Example:" }, { "code": "// Java code to illustrate boolean add(Object element)import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements in the Stack stack.add(\"Geeks\"); stack.add(\"for\"); stack.add(\"Geeks\"); stack.add(\"10\"); stack.add(\"20\"); // Output the present Stack System.out.println(\"The Stack is: \" + stack); // Adding new elements stack.add(2, \"Last\"); stack.add(4, \"Element\"); // Printing the new Stack System.out.println(\"The new Stack is: \" + stack); }}", "e": 1475, "s": 776, "text": null }, { "code": null, "e": 1579, "s": 1475, "text": "The Stack is: [Geeks, for, Geeks, 10, 20]\nThe new Stack is: [Geeks, for, Last, Geeks, Element, 10, 20]\n" }, { "code": null, "e": 1590, "s": 1579, "text": "Example 2:" }, { "code": "// Java code to illustrate// boolean add(Object element) import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method // to add elements in the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Output the present Stack System.out.println(\"The Stack is: \" + stack); // Adding new elements stack.add(0, 100); stack.add(3, 200); // Printing the new Stack System.out.println(\"The new Stack is: \" + stack); }}", "e": 2342, "s": 1590, "text": null }, { "code": null, "e": 2427, "s": 2342, "text": "The Stack is: [10, 20, 30, 40, 50]\nThe new Stack is: [100, 10, 20, 200, 30, 40, 50]\n" }, { "code": null, "e": 2447, "s": 2427, "text": "Java - util package" }, { "code": null, "e": 2464, "s": 2447, "text": "Java-Collections" }, { "code": null, "e": 2479, "s": 2464, "text": "Java-Functions" }, { "code": null, "e": 2490, "s": 2479, "text": "Java-Stack" }, { "code": null, "e": 2495, "s": 2490, "text": "Java" }, { "code": null, "e": 2500, "s": 2495, "text": "Java" }, { "code": null, "e": 2517, "s": 2500, "text": "Java-Collections" }, { "code": null, "e": 2615, "s": 2517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2630, "s": 2615, "text": "Arrays in Java" }, { "code": null, "e": 2674, "s": 2630, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2710, "s": 2674, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 2735, "s": 2710, "text": "Reverse a string in Java" }, { "code": null, "e": 2786, "s": 2735, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2808, "s": 2786, "text": "For-each loop in Java" }, { "code": null, "e": 2839, "s": 2808, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2858, "s": 2839, "text": "Interfaces in Java" }, { "code": null, "e": 2888, "s": 2858, "text": "HashMap in Java with Examples" } ]
How to create a pop up message when a button is pressed in Python – Tkinter?
26 Dec, 2020 In this article, we will see how to create a button and how to show a popup message when a button is pressed in Python. Tkinter is a standard Python Package for creating GUI applications. Tkinter may be a set of wrappers that implement the Tk widgets as Python classes. Python, when combined with Tkinter, provides a quick and straightforward way to create GUI applications. Steps to create a Simple GUI in Python using Tkinter: Import Tkinter package and all of its modules.Create a GUI application root window (root = Tk()) and widgets will be inside the main window.Use mainloop() to call the endless loop of the window. If you forget to call this nothing will appear to the user. The window will await any user interaction till we close it. Import Tkinter package and all of its modules. Create a GUI application root window (root = Tk()) and widgets will be inside the main window. Use mainloop() to call the endless loop of the window. If you forget to call this nothing will appear to the user. The window will await any user interaction till we close it. Syntax : W = Button(root, options) main: Represents the root window. options: Its used for widgets. It can be used as key-value pairs separated by commas. Example 1: Python3 # import everything from tkinter modulefrom tkinter import * # import messagebox from tkinter moduleimport tkinter.messagebox # create a tkinter root windowroot = tkinter.Tk() # root window title and dimensionroot.title("When you press a button the message will pop up")root.geometry('500x300') # Create a messagebox showinfo def onClick(): tkinter.messagebox.showinfo("Welcome to GFG.", "Hi I'm your message") # Create a Buttonbutton = Button(root, text="Click Me", command=onClick, height=5, width=10) # Set the position of button on the top of window.button.pack(side='bottom')root.mainloop() Output: Output After clicking “Click me” Example 2: Python3 # import everything from tkinter modulefrom tkinter import * # import messagebox from tkinter moduleimport tkinter.messagebox # create a tkinter root windowroot = tkinter.Tk() # root window title and dimensionroot.title("When you press a any button the message will pop up")root.geometry('500x300') # Create a messagebox showinfo def East(): tkinter.messagebox.showinfo("Welcome to GFG", "East Button clicked") def West(): tkinter.messagebox.showinfo("Welcome to GFG", "West Button clicked") def North(): tkinter.messagebox.showinfo("Welcome to GFG", "North Button clicked") def South(): tkinter.messagebox.showinfo("Welcome to GFG", "South Button clicked") # Create a Buttons Button1 = Button(root, text="West", command=West, pady=10)Button2 = Button(root, text="East", command=East, pady=10)Button3 = Button(root, text="North", command=North, pady=10)Button4 = Button(root, text="South", command=South, pady=10) # Set the position of buttonsButton1.pack(side=LEFT)Button2.pack(side=RIGHT)Button3.pack(side=TOP)Button4.pack(side=BOTTOM) root.mainloop() Output 2: Output After clicking “North” Output After clicking “East” Picked Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Dec, 2020" }, { "code": null, "e": 403, "s": 28, "text": "In this article, we will see how to create a button and how to show a popup message when a button is pressed in Python. Tkinter is a standard Python Package for creating GUI applications. Tkinter may be a set of wrappers that implement the Tk widgets as Python classes. Python, when combined with Tkinter, provides a quick and straightforward way to create GUI applications." }, { "code": null, "e": 457, "s": 403, "text": "Steps to create a Simple GUI in Python using Tkinter:" }, { "code": null, "e": 773, "s": 457, "text": "Import Tkinter package and all of its modules.Create a GUI application root window (root = Tk()) and widgets will be inside the main window.Use mainloop() to call the endless loop of the window. If you forget to call this nothing will appear to the user. The window will await any user interaction till we close it." }, { "code": null, "e": 820, "s": 773, "text": "Import Tkinter package and all of its modules." }, { "code": null, "e": 915, "s": 820, "text": "Create a GUI application root window (root = Tk()) and widgets will be inside the main window." }, { "code": null, "e": 1091, "s": 915, "text": "Use mainloop() to call the endless loop of the window. If you forget to call this nothing will appear to the user. The window will await any user interaction till we close it." }, { "code": null, "e": 1129, "s": 1091, "text": "Syntax : W = Button(root, options) " }, { "code": null, "e": 1163, "s": 1129, "text": "main: Represents the root window." }, { "code": null, "e": 1250, "s": 1163, "text": "options: Its used for widgets. It can be used as key-value pairs separated by commas." }, { "code": null, "e": 1262, "s": 1250, "text": "Example 1: " }, { "code": null, "e": 1270, "s": 1262, "text": "Python3" }, { "code": "# import everything from tkinter modulefrom tkinter import * # import messagebox from tkinter moduleimport tkinter.messagebox # create a tkinter root windowroot = tkinter.Tk() # root window title and dimensionroot.title(\"When you press a button the message will pop up\")root.geometry('500x300') # Create a messagebox showinfo def onClick(): tkinter.messagebox.showinfo(\"Welcome to GFG.\", \"Hi I'm your message\") # Create a Buttonbutton = Button(root, text=\"Click Me\", command=onClick, height=5, width=10) # Set the position of button on the top of window.button.pack(side='bottom')root.mainloop()", "e": 1877, "s": 1270, "text": null }, { "code": null, "e": 1885, "s": 1877, "text": "Output:" }, { "code": null, "e": 1918, "s": 1885, "text": "Output After clicking “Click me”" }, { "code": null, "e": 1929, "s": 1918, "text": "Example 2:" }, { "code": null, "e": 1937, "s": 1929, "text": "Python3" }, { "code": "# import everything from tkinter modulefrom tkinter import * # import messagebox from tkinter moduleimport tkinter.messagebox # create a tkinter root windowroot = tkinter.Tk() # root window title and dimensionroot.title(\"When you press a any button the message will pop up\")root.geometry('500x300') # Create a messagebox showinfo def East(): tkinter.messagebox.showinfo(\"Welcome to GFG\", \"East Button clicked\") def West(): tkinter.messagebox.showinfo(\"Welcome to GFG\", \"West Button clicked\") def North(): tkinter.messagebox.showinfo(\"Welcome to GFG\", \"North Button clicked\") def South(): tkinter.messagebox.showinfo(\"Welcome to GFG\", \"South Button clicked\") # Create a Buttons Button1 = Button(root, text=\"West\", command=West, pady=10)Button2 = Button(root, text=\"East\", command=East, pady=10)Button3 = Button(root, text=\"North\", command=North, pady=10)Button4 = Button(root, text=\"South\", command=South, pady=10) # Set the position of buttonsButton1.pack(side=LEFT)Button2.pack(side=RIGHT)Button3.pack(side=TOP)Button4.pack(side=BOTTOM) root.mainloop()", "e": 3015, "s": 1937, "text": null }, { "code": null, "e": 3025, "s": 3015, "text": "Output 2:" }, { "code": null, "e": 3055, "s": 3025, "text": "Output After clicking “North”" }, { "code": null, "e": 3084, "s": 3055, "text": "Output After clicking “East”" }, { "code": null, "e": 3091, "s": 3084, "text": "Picked" }, { "code": null, "e": 3106, "s": 3091, "text": "Python-tkinter" }, { "code": null, "e": 3113, "s": 3106, "text": "Python" } ]
\subseteq - Tex Command
\subseteq - Used to create subseteq symbol. { \subseteq} \subseteq command draws subseteq symbol.
[ { "code": null, "e": 8164, "s": 8120, "text": "\\subseteq - Used to create subseteq symbol." }, { "code": null, "e": 8177, "s": 8164, "text": "{ \\subseteq}" } ]
Throwable printStackTrace() method in Java with Examples
15 Oct, 2021 The printStackTrace() method of Java.lang.Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred means its backtrace. This method prints a stack trace for this Throwable object on the standard error output stream. The first line of output shows the same string which was returned by the toString() method for this object means Exception class name and later lines represent data previously recorded by the method fillInStackTrace(). Syntax: public void printStackTrace() Return Value: This method do not returns anything.Below programs illustrate the printStackTrace method of Java.lang.Throwable class:Example 1: Java // Java program to demonstrate// the printStackTrace () Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // print stack trace e.printStackTrace(); } } // method which throws Exception public static void testException1() throws Exception { // create a ArrayIndexOutOfBoundsException Exception ArrayIndexOutOfBoundsException ae = new ArrayIndexOutOfBoundsException(); // create a new Exception Exception ioe = new Exception(); // initialize the cause and throw Exception ioe.initCause(ae); throw ioe; }} java.lang.Exception at GFG.testException1(File.java:36) at GFG.main(File.java:15) Caused by: java.lang.ArrayIndexOutOfBoundsException at GFG.testException1(File.java:32) ... 1 more Example 2: Java // Java program to demonstrate// the printStackTrace () Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // print stack trace e.printStackTrace(); } } // method which throws Exception public static void testException1() throws Exception { // create a ArrayIndexOutOfBoundsException Exception ArrayIndexOutOfBoundsException ae = new ArrayIndexOutOfBoundsException(); // create a new Exception Exception ioe = new Exception(); // initialize the cause and throw Exception ioe.initCause(ae); throw ioe; }} java.lang.Exception at GFG.testException1(File.java:36) at GFG.main(File.java:15) Caused by: java.lang.ArrayIndexOutOfBoundsException at GFG.testException1(File.java:32) ... 1 more The printStackTrace(PrintStream s) method of Java.lang.Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred to the specified print stream. This method works same as printStackTrace() but difference is only that it prints to specified print stream passed as parameter.Syntax: public void printStackTrace(PrintStream s) Parameters: This method accepts PrintStream s as a parameter which is specified print stream where we want to write this Throwable details.Return Value: This method do not returns anything.Below programs illustrate the printStackTrace(PrintStream s) method of Java.lang.Throwable class:Example 1: Java // Java program to demonstrate// the printStackTrace(PrintStream s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // create a array of Integers int[] i = new int[2]; // try to add numbers to array i[2] = 3; } catch (Throwable e) { // print Stack Trace e.printStackTrace(System.out); } }} java.lang.ArrayIndexOutOfBoundsException: 2 at GFG.main(File.java:18) Example 2: Java // Java program to demonstrate// the printStackTrace(PrintStream s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // create printstream object PrintStream obj = new PrintStream(System.out); // print stack trace e.printStackTrace(obj); } } // method which throws Exception public static void testException1() throws Exception { throw new Exception("System is Down"); }} java.lang.Exception: System is Down at GFG.testException1(File.java:35) at GFG.main(File.java:15) The printStackTrace(PrintWriter s) method of Java.lang.Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred to the specified print Writer. This method works same as printStackTrace() but difference is only that it prints to specified print Writer passed as parameter.Syntax: public void printStackTrace(PrintWriter s) Parameters: This method accepts PrintWriter s as a parameter which is specified print writer where this Throwable details are to be written.Return Value: This method do not returns anything.Below programs illustrate the printStackTrace(PrintWriter s) method of Throwable class:Example 1: Java // Java program to demonstrate// the printStackTrace(PrintWriter s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // divide two numbers int a = 74, b = 0; int c = a / b; } catch (Throwable e) { // Using a StringWriter, // to convert trace into a String: StringWriter sw = new StringWriter(); // create a PrintWriter PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String error = sw.toString(); System.out.println("Error:\n" + error); } }} Error: java.lang.ArithmeticException: / by zero at GFG.main(File.java:17) Example 2: Java // Java program to demonstrate// the printStackTrace(PrintWriter s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // Using a StringWriter, // to convert trace into a String: StringWriter sw = new StringWriter(); // create a PrintWriter PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String error = sw.toString(); System.out.println("Error:\n" + error); } } // method which throws Exception public static void testException1() throws Exception { throw new Exception( "Waiting for input but no response"); }} Error: java.lang.Exception: Waiting for input but no response at GFG.testException1(File.java:38) at GFG.main(File.java:15) References: https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#printStackTrace() https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream) https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintWriter) anikakapoor Java-Exception Handling Java-Exceptions Java-Functions Java-lang package java-Throwable Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Oct, 2021" }, { "code": null, "e": 573, "s": 54, "text": "The printStackTrace() method of Java.lang.Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred means its backtrace. This method prints a stack trace for this Throwable object on the standard error output stream. The first line of output shows the same string which was returned by the toString() method for this object means Exception class name and later lines represent data previously recorded by the method fillInStackTrace(). Syntax: " }, { "code": null, "e": 603, "s": 573, "text": "public void printStackTrace()" }, { "code": null, "e": 747, "s": 603, "text": "Return Value: This method do not returns anything.Below programs illustrate the printStackTrace method of Java.lang.Throwable class:Example 1: " }, { "code": null, "e": 752, "s": 747, "text": "Java" }, { "code": "// Java program to demonstrate// the printStackTrace () Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // print stack trace e.printStackTrace(); } } // method which throws Exception public static void testException1() throws Exception { // create a ArrayIndexOutOfBoundsException Exception ArrayIndexOutOfBoundsException ae = new ArrayIndexOutOfBoundsException(); // create a new Exception Exception ioe = new Exception(); // initialize the cause and throw Exception ioe.initCause(ae); throw ioe; }}", "e": 1543, "s": 752, "text": null }, { "code": null, "e": 1740, "s": 1543, "text": "java.lang.Exception\n at GFG.testException1(File.java:36)\n at GFG.main(File.java:15)\nCaused by: java.lang.ArrayIndexOutOfBoundsException\n at GFG.testException1(File.java:32)\n ... 1 more" }, { "code": null, "e": 1754, "s": 1742, "text": "Example 2: " }, { "code": null, "e": 1759, "s": 1754, "text": "Java" }, { "code": "// Java program to demonstrate// the printStackTrace () Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // print stack trace e.printStackTrace(); } } // method which throws Exception public static void testException1() throws Exception { // create a ArrayIndexOutOfBoundsException Exception ArrayIndexOutOfBoundsException ae = new ArrayIndexOutOfBoundsException(); // create a new Exception Exception ioe = new Exception(); // initialize the cause and throw Exception ioe.initCause(ae); throw ioe; }}", "e": 2550, "s": 1759, "text": null }, { "code": null, "e": 2747, "s": 2550, "text": "java.lang.Exception\n at GFG.testException1(File.java:36)\n at GFG.main(File.java:15)\nCaused by: java.lang.ArrayIndexOutOfBoundsException\n at GFG.testException1(File.java:32)\n ... 1 more" }, { "code": null, "e": 3104, "s": 2749, "text": "The printStackTrace(PrintStream s) method of Java.lang.Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred to the specified print stream. This method works same as printStackTrace() but difference is only that it prints to specified print stream passed as parameter.Syntax: " }, { "code": null, "e": 3147, "s": 3104, "text": "public void printStackTrace(PrintStream s)" }, { "code": null, "e": 3445, "s": 3147, "text": "Parameters: This method accepts PrintStream s as a parameter which is specified print stream where we want to write this Throwable details.Return Value: This method do not returns anything.Below programs illustrate the printStackTrace(PrintStream s) method of Java.lang.Throwable class:Example 1: " }, { "code": null, "e": 3450, "s": 3445, "text": "Java" }, { "code": "// Java program to demonstrate// the printStackTrace(PrintStream s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // create a array of Integers int[] i = new int[2]; // try to add numbers to array i[2] = 3; } catch (Throwable e) { // print Stack Trace e.printStackTrace(System.out); } }}", "e": 3926, "s": 3450, "text": null }, { "code": null, "e": 4000, "s": 3926, "text": "java.lang.ArrayIndexOutOfBoundsException: 2\n at GFG.main(File.java:18)" }, { "code": null, "e": 4014, "s": 4002, "text": "Example 2: " }, { "code": null, "e": 4019, "s": 4014, "text": "Java" }, { "code": "// Java program to demonstrate// the printStackTrace(PrintStream s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // create printstream object PrintStream obj = new PrintStream(System.out); // print stack trace e.printStackTrace(obj); } } // method which throws Exception public static void testException1() throws Exception { throw new Exception(\"System is Down\"); }}", "e": 4667, "s": 4019, "text": null }, { "code": null, "e": 4773, "s": 4667, "text": "java.lang.Exception: System is Down\n at GFG.testException1(File.java:35)\n at GFG.main(File.java:15)" }, { "code": null, "e": 5130, "s": 4775, "text": "The printStackTrace(PrintWriter s) method of Java.lang.Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred to the specified print Writer. This method works same as printStackTrace() but difference is only that it prints to specified print Writer passed as parameter.Syntax: " }, { "code": null, "e": 5173, "s": 5130, "text": "public void printStackTrace(PrintWriter s)" }, { "code": null, "e": 5462, "s": 5173, "text": "Parameters: This method accepts PrintWriter s as a parameter which is specified print writer where this Throwable details are to be written.Return Value: This method do not returns anything.Below programs illustrate the printStackTrace(PrintWriter s) method of Throwable class:Example 1: " }, { "code": null, "e": 5467, "s": 5462, "text": "Java" }, { "code": "// Java program to demonstrate// the printStackTrace(PrintWriter s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // divide two numbers int a = 74, b = 0; int c = a / b; } catch (Throwable e) { // Using a StringWriter, // to convert trace into a String: StringWriter sw = new StringWriter(); // create a PrintWriter PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String error = sw.toString(); System.out.println(\"Error:\\n\" + error); } }}", "e": 6165, "s": 5467, "text": null }, { "code": null, "e": 6243, "s": 6165, "text": "Error:\njava.lang.ArithmeticException: / by zero\n at GFG.main(File.java:17)" }, { "code": null, "e": 6258, "s": 6245, "text": "Example 2: " }, { "code": null, "e": 6263, "s": 6258, "text": "Java" }, { "code": "// Java program to demonstrate// the printStackTrace(PrintWriter s) Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // Using a StringWriter, // to convert trace into a String: StringWriter sw = new StringWriter(); // create a PrintWriter PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String error = sw.toString(); System.out.println(\"Error:\\n\" + error); } } // method which throws Exception public static void testException1() throws Exception { throw new Exception( \"Waiting for input but no response\"); }}", "e": 7089, "s": 6263, "text": null }, { "code": null, "e": 7221, "s": 7089, "text": "Error:\njava.lang.Exception: Waiting for input but no response\n at GFG.testException1(File.java:38)\n at GFG.main(File.java:15)" }, { "code": null, "e": 7532, "s": 7223, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#printStackTrace() https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream) https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintWriter) " }, { "code": null, "e": 7544, "s": 7532, "text": "anikakapoor" }, { "code": null, "e": 7568, "s": 7544, "text": "Java-Exception Handling" }, { "code": null, "e": 7584, "s": 7568, "text": "Java-Exceptions" }, { "code": null, "e": 7599, "s": 7584, "text": "Java-Functions" }, { "code": null, "e": 7617, "s": 7599, "text": "Java-lang package" }, { "code": null, "e": 7632, "s": 7617, "text": "java-Throwable" }, { "code": null, "e": 7637, "s": 7632, "text": "Java" }, { "code": null, "e": 7642, "s": 7637, "text": "Java" }, { "code": null, "e": 7740, "s": 7642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7791, "s": 7740, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 7822, "s": 7791, "text": "How to iterate any Map in Java" }, { "code": null, "e": 7841, "s": 7822, "text": "Interfaces in Java" }, { "code": null, "e": 7871, "s": 7841, "text": "HashMap in Java with Examples" }, { "code": null, "e": 7886, "s": 7871, "text": "Stream In Java" }, { "code": null, "e": 7904, "s": 7886, "text": "ArrayList in Java" }, { "code": null, "e": 7924, "s": 7904, "text": "Collections in Java" }, { "code": null, "e": 7948, "s": 7924, "text": "Singleton Class in Java" }, { "code": null, "e": 7980, "s": 7948, "text": "Multidimensional Arrays in Java" } ]
How to convert a list to matrix in R?
If we have a list that contain vectors having even number of elements in total then we can create a matrix of those elements. example, if a list contain 8 vectors and the total number of elements in those 8 vectors is 100 or any other multiple of 2 then we can create a matrix of those elements. This can be done by using unlist function inside matrix function. Consider the below list x − > x<-list(1:25,26:50,51:75,76:100,101:125,126:150,151:175,176:200) > x [[1]] [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 [[2]] [1] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 [[3]] [1] 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 [[4]] [1] 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 [20] 95 96 97 98 99 100 [[5]] [1] 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 [20] 120 121 122 123 124 125 [[6]] [1] 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 [20] 145 146 147 148 149 150 [[7]] [1] 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 [20] 170 171 172 173 174 175 [[8]] [1] 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 [20] 195 196 197 198 199 200 > Matrix_x <- matrix(unlist(x), ncol = 10, byrow = TRUE) > Matrix_x [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 2 3 4 5 6 7 8 9 10 [2,] 11 12 13 14 15 16 17 18 19 20 [3,] 21 22 23 24 25 26 27 28 29 30 [4,] 31 32 33 34 35 36 37 38 39 40 [5,] 41 42 43 44 45 46 47 48 49 50 [6,] 51 52 53 54 55 56 57 58 59 60 [7,] 61 62 63 64 65 66 67 68 69 70 [8,] 71 72 73 74 75 76 77 78 79 80 [9,] 81 82 83 84 85 86 87 88 89 90 [10,] 91 92 93 94 95 96 97 98 99 100 [11,] 101 102 103 104 105 106 107 108 109 110 [12,] 111 112 113 114 115 116 117 118 119 120 [13,] 121 122 123 124 125 126 127 128 129 130 [14,] 131 132 133 134 135 136 137 138 139 140 [15,] 141 142 143 144 145 146 147 148 149 150 [16,] 151 152 153 154 155 156 157 158 159 160 [17,] 161 162 163 164 165 166 167 168 169 170 [18,] 171 172 173 174 175 176 177 178 179 180 [19,] 181 182 183 184 185 186 187 188 189 190 [20,] 191 192 193 194 195 196 197 198 199 200 > Matrix_x <- matrix(unlist(x), ncol = 10) > Matrix_x [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 21 41 61 81 101 121 141 161 181 [2,] 2 22 42 62 82 102 122 142 162 182 [3,] 3 23 43 63 83 103 123 143 163 183 [4,] 4 24 44 64 84 104 124 144 164 184 [5,] 5 25 45 65 85 105 125 145 165 185 [6,] 6 26 46 66 86 106 126 146 166 186 [7,] 7 27 47 67 87 107 127 147 167 187 [8,] 8 28 48 68 88 108 128 148 168 188 [9,] 9 29 49 69 89 109 129 149 169 189 [10,] 10 30 50 70 90 110 130 150 170 190 [11,] 11 31 51 71 91 111 131 151 171 191 [12,] 12 32 52 72 92 112 132 152 172 192 [13,] 13 33 53 73 93 113 133 153 173 193 [14,] 14 34 54 74 94 114 134 154 174 194 [15,] 15 35 55 75 95 115 135 155 175 195 [16,] 16 36 56 76 96 116 136 156 176 196 [17,] 17 37 57 77 97 117 137 157 177 197 [18,] 18 38 58 78 98 118 138 158 178 198 [19,] 19 39 59 79 99 119 139 159 179 199 [20,] 20 40 60 80 100 120 140 160 180 200
[ { "code": null, "e": 1549, "s": 1187, "text": "If we have a list that contain vectors having even number of elements in total then we can create a matrix of those elements. example, if a list contain 8 vectors and the total number of elements in those 8 vectors is 100 or any other multiple of 2 then we can create a matrix of those elements. This can be done by using unlist function inside matrix function." }, { "code": null, "e": 1577, "s": 1549, "text": "Consider the below list x −" }, { "code": null, "e": 4606, "s": 1577, "text": "> x<-list(1:25,26:50,51:75,76:100,101:125,126:150,151:175,176:200)\n> x\n[[1]]\n [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25\n\n[[2]]\n [1] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50\n\n[[3]]\n [1] 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75\n\n[[4]]\n [1] 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94\n [20] 95 96 97 98 99 100\n[[5]]\n [1] 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119\n[20] 120 121 122 123 124 125\n[[6]]\n [1] 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144\n[20] 145 146 147 148 149 150\n[[7]]\n [1] 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169\n[20] 170 171 172 173 174 175\n[[8]]\n [1] 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194\n[20] 195 196 197 198 199 200\n> Matrix_x <- matrix(unlist(x), ncol = 10, byrow = TRUE)\n> Matrix_x\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n [1,] 1 2 3 4 5 6 7 8 9 10\n [2,] 11 12 13 14 15 16 17 18 19 20\n [3,] 21 22 23 24 25 26 27 28 29 30\n [4,] 31 32 33 34 35 36 37 38 39 40\n [5,] 41 42 43 44 45 46 47 48 49 50\n [6,] 51 52 53 54 55 56 57 58 59 60\n [7,] 61 62 63 64 65 66 67 68 69 70\n [8,] 71 72 73 74 75 76 77 78 79 80\n [9,] 81 82 83 84 85 86 87 88 89 90\n[10,] 91 92 93 94 95 96 97 98 99 100\n[11,] 101 102 103 104 105 106 107 108 109 110\n[12,] 111 112 113 114 115 116 117 118 119 120\n[13,] 121 122 123 124 125 126 127 128 129 130\n[14,] 131 132 133 134 135 136 137 138 139 140\n[15,] 141 142 143 144 145 146 147 148 149 150\n[16,] 151 152 153 154 155 156 157 158 159 160\n[17,] 161 162 163 164 165 166 167 168 169 170\n[18,] 171 172 173 174 175 176 177 178 179 180\n[19,] 181 182 183 184 185 186 187 188 189 190\n[20,] 191 192 193 194 195 196 197 198 199 200\n> Matrix_x <- matrix(unlist(x), ncol = 10)\n> Matrix_x\n[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n [1,] 1 21 41 61 81 101 121 141 161 181\n [2,] 2 22 42 62 82 102 122 142 162 182\n [3,] 3 23 43 63 83 103 123 143 163 183\n [4,] 4 24 44 64 84 104 124 144 164 184\n [5,] 5 25 45 65 85 105 125 145 165 185\n [6,] 6 26 46 66 86 106 126 146 166 186\n [7,] 7 27 47 67 87 107 127 147 167 187\n [8,] 8 28 48 68 88 108 128 148 168 188\n [9,] 9 29 49 69 89 109 129 149 169 189\n[10,] 10 30 50 70 90 110 130 150 170 190\n[11,] 11 31 51 71 91 111 131 151 171 191\n[12,] 12 32 52 72 92 112 132 152 172 192\n[13,] 13 33 53 73 93 113 133 153 173 193\n[14,] 14 34 54 74 94 114 134 154 174 194\n[15,] 15 35 55 75 95 115 135 155 175 195\n[16,] 16 36 56 76 96 116 136 156 176 196\n[17,] 17 37 57 77 97 117 137 157 177 197\n[18,] 18 38 58 78 98 118 138 158 178 198\n[19,] 19 39 59 79 99 119 139 159 179 199\n[20,] 20 40 60 80 100 120 140 160 180 200" } ]
How to get Month and Date of JavaScript in two digit format ?
24 May, 2019 Given a date and the task is to get the Month and Date in 2 digit format. Use JavaScript methods to get the Month and Date in 2 digit format. JavaScript getDate() Method: This method returns the day of the month (from 1 to 31) for the defined date.Syntax:Date.getDate()Return value: It returns a number, from 1 to 31, representing the day of the month. Syntax: Date.getDate() Return value: It returns a number, from 1 to 31, representing the day of the month. JavaScript getMonth() Method: This method returns the month (from 0 to 11) for the defined date, based on to local time.Syntax:Date.getMonth()Return value: It returns a number, from 0 to 11, representing the month. Syntax: Date.getMonth() Return value: It returns a number, from 0 to 11, representing the month. JavaScript String slice() method: This method gets part of a string and returns the extracted parts in a new string. It uses the start and end parameters to define the part of the string to extract. First character starts from position 0, the second has position 1, and so on.Syntax:string.slice(start, end)Parameters:start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string.Return value: It returns a string, representing the extracted part of the string. Syntax: string.slice(start, end) Parameters: start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0 end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string. Return value: It returns a string, representing the extracted part of the string. Example 1: This example first get the Date and Month and then slicing properly to get them in 2 digit format by using getDate(), getMonth() and slice() method. <!DOCTYPE HTML> <html> <head> <title> How to get the Month and Date of JavaScript in 2 digit format </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; function gfg_Run() { var a = new Date(); var month = ("0" + (a.getMonth() + 1)).slice(-2); var date = ("0" + a.getDate()).slice(-2); el_down.innerHTML = "Date = " + date + ", Month = " + month; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example creates a function which adds zero to the Date if it is less than 10 and adds zeros appropriately for the Month also, by using getDate() and getMonth() method. <!DOCTYPE HTML> <html> <head> <title> How to get the Month and Date of JavaScript in 2 digit format </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; function formatDateToString(date) { var dd = (date.getDate() < 10 ? '0' : '') + date.getDate(); var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1); return "Date = " + dd + ", Month = " + MM; } function gfg_Run() { var a = new Date(); el_down.innerHTML = formatDateToString(a); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: javascript-date JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2019" }, { "code": null, "e": 170, "s": 28, "text": "Given a date and the task is to get the Month and Date in 2 digit format. Use JavaScript methods to get the Month and Date in 2 digit format." }, { "code": null, "e": 381, "s": 170, "text": "JavaScript getDate() Method: This method returns the day of the month (from 1 to 31) for the defined date.Syntax:Date.getDate()Return value: It returns a number, from 1 to 31, representing the day of the month." }, { "code": null, "e": 389, "s": 381, "text": "Syntax:" }, { "code": null, "e": 404, "s": 389, "text": "Date.getDate()" }, { "code": null, "e": 488, "s": 404, "text": "Return value: It returns a number, from 1 to 31, representing the day of the month." }, { "code": null, "e": 703, "s": 488, "text": "JavaScript getMonth() Method: This method returns the month (from 0 to 11) for the defined date, based on to local time.Syntax:Date.getMonth()Return value: It returns a number, from 0 to 11, representing the month." }, { "code": null, "e": 711, "s": 703, "text": "Syntax:" }, { "code": null, "e": 727, "s": 711, "text": "Date.getMonth()" }, { "code": null, "e": 800, "s": 727, "text": "Return value: It returns a number, from 0 to 11, representing the month." }, { "code": null, "e": 1524, "s": 800, "text": "JavaScript String slice() method: This method gets part of a string and returns the extracted parts in a new string. It uses the start and end parameters to define the part of the string to extract. First character starts from position 0, the second has position 1, and so on.Syntax:string.slice(start, end)Parameters:start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string.Return value: It returns a string, representing the extracted part of the string." }, { "code": null, "e": 1532, "s": 1524, "text": "Syntax:" }, { "code": null, "e": 1557, "s": 1532, "text": "string.slice(start, end)" }, { "code": null, "e": 1569, "s": 1557, "text": "Parameters:" }, { "code": null, "e": 1699, "s": 1569, "text": "start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0" }, { "code": null, "e": 1895, "s": 1699, "text": "end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string." }, { "code": null, "e": 1977, "s": 1895, "text": "Return value: It returns a string, representing the extracted part of the string." }, { "code": null, "e": 2137, "s": 1977, "text": "Example 1: This example first get the Date and Month and then slicing properly to get them in 2 digit format by using getDate(), getMonth() and slice() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to get the Month and Date of JavaScript in 2 digit format </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; function gfg_Run() { var a = new Date(); var month = (\"0\" + (a.getMonth() + 1)).slice(-2); var date = (\"0\" + a.getDate()).slice(-2); el_down.innerHTML = \"Date = \" + date + \", Month = \" + month; } </script> </body> </html> ", "e": 3321, "s": 2137, "text": null }, { "code": null, "e": 3329, "s": 3321, "text": "Output:" }, { "code": null, "e": 3360, "s": 3329, "text": "Before clicking on the button:" }, { "code": null, "e": 3390, "s": 3360, "text": "After clicking on the button:" }, { "code": null, "e": 3574, "s": 3390, "text": "Example 2: This example creates a function which adds zero to the Date if it is less than 10 and adds zeros appropriately for the Month also, by using getDate() and getMonth() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to get the Month and Date of JavaScript in 2 digit format </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; function formatDateToString(date) { var dd = (date.getDate() < 10 ? '0' : '') + date.getDate(); var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1); return \"Date = \" + dd + \", Month = \" + MM; } function gfg_Run() { var a = new Date(); el_down.innerHTML = formatDateToString(a); } </script> </body> </html> ", "e": 5011, "s": 3574, "text": null }, { "code": null, "e": 5019, "s": 5011, "text": "Output:" }, { "code": null, "e": 5050, "s": 5019, "text": "Before clicking on the button:" }, { "code": null, "e": 5080, "s": 5050, "text": "After clicking on the button:" }, { "code": null, "e": 5096, "s": 5080, "text": "javascript-date" }, { "code": null, "e": 5107, "s": 5096, "text": "JavaScript" }, { "code": null, "e": 5124, "s": 5107, "text": "Web Technologies" }, { "code": null, "e": 5151, "s": 5124, "text": "Web technologies Questions" } ]
Calculate sum of all numbers present in a string
04 Jul, 2022 Given a string containing alphanumeric characters, calculate sum of all numbers present in the string. Examples: Input: 1abc23 Output: 24 Input: geeks4geeks Output: 4 Input: 1abc2x30yz67 Output: 100 Input: 123abc Output: 123 Difficulty level: Rookie The only tricky part in this question is that multiple consecutive digits are considered as one number.The idea is very simple. We scan each character of the input string and if a number is formed by consecutive characters of the string, we increment the result by that amount. Below is the implementation of the above idea: C++ Java Python3 C# Javascript // C++ program to calculate sum of all numbers present// in a string containing alphanumeric characters#include <iostream>using namespace std; // Function to calculate sum of all numbers present// in a string containing alphanumeric charactersint findSum(string str){ // A temporary string string temp = ""; // holds sum of all numbers present in the string int sum = 0; // read each character in input string for (char ch : str) { // if current character is a digit if (isdigit(ch)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += atoi(temp.c_str()); // reset temporary string to empty temp = ""; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + atoi(temp.c_str());} // Driver codeint main(){ // input alphanumeric string string str = "12abc20yz68"; // Function call cout << findSum(str); return 0;} // Java program to calculate sum of all numbers present// in a string containing alphanumeric charactersclass GFG { // Function to calculate sum of all numbers present // in a string containing alphanumeric characters static int findSum(String str) { // A temporary string String temp = "0"; // holds sum of all numbers present in the string int sum = 0; // read each character in input string for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); // if current character is a digit if (Character.isDigit(ch)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += Integer.parseInt(temp); // reset temporary string to empty temp = "0"; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + Integer.parseInt(temp); } // Driver code public static void main(String[] args) { // input alphanumeric string String str = "12abc20yz68"; // Function call System.out.println(findSum(str)); }} // This code is contributed by AnkitRai01 # Python3 program to calculate sum of# all numbers present in a string# containing alphanumeric characters # Function to calculate sum of all# numbers present in a string# containing alphanumeric characters def findSum(str1): # A temporary string temp = "0" # holds sum of all numbers # present in the string Sum = 0 # read each character in input string for ch in str1: # if current character is a digit if (ch.isdigit()): temp += ch # if current character is an alphabet else: # increment Sum by number found # earlier(if any) Sum += int(temp) # reset temporary string to empty temp = "0" # atoi(temp.c_str1()) takes care # of trailing numbers return Sum + int(temp) # Driver code # input alphanumeric stringstr1 = "12abc20yz68" # Function callprint(findSum(str1)) # This code is contributed# by mohit kumar // C# program to calculate sum of// all numbers present in a string// containing alphanumeric charactersusing System; class GFG { // Function to calculate sum of // all numbers present in a string // containing alphanumeric characters static int findSum(String str) { // A temporary string String temp = "0"; // holds sum of all numbers // present in the string int sum = 0; // read each character in input string for (int i = 0; i < str.Length; i++) { char ch = str[i]; // if current character is a digit if (char.IsDigit(ch)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += int.Parse(temp); // reset temporary string to empty temp = "0"; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + int.Parse(temp); } // Driver code public static void Main(String[] args) { // input alphanumeric string String str = "12abc20yz68"; // Function call Console.WriteLine(findSum(str)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program to calculate// sum of all numbers present// in a string containing// alphanumeric characters // Function to calculate sum // of all numbers present // in a string containing // alphanumeric characters function findSum(str) { // A temporary string let temp = "0"; // holds sum of all numbers // present in the string let sum = 0; // read each character in input string for (let i = 0; i < str.length; i++) { let ch = str[i]; // if current character is a digit if (!isNaN(String(ch) * 1)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += parseInt(temp); // reset temporary string to empty temp = "0"; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + parseInt(temp); } // Driver code // input alphanumeric string let str = "12abc20yz68"; // Function call document.write(findSum(str)); // This code is contributed by unknown2108 </script> 100 Time complexity: O(n) where n is length of the string. Auxiliary Space: O(n) where n is length of the string. A Better Solution implementing Regex. Python3 # Python3 program to calculate sum of# all numbers present in a string# containing alphanumeric characters # Function to calculate sum of all# numbers present in a string# containing alphanumeric charactersimport re def find_sum(str1): # Regular Expression that matches # digits in between a string return sum(map(int, re.findall('\d+', str1))) # Driver code# input alphanumeric stringstr1 = "12abc20yz68" # Function callprint(find_sum(str1)) # This code is contributed# by Venkata Ramana B 100 Time complexity: O(n) where n is length of the string. Auxiliary Space: O(n) where n is length of the string. This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. mohit kumar 29 iskra nidhi_biet ankthon princiraj1992 shrey_shreyansh unknown2108 simmytarika5 anandkumarshivam2266 hardikkoriintern Amazon Linkedin MAQ Software SAP Labs Strings Amazon MAQ Software SAP Labs Linkedin Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++ Longest Common Subsequence | DP-4 Python program to check if a string is palindrome or not Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 155, "s": 52, "text": "Given a string containing alphanumeric characters, calculate sum of all numbers present in the string." }, { "code": null, "e": 166, "s": 155, "text": "Examples: " }, { "code": null, "e": 285, "s": 166, "text": "Input: 1abc23\nOutput: 24\n\nInput: geeks4geeks\nOutput: 4\n\nInput: 1abc2x30yz67\nOutput: 100\n\nInput: 123abc\nOutput: 123" }, { "code": null, "e": 310, "s": 285, "text": "Difficulty level: Rookie" }, { "code": null, "e": 589, "s": 310, "text": "The only tricky part in this question is that multiple consecutive digits are considered as one number.The idea is very simple. We scan each character of the input string and if a number is formed by consecutive characters of the string, we increment the result by that amount. " }, { "code": null, "e": 636, "s": 589, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 640, "s": 636, "text": "C++" }, { "code": null, "e": 645, "s": 640, "text": "Java" }, { "code": null, "e": 653, "s": 645, "text": "Python3" }, { "code": null, "e": 656, "s": 653, "text": "C#" }, { "code": null, "e": 667, "s": 656, "text": "Javascript" }, { "code": "// C++ program to calculate sum of all numbers present// in a string containing alphanumeric characters#include <iostream>using namespace std; // Function to calculate sum of all numbers present// in a string containing alphanumeric charactersint findSum(string str){ // A temporary string string temp = \"\"; // holds sum of all numbers present in the string int sum = 0; // read each character in input string for (char ch : str) { // if current character is a digit if (isdigit(ch)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += atoi(temp.c_str()); // reset temporary string to empty temp = \"\"; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + atoi(temp.c_str());} // Driver codeint main(){ // input alphanumeric string string str = \"12abc20yz68\"; // Function call cout << findSum(str); return 0;}", "e": 1715, "s": 667, "text": null }, { "code": "// Java program to calculate sum of all numbers present// in a string containing alphanumeric charactersclass GFG { // Function to calculate sum of all numbers present // in a string containing alphanumeric characters static int findSum(String str) { // A temporary string String temp = \"0\"; // holds sum of all numbers present in the string int sum = 0; // read each character in input string for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); // if current character is a digit if (Character.isDigit(ch)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += Integer.parseInt(temp); // reset temporary string to empty temp = \"0\"; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + Integer.parseInt(temp); } // Driver code public static void main(String[] args) { // input alphanumeric string String str = \"12abc20yz68\"; // Function call System.out.println(findSum(str)); }} // This code is contributed by AnkitRai01", "e": 3025, "s": 1715, "text": null }, { "code": "# Python3 program to calculate sum of# all numbers present in a string# containing alphanumeric characters # Function to calculate sum of all# numbers present in a string# containing alphanumeric characters def findSum(str1): # A temporary string temp = \"0\" # holds sum of all numbers # present in the string Sum = 0 # read each character in input string for ch in str1: # if current character is a digit if (ch.isdigit()): temp += ch # if current character is an alphabet else: # increment Sum by number found # earlier(if any) Sum += int(temp) # reset temporary string to empty temp = \"0\" # atoi(temp.c_str1()) takes care # of trailing numbers return Sum + int(temp) # Driver code # input alphanumeric stringstr1 = \"12abc20yz68\" # Function callprint(findSum(str1)) # This code is contributed# by mohit kumar", "e": 3969, "s": 3025, "text": null }, { "code": "// C# program to calculate sum of// all numbers present in a string// containing alphanumeric charactersusing System; class GFG { // Function to calculate sum of // all numbers present in a string // containing alphanumeric characters static int findSum(String str) { // A temporary string String temp = \"0\"; // holds sum of all numbers // present in the string int sum = 0; // read each character in input string for (int i = 0; i < str.Length; i++) { char ch = str[i]; // if current character is a digit if (char.IsDigit(ch)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += int.Parse(temp); // reset temporary string to empty temp = \"0\"; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + int.Parse(temp); } // Driver code public static void Main(String[] args) { // input alphanumeric string String str = \"12abc20yz68\"; // Function call Console.WriteLine(findSum(str)); }} // This code is contributed by PrinciRaj1992", "e": 5284, "s": 3969, "text": null }, { "code": "<script> // Javascript program to calculate// sum of all numbers present// in a string containing// alphanumeric characters // Function to calculate sum // of all numbers present // in a string containing // alphanumeric characters function findSum(str) { // A temporary string let temp = \"0\"; // holds sum of all numbers // present in the string let sum = 0; // read each character in input string for (let i = 0; i < str.length; i++) { let ch = str[i]; // if current character is a digit if (!isNaN(String(ch) * 1)) temp += ch; // if current character is an alphabet else { // increment sum by number found earlier // (if any) sum += parseInt(temp); // reset temporary string to empty temp = \"0\"; } } // atoi(temp.c_str()) takes care of trailing // numbers return sum + parseInt(temp); } // Driver code // input alphanumeric string let str = \"12abc20yz68\"; // Function call document.write(findSum(str)); // This code is contributed by unknown2108 </script>", "e": 6550, "s": 5284, "text": null }, { "code": null, "e": 6554, "s": 6550, "text": "100" }, { "code": null, "e": 6664, "s": 6554, "text": "Time complexity: O(n) where n is length of the string. Auxiliary Space: O(n) where n is length of the string." }, { "code": null, "e": 6702, "s": 6664, "text": "A Better Solution implementing Regex." }, { "code": null, "e": 6710, "s": 6702, "text": "Python3" }, { "code": "# Python3 program to calculate sum of# all numbers present in a string# containing alphanumeric characters # Function to calculate sum of all# numbers present in a string# containing alphanumeric charactersimport re def find_sum(str1): # Regular Expression that matches # digits in between a string return sum(map(int, re.findall('\\d+', str1))) # Driver code# input alphanumeric stringstr1 = \"12abc20yz68\" # Function callprint(find_sum(str1)) # This code is contributed# by Venkata Ramana B", "e": 7211, "s": 6710, "text": null }, { "code": null, "e": 7215, "s": 7211, "text": "100" }, { "code": null, "e": 7325, "s": 7215, "text": "Time complexity: O(n) where n is length of the string. Auxiliary Space: O(n) where n is length of the string." }, { "code": null, "e": 7621, "s": 7325, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 7636, "s": 7621, "text": "mohit kumar 29" }, { "code": null, "e": 7642, "s": 7636, "text": "iskra" }, { "code": null, "e": 7653, "s": 7642, "text": "nidhi_biet" }, { "code": null, "e": 7661, "s": 7653, "text": "ankthon" }, { "code": null, "e": 7675, "s": 7661, "text": "princiraj1992" }, { "code": null, "e": 7691, "s": 7675, "text": "shrey_shreyansh" }, { "code": null, "e": 7703, "s": 7691, "text": "unknown2108" }, { "code": null, "e": 7716, "s": 7703, "text": "simmytarika5" }, { "code": null, "e": 7737, "s": 7716, "text": "anandkumarshivam2266" }, { "code": null, "e": 7754, "s": 7737, "text": "hardikkoriintern" }, { "code": null, "e": 7761, "s": 7754, "text": "Amazon" }, { "code": null, "e": 7770, "s": 7761, "text": "Linkedin" }, { "code": null, "e": 7783, "s": 7770, "text": "MAQ Software" }, { "code": null, "e": 7792, "s": 7783, "text": "SAP Labs" }, { "code": null, "e": 7800, "s": 7792, "text": "Strings" }, { "code": null, "e": 7807, "s": 7800, "text": "Amazon" }, { "code": null, "e": 7820, "s": 7807, "text": "MAQ Software" }, { "code": null, "e": 7829, "s": 7820, "text": "SAP Labs" }, { "code": null, "e": 7838, "s": 7829, "text": "Linkedin" }, { "code": null, "e": 7846, "s": 7838, "text": "Strings" }, { "code": null, "e": 7944, "s": 7846, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7990, "s": 7944, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 8015, "s": 7990, "text": "Reverse a string in Java" }, { "code": null, "e": 8075, "s": 8015, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8090, "s": 8075, "text": "C++ Data Types" }, { "code": null, "e": 8165, "s": 8090, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 8210, "s": 8165, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 8244, "s": 8210, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 8301, "s": 8244, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 8362, "s": 8301, "text": "Length of the longest substring without repeating characters" } ]
Maven - Build Automation
Build Automation defines the scenario where dependent project(s) build process gets started once the project build is successfully completed, in order to ensure that dependent project(s) is/are stable. Example Consider a team is developing a project bus-core-api on which two other projects app-web-ui and app-desktop-ui are dependent. app-web-ui project is using 1.0-SNAPSHOT of bus-core-api project. <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>app-web-ui</groupId> <artifactId>app-web-ui</artifactId> <version>1.0</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>bus-core-api</groupId> <artifactId>bus-core-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project> app-desktop-ui project is using 1.0-SNAPSHOT of bus-core-api project. <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>app_desktop_ui</groupId> <artifactId>app_desktop_ui</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>app_desktop_ui</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>bus_core_api</groupId> <artifactId>bus_core_api</artifactId> <version>1.0-SNAPSHOT</version> <scope>system</scope> <systemPath>C:\MVN\bus_core_api\target\bus_core_api-1.0-SNAPSHOT.jar</systemPath> </dependency> </dependencies> </project> bus-core-api project − <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>bus_core_api</groupId> <artifactId>bus_core_api</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> </project> Now, teams of app-web-ui and app-desktop-ui projects require that their build process should kick off whenever bus-core-api project changes. Using snapshot, ensures that the latest bus-core-api project should be used but to meet the above requirement we need to do something extra. We can proceed with the following two ways − Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds. Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds. Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically. Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically. Update bus-core-api project pom.xml. <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>bus-core-api</groupId> <artifactId>bus-core-api</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <build> <plugins> <plugin> <artifactId>maven-invoker-plugin</artifactId> <version>1.6</version> <configuration> <debug>true</debug> <pomIncludes> <pomInclude>app-web-ui/pom.xml</pomInclude> <pomInclude>app-desktop-ui/pom.xml</pomInclude> </pomIncludes> </configuration> <executions> <execution> <id>build</id> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> <build> </project> Let's open the command console, go to the C:\ > MVN > bus-core-api directory and execute the following mvn command. >mvn clean package -U Maven will start building the project bus-core-api. [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------ [INFO] Building bus-core-api [INFO] task-segment: [clean, package] [INFO] ------------------------------------------------------------------ ... [INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: C:\MVN\bus-core-ui\target\ bus-core-ui-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------ Once bus-core-api build is successful, Maven will start building the app-web-ui project. [INFO] ------------------------------------------------------------------ [INFO] Building app-web-ui [INFO] task-segment: [package] [INFO] ------------------------------------------------------------------ ... [INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: C:\MVN\app-web-ui\target\ app-web-ui-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------ Once app-web-ui build is successful, Maven will start building the app-desktop-ui project. [INFO] ------------------------------------------------------------------ [INFO] Building app-desktop-ui [INFO] task-segment: [package] [INFO] ------------------------------------------------------------------ ... [INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: C:\MVN\app-desktop-ui\target\ app-desktop-ui-1.0-SNAPSHOT.jar [INFO] ------------------------------------------------------------------- [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------- Using a CI Server is more preferable to developers. It is not required to update the bus-core-api project, every time a new project (for example, app-mobile-ui) is added, as dependent project on bus-core-api project. Hudsion is a continuous integration tool written in java, which in a servlet container, such as, Apache tomcat and glassfish application server. Hudson automatically manages build automation using Maven dependency management. The following snapshot will define the role of Hudson tool. Hudson considers each project build as job. Once a project code is checked-in to SVN (or any Source Management Tool mapped to Hudson), Hudson starts its build job and once this job gets completed, it start other dependent jobs (other dependent projects) automatically. In the above example, when bus-core-ui source code is updated in SVN, Hudson starts its build. Once build is successful, Hudson looks for dependent projects automatically, and starts building app-web-ui and app-desktop-ui projects.
[ { "code": null, "e": 2396, "s": 2194, "text": "Build Automation defines the scenario where dependent project(s) build process gets started once the project build is successfully completed, in order to ensure that dependent project(s) is/are stable." }, { "code": null, "e": 2404, "s": 2396, "text": "Example" }, { "code": null, "e": 2530, "s": 2404, "text": "Consider a team is developing a project bus-core-api on which two other projects app-web-ui and app-desktop-ui are dependent." }, { "code": null, "e": 2596, "s": 2530, "text": "app-web-ui project is using 1.0-SNAPSHOT of bus-core-api project." }, { "code": null, "e": 3204, "s": 2596, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>app-web-ui</groupId>\n <artifactId>app-web-ui</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <dependencies>\n <dependency>\n <groupId>bus-core-api</groupId>\n <artifactId>bus-core-api</artifactId>\n <version>1.0-SNAPSHOT</version>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 3274, "s": 3204, "text": "app-desktop-ui project is using 1.0-SNAPSHOT of bus-core-api project." }, { "code": null, "e": 4359, "s": 3274, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>app_desktop_ui</groupId>\n <artifactId>app_desktop_ui</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <name>app_desktop_ui</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>bus_core_api</groupId>\n <artifactId>bus_core_api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <scope>system</scope>\n <systemPath>C:\\MVN\\bus_core_api\\target\\bus_core_api-1.0-SNAPSHOT.jar</systemPath>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 4382, "s": 4359, "text": "bus-core-api project −" }, { "code": null, "e": 4797, "s": 4382, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>bus_core_api</groupId>\n <artifactId>bus_core_api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging> \n</project>" }, { "code": null, "e": 4938, "s": 4797, "text": "Now, teams of app-web-ui and app-desktop-ui projects require that their build process should kick off whenever bus-core-api project changes." }, { "code": null, "e": 5079, "s": 4938, "text": "Using snapshot, ensures that the latest bus-core-api project should be used but to meet the above requirement we need to do something extra." }, { "code": null, "e": 5124, "s": 5079, "text": "We can proceed with the following two ways −" }, { "code": null, "e": 5216, "s": 5124, "text": "Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds." }, { "code": null, "e": 5308, "s": 5216, "text": "Add a post-build goal in bus-core-api pom to kick-off app-web-ui and app-desktop-ui builds." }, { "code": null, "e": 5403, "s": 5308, "text": "Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically." }, { "code": null, "e": 5498, "s": 5403, "text": "Use a Continuous Integration (CI) Server like Hudson to manage build automation automatically." }, { "code": null, "e": 5535, "s": 5498, "text": "Update bus-core-api project pom.xml." }, { "code": null, "e": 6588, "s": 5535, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>bus-core-api</groupId>\n <artifactId>bus-core-api</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging>\n <build>\n <plugins>\n <plugin>\n <artifactId>maven-invoker-plugin</artifactId>\n <version>1.6</version>\n <configuration>\n <debug>true</debug>\n <pomIncludes>\n <pomInclude>app-web-ui/pom.xml</pomInclude>\n <pomInclude>app-desktop-ui/pom.xml</pomInclude>\n </pomIncludes>\n </configuration>\n <executions>\n <execution>\n <id>build</id>\n <goals>\n <goal>run</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n <build>\n</project>" }, { "code": null, "e": 6704, "s": 6588, "text": "Let's open the command console, go to the C:\\ > MVN > bus-core-api directory and execute the following mvn command." }, { "code": null, "e": 6727, "s": 6704, "text": ">mvn clean package -U\n" }, { "code": null, "e": 6779, "s": 6727, "text": "Maven will start building the project bus-core-api." }, { "code": null, "e": 7322, "s": 6779, "text": "[INFO] Scanning for projects...\n[INFO] ------------------------------------------------------------------\n[INFO] Building bus-core-api\n[INFO] task-segment: [clean, package]\n[INFO] ------------------------------------------------------------------\n...\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\bus-core-ui\\target\\\nbus-core-ui-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] ------------------------------------------------------------------\n" }, { "code": null, "e": 7411, "s": 7322, "text": "Once bus-core-api build is successful, Maven will start building the app-web-ui project." }, { "code": null, "e": 7911, "s": 7411, "text": "[INFO] ------------------------------------------------------------------\n[INFO] Building app-web-ui\n[INFO] task-segment: [package]\n[INFO] ------------------------------------------------------------------\n...\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\app-web-ui\\target\\\napp-web-ui-1.0-SNAPSHOT.jar\n[INFO] ------------------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] ------------------------------------------------------------------\n" }, { "code": null, "e": 8002, "s": 7911, "text": "Once app-web-ui build is successful, Maven will start building the app-desktop-ui project." }, { "code": null, "e": 8516, "s": 8002, "text": "[INFO] ------------------------------------------------------------------\n[INFO] Building app-desktop-ui\n[INFO] task-segment: [package]\n[INFO] ------------------------------------------------------------------\n...\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: C:\\MVN\\app-desktop-ui\\target\\\napp-desktop-ui-1.0-SNAPSHOT.jar\n[INFO] -------------------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] -------------------------------------------------------------------\n" }, { "code": null, "e": 9019, "s": 8516, "text": "Using a CI Server is more preferable to developers. It is not required to update the bus-core-api project, every time a new project (for example, app-mobile-ui) is added, as dependent project on bus-core-api project. Hudsion is a continuous integration tool written in java, which in a servlet container, such as, Apache tomcat and glassfish application server. Hudson automatically manages build automation using Maven dependency management. The following snapshot will define the role of Hudson tool." }, { "code": null, "e": 9288, "s": 9019, "text": "Hudson considers each project build as job. Once a project code is checked-in to SVN (or any Source Management Tool mapped to Hudson), Hudson starts its build job and once this job gets completed, it start other dependent jobs (other dependent projects) automatically." } ]
Oracle : ERP Software
07 Apr, 2021 An ERP system are the software tools that are used to manage Enterprise Data. ERP System helps various organizations to deal with supply chain, receiving, inventory management, production planning, finance/accounting, Human Resource Management and other business function. Oracle ERP :Oracle Corporation was founded in the year of 1977, and it is the world’s largest software company and leading supplier for Enterprise Information Management. This is the first software company which implement internet computing model for using Enterprise software across entire product line. It also provides database and relational services, application development tools and Enterprise Business Application. History : Oracle was founded in 1977 by Larry Ellison, Bob Miner and Ed Oates under the name of Software Development Laboratories. Initially they created Database by inspiring from IBM later on they started other services like providing Enterprise Software. In 1995, they change their name to Oracle Corporation. Oracle corporation owned various ERP Companies like PeopleSoft, JD Edward, Ban ERP etc. In 2012 Oracle shifted their ERP Software Solutions into Cloud basis. Now Oracle provide cloud based ERP Software. Oracle cloud based technology of providing ERP System had come in India in 2017. Technology and Product : Oracle Software runs on network computers, work station etc. Oracle 8i is the leading database used for internet Enterprise Computing. Oracle consist of 45 plus software Modules which is divided into following modules: Oracle Financials –This module includes Account Payable, Account Receivable, Cash Management, Fixed Assets etc. Oracle Human Resource –The module of Oracle records basic demographic and address data, selection, training and development, capabilities and skills management, compensation planning records and other related activities. Distribution Module –This module includes sales management, purchase management, and warehouse management etc.Tools and Utilities : This includes server platform, database, Programming Language. Oracle Projects : This module includes –Project budget, project definition, project cost estimation, project planning etc. Oracle Manufacturing –This module consist of Cost price calculation, billing, Material Requirement planning etc. Oracle Supply Chain –This module deals with the supply of products to the consumer’s and various other components related to Supply Management. Oracle Warehouse Technology Initiative is one of the fastest comprehensive program in data warehousing industry which provide Customers a complete data warehousing solution. Oracle Software Engineering Oracle Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Software Engineering | Black box testing Unit Testing | Software Testing System Testing Software Engineering | Integration Testing Difference Between Edge Computing and Fog Computing What is DFD(Data Flow Diagram)? Software Engineering | Calculation of Function Point (FP) Software Development Life Cycle (SDLC) Software Processes in Software Engineering Software Engineering | Testing Guidelines
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 301, "s": 28, "text": "An ERP system are the software tools that are used to manage Enterprise Data. ERP System helps various organizations to deal with supply chain, receiving, inventory management, production planning, finance/accounting, Human Resource Management and other business function." }, { "code": null, "e": 606, "s": 301, "text": "Oracle ERP :Oracle Corporation was founded in the year of 1977, and it is the world’s largest software company and leading supplier for Enterprise Information Management. This is the first software company which implement internet computing model for using Enterprise software across entire product line." }, { "code": null, "e": 724, "s": 606, "text": "It also provides database and relational services, application development tools and Enterprise Business Application." }, { "code": null, "e": 734, "s": 724, "text": "History :" }, { "code": null, "e": 982, "s": 734, "text": "Oracle was founded in 1977 by Larry Ellison, Bob Miner and Ed Oates under the name of Software Development Laboratories. Initially they created Database by inspiring from IBM later on they started other services like providing Enterprise Software." }, { "code": null, "e": 1125, "s": 982, "text": "In 1995, they change their name to Oracle Corporation. Oracle corporation owned various ERP Companies like PeopleSoft, JD Edward, Ban ERP etc." }, { "code": null, "e": 1321, "s": 1125, "text": "In 2012 Oracle shifted their ERP Software Solutions into Cloud basis. Now Oracle provide cloud based ERP Software. Oracle cloud based technology of providing ERP System had come in India in 2017." }, { "code": null, "e": 1346, "s": 1321, "text": "Technology and Product :" }, { "code": null, "e": 1407, "s": 1346, "text": "Oracle Software runs on network computers, work station etc." }, { "code": null, "e": 1481, "s": 1407, "text": "Oracle 8i is the leading database used for internet Enterprise Computing." }, { "code": null, "e": 1565, "s": 1481, "text": "Oracle consist of 45 plus software Modules which is divided into following modules:" }, { "code": null, "e": 1678, "s": 1565, "text": "Oracle Financials –This module includes Account Payable, Account Receivable, Cash Management, Fixed Assets etc. " }, { "code": null, "e": 1900, "s": 1678, "text": "Oracle Human Resource –The module of Oracle records basic demographic and address data, selection, training and development, capabilities and skills management, compensation planning records and other related activities. " }, { "code": null, "e": 2096, "s": 1900, "text": "Distribution Module –This module includes sales management, purchase management, and warehouse management etc.Tools and Utilities : This includes server platform, database, Programming Language. " }, { "code": null, "e": 2220, "s": 2096, "text": "Oracle Projects : This module includes –Project budget, project definition, project cost estimation, project planning etc. " }, { "code": null, "e": 2334, "s": 2220, "text": "Oracle Manufacturing –This module consist of Cost price calculation, billing, Material Requirement planning etc. " }, { "code": null, "e": 2478, "s": 2334, "text": "Oracle Supply Chain –This module deals with the supply of products to the consumer’s and various other components related to Supply Management." }, { "code": null, "e": 2652, "s": 2478, "text": "Oracle Warehouse Technology Initiative is one of the fastest comprehensive program in data warehousing industry which provide Customers a complete data warehousing solution." }, { "code": null, "e": 2659, "s": 2652, "text": "Oracle" }, { "code": null, "e": 2680, "s": 2659, "text": "Software Engineering" }, { "code": null, "e": 2687, "s": 2680, "text": "Oracle" }, { "code": null, "e": 2785, "s": 2687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2826, "s": 2785, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 2858, "s": 2826, "text": "Unit Testing | Software Testing" }, { "code": null, "e": 2873, "s": 2858, "text": "System Testing" }, { "code": null, "e": 2916, "s": 2873, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 2968, "s": 2916, "text": "Difference Between Edge Computing and Fog Computing" }, { "code": null, "e": 3000, "s": 2968, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 3058, "s": 3000, "text": "Software Engineering | Calculation of Function Point (FP)" }, { "code": null, "e": 3097, "s": 3058, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 3140, "s": 3097, "text": "Software Processes in Software Engineering" } ]
Python | Pandas Series.str.find()
23 Jun, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas str.find() method is used to search a substring in each string present in a series. If the string is found, it returns the lowest index of its occurrence. If string is not found, it will return -1. Start and end points can also be passed to search a specific part of string for the passed character or substring. Syntax: Series.str.find(sub, start=0, end=None)Parameters: sub: String or character to be searched in the text value in series start: int value, start point of searching. Default is 0 which means from the beginning of string end: int value, end point where the search needs to be stopped. Default is None.Return type: Series with index position of substring occurrence To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1: Finding single characterIn this example, a single character ‘a’ is searched in each string of Name column using str.find() method. Start and end parameters are kept default. The returned series is stored in a new column so that the indexes can be compared by looking directly. Before applying this method, null rows are dropped using .dropna() to avoid errors. Python3 # importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # substring to be searchedsub ='a' # creating and passing series to new columndata["Indexes"]= data["Name"].str.find(sub) # displaydata Output: As shown in the output image, the occurrence of index in the Indexes column is equal to the position first occurrence of character in the string. If the substring doesn’t exist in the text, -1 is returned. It can also be seen by looking at the first row itself that ‘A’ wasn’t considered which proves this method is case sensitive. Example #2: Searching substring (More than one character)In this example, ‘er’ substring will be searched in the Name column of data frame. The start parameter is kept 2 to start search from 3rd(index position 2) element. Python3 # importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # substring to be searchedsub ='er' # start varstart = 2 # creating and passing series to new columndata["Indexes"]= data["Name"].str.find(sub, start) # displaydata Output: As shown in the output image, the lest index of occurrence of substring is returned. But it can be seen, in case of Terry Rozier(Row 9 in data frame), instead of first occurrence of ‘er’, 10 was returned. This is because the start parameter was kept 2 and the first ‘er’ occurs before that. ruhelaa48 Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2021" }, { "code": null, "e": 562, "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.Pandas str.find() method is used to search a substring in each string present in a series. If the string is found, it returns the lowest index of its occurrence. If string is not found, it will return -1. Start and end points can also be passed to search a specific part of string for the passed character or substring. " }, { "code": null, "e": 933, "s": 562, "text": "Syntax: Series.str.find(sub, start=0, end=None)Parameters: sub: String or character to be searched in the text value in series start: int value, start point of searching. Default is 0 which means from the beginning of string end: int value, end point where the search needs to be stopped. Default is None.Return type: Series with index position of substring occurrence " }, { "code": null, "e": 1127, "s": 933, "text": "To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. " }, { "code": null, "e": 1503, "s": 1127, "text": " Example #1: Finding single characterIn this example, a single character ‘a’ is searched in each string of Name column using str.find() method. Start and end parameters are kept default. The returned series is stored in a new column so that the indexes can be compared by looking directly. Before applying this method, null rows are dropped using .dropna() to avoid errors. " }, { "code": null, "e": 1511, "s": 1503, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # substring to be searchedsub ='a' # creating and passing series to new columndata[\"Indexes\"]= data[\"Name\"].str.find(sub) # displaydata", "e": 1874, "s": 1511, "text": null }, { "code": null, "e": 2216, "s": 1874, "text": "Output: As shown in the output image, the occurrence of index in the Indexes column is equal to the position first occurrence of character in the string. If the substring doesn’t exist in the text, -1 is returned. It can also be seen by looking at the first row itself that ‘A’ wasn’t considered which proves this method is case sensitive. " }, { "code": null, "e": 2441, "s": 2216, "text": " Example #2: Searching substring (More than one character)In this example, ‘er’ substring will be searched in the Name column of data frame. The start parameter is kept 2 to start search from 3rd(index position 2) element. " }, { "code": null, "e": 2449, "s": 2441, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # reading csv file from urldata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # substring to be searchedsub ='er' # start varstart = 2 # creating and passing series to new columndata[\"Indexes\"]= data[\"Name\"].str.find(sub, start) # displaydata", "e": 2842, "s": 2449, "text": null }, { "code": null, "e": 3143, "s": 2842, "text": "Output: As shown in the output image, the lest index of occurrence of substring is returned. But it can be seen, in case of Terry Rozier(Row 9 in data frame), instead of first occurrence of ‘er’, 10 was returned. This is because the start parameter was kept 2 and the first ‘er’ occurs before that. " }, { "code": null, "e": 3155, "s": 3145, "text": "ruhelaa48" }, { "code": null, "e": 3176, "s": 3155, "text": "Python pandas-series" }, { "code": null, "e": 3205, "s": 3176, "text": "Python pandas-series-methods" }, { "code": null, "e": 3219, "s": 3205, "text": "Python-pandas" }, { "code": null, "e": 3226, "s": 3219, "text": "Python" }, { "code": null, "e": 3324, "s": 3226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3366, "s": 3324, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3388, "s": 3366, "text": "Enumerate() in Python" }, { "code": null, "e": 3420, "s": 3388, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3449, "s": 3420, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3476, "s": 3449, "text": "Python Classes and Objects" }, { "code": null, "e": 3512, "s": 3476, "text": "Convert integer to string in Python" }, { "code": null, "e": 3533, "s": 3512, "text": "Python OOPs Concepts" }, { "code": null, "e": 3564, "s": 3533, "text": "Python | os.path.join() method" }, { "code": null, "e": 3620, "s": 3564, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
PHP – Mysql Joins
31 Mar, 2021 In this article, we are going to join two tables using PHP and display them on the web page. Introduction : PHP is a server-side scripting language, which is used to connect with databases. Using this, we can get data from the database using PHP scripts. The database language that can be used to communicate with PHP is MySQL. MySQL is a database query language that is used to manage databases. Requirements : Xampp server – xampp server is used to store our database locally. We are going to access the data from xampp server using PHP. In this article, we are taking the student details database that contains two tables. They are student_address and student_marks. Structure of tables : table1=student_address table2=student_marks. We are going to perform INNER JOIN, LEFT JOIN, RIGHT JOIN on these two tables. 1. INNER JOIN : The INNER JOIN is a keyword that selects records that have matching values in both tables. Syntax : SELECT column 1,column 2,...column n FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name; Example : Let student_address contains these details And student_marks table includes By using sid, we can join these two tables using an Inner join, since, sid is common in two tables. Query to display student_address details based on inner join – SELECT * from student_address INNER JOIN student_marks on student_address.sid=student_marks.sid; Result : STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu STUDENT-ID : 2 ----- NAME : bobby ----- ADDRESS : kakumanu STUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad STUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad Query to display student_marks details based on inner join. SELECT * from student_marks INNER JOIN student_address on student_address.sid=student_marks.sid Result : STUDENT-ID : 1 ----- SUBJECT 1 : 98 ----- SUBJECT 2 : 99 STUDENT-ID : 2 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 89 STUDENT-ID : 3 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 98 STUDENT-ID : 4 ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 98 2. LEFT JOIN : The LEFT JOIN keyword is used to return all records from the left table (table1), and the matching records from the right table (table2). Syntax : SELECT column1,column2,...columnn FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name; Query to display all student_address table based on student id using left join SELECT * from student_address LEFT JOIN student_marks on student_address.sid=student_marks.sid Result : STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu STUDENT-ID : 2 ----- NAME : bobby ----- ADDRESS : kakumanu STUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad STUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad STUDENT-ID : ----- NAME : gnanesh ----- ADDRESS : hyderabad Query to display all student_marks table based on student id using left join SELECT * from student_marks LEFT JOIN student_address on student_address.sid=student_marks.sid Result : STUDENT-ID : 1 ----- SUBJECT 1 : 98 ----- SUBJECT 2 : 99 STUDENT-ID : 2 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 89 STUDENT-ID : 3 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 98 STUDENT-ID : 4 ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 98 STUDENT-ID : ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 79 3. RIGHT JOIN : The RIGHT JOIN keyword is used to return all records from the right table (table2), and the matching records from the left table (table1). Syntax : SELECT column1,column2,...columnn FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name; Query to display all student_address table based on student id using right join SELECT * from student_address RIGHT JOIN student_marks on student_address.sid=student_marks.sid Result : STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu STUDENT-ID : 2 ----- NAME : bobby ----- ADDRESS : kakumanu STUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad STUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad STUDENT-ID : 7 ----- NAME : ----- ADDRESS : Query to display all student_marks table based on student id using right join SELECT * from student_marks RIGHT JOIN student_address on student_address.sid=student_marks.sid Result : STUDENT-ID : 1 ----- SUBJECT 1 : 98 ----- SUBJECT 2 : 99 STUDENT-ID : 2 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 89 STUDENT-ID : 3 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 98 STUDENT-ID : 4 ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 98 STUDENT-ID : 5 ----- SUBJECT 1 : ----- SUBJECT 2 : Approach : Create a database named database and create tables(student_address and student_marks) Insert records into two tables using PHP Write SQL query to perform all joins using PHP Observe the results. Steps: Start xampp server Type “localhost/phpmyadmin” in your browser and create a database named “database” then create two tables named student_address and student_marks Student_address table structure : Student_marks table structure : Insert the records into the student_address table using PHP (data1.php) Run code by typing “localhost/data1.php” PHP <?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}//insert records into table$sql = "INSERT INTO student_address VALUES (1,'sravan kumar','kakumanu');";$sql .= "INSERT INTO student_address VALUES (2,'bobby','kakumanu');";$sql .= "INSERT INTO student_address VALUES (3,'ojaswi','hyderabad');";$sql .= "INSERT INTO student_address VALUES (4,'rohith','hyderabad');";$sql .= "INSERT INTO student_address VALUES (5,'gnanesh','hyderabad');"; if ($conn->multi_query($sql) === TRUE) { echo "data stored successfully";} else { echo "Error: " . $sql . "<br>" . $conn->error;} $conn->close();?> Output : Write PHP code to insert details in the student_marks table. (data2.PHP) PHP <?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}//insert records into table$sql = "INSERT INTO student_marks VALUES (1,98,99);";$sql .= "INSERT INTO student_marks VALUES (2,78,89);";$sql .= "INSERT INTO student_marks VALUES (3,78,98);";$sql .= "INSERT INTO student_marks VALUES (4,89,98);";$sql .= "INSERT INTO student_marks VALUES (7,89,79);"; if ($conn->multi_query($sql) === TRUE) { echo "data stored successfully";} else { echo "Error: " . $sql . "<br>" . $conn->error;} $conn->close();?> Output : Type “localhost/data2.php” to see the output Write PHP code to perform inner join (form.php) PHP <html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "inner join on student_address: ";echo "<br>";echo "<br>";//sql query to display all student_address table based on student id using inner join$sql = "SELECT * from student_address INNER JOIN student_marks on student_address.sid=student_marks.sid";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } echo "<br>";echo "inner join on student_marks: ";echo "<br>";echo "<br>";//sql query to display all student_marks table based on student id using inner join$sql1 = "SELECT * from student_marks INNER JOIN student_address on student_address.sid=student_marks.sid";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo " STUDENT-ID : ". $row['sid'], " ----- SUBJECT 1 : ". $row['subject1'] ," ----- SUBJECT 2 : ". $row['subject2'] ; echo "<br>"; } //close the connection $conn->close();?></body></html> Output : Type “localhost/form.php” in your browser. Write code to perform right join (form1.php) PHP <html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "right join on student_address: ";echo "<br>";echo "<br>";//sql query to display all student_address table based on student id using right join$sql = "SELECT * from student_address RIGHT JOIN student_marks on student_address.sid=student_marks.sid";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } echo "<br>";echo "right join on student_marks: ";echo "<br>";echo "<br>";//sql query to display all student_marks table based on student id using right join$sql1 = "SELECT * from student_marks RIGHT JOIN student_address on student_address.sid=student_marks.sid";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo " STUDENT-ID : ". $row['sid'], " ----- SUBJECT 1 : ". $row['subject1'] ," ----- SUBJECT 2 : ". $row['subject2'] ; echo "<br>"; } //close the connection $conn->close();?></body></html> Output : Type “localhost/form1.php” in your browser. Write PHP code to perform left join (form2.php) PHP <html><body><?php//servername$servername = "localhost";//username$username = "root";//empty password$password = "";//database is the database name$dbname = "database"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo "left join on student_address: ";echo "<br>";echo "<br>";//sql query to display all student_address table based on student id using left join$sql = "SELECT * from student_address LEFT JOIN student_marks on student_address.sid=student_marks.sid";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo " STUDENT-ID : ". $row['sid'], " ----- NAME : ". $row['sname'] ," ----- ADDRESS : ". $row['saddress'] ; echo "<br>"; } echo "<br>";echo "left join on student_marks: ";echo "<br>";echo "<br>";//sql query to display all student_marks table based on student id using left join$sql1 = "SELECT * from student_marks LEFT JOIN student_address on student_address.sid=student_marks.sid";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo " STUDENT-ID : ". $row['sid'], " ----- SUBJECT 1 : ". $row['subject1'] ," ----- SUBJECT 2 : ". $row['subject2'] ; echo "<br>"; } //close the connection $conn->close();?></body></html> Output : type localhost/form2.php in browser PHP SQL SQL PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator SQL | DDL, DQL, DML, DCL and TCL Commands SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause How to find Nth highest salary from a table CTE in SQL
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Mar, 2021" }, { "code": null, "e": 146, "s": 52, "text": "In this article, we are going to join two tables using PHP and display them on the web page. " }, { "code": null, "e": 161, "s": 146, "text": "Introduction :" }, { "code": null, "e": 450, "s": 161, "text": "PHP is a server-side scripting language, which is used to connect with databases. Using this, we can get data from the database using PHP scripts. The database language that can be used to communicate with PHP is MySQL. MySQL is a database query language that is used to manage databases." }, { "code": null, "e": 465, "s": 450, "text": "Requirements :" }, { "code": null, "e": 594, "s": 465, "text": "Xampp server – xampp server is used to store our database locally. We are going to access the data from xampp server using PHP." }, { "code": null, "e": 724, "s": 594, "text": "In this article, we are taking the student details database that contains two tables. They are student_address and student_marks." }, { "code": null, "e": 746, "s": 724, "text": "Structure of tables :" }, { "code": null, "e": 769, "s": 746, "text": "table1=student_address" }, { "code": null, "e": 791, "s": 769, "text": "table2=student_marks." }, { "code": null, "e": 870, "s": 791, "text": "We are going to perform INNER JOIN, LEFT JOIN, RIGHT JOIN on these two tables." }, { "code": null, "e": 886, "s": 870, "text": "1. INNER JOIN :" }, { "code": null, "e": 977, "s": 886, "text": "The INNER JOIN is a keyword that selects records that have matching values in both tables." }, { "code": null, "e": 986, "s": 977, "text": "Syntax :" }, { "code": null, "e": 1097, "s": 986, "text": "SELECT column 1,column 2,...column n\nFROM table1\nINNER JOIN table2\nON table1.column_name = table2.column_name;" }, { "code": null, "e": 1107, "s": 1097, "text": "Example :" }, { "code": null, "e": 1150, "s": 1107, "text": "Let student_address contains these details" }, { "code": null, "e": 1183, "s": 1150, "text": "And student_marks table includes" }, { "code": null, "e": 1283, "s": 1183, "text": "By using sid, we can join these two tables using an Inner join, since, sid is common in two tables." }, { "code": null, "e": 1346, "s": 1283, "text": "Query to display student_address details based on inner join –" }, { "code": null, "e": 1444, "s": 1346, "text": "SELECT * from student_address INNER JOIN student_marks on student_address.sid=student_marks.sid;" }, { "code": null, "e": 1453, "s": 1444, "text": "Result :" }, { "code": null, "e": 1700, "s": 1453, "text": "STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu\nSTUDENT-ID : 2 ----- NAME : bobby ----- ADDRESS : kakumanu\nSTUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad\nSTUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad" }, { "code": null, "e": 1760, "s": 1700, "text": "Query to display student_marks details based on inner join." }, { "code": null, "e": 1857, "s": 1760, "text": "SELECT * from student_marks INNER JOIN student_address on student_address.sid=student_marks.sid" }, { "code": null, "e": 1866, "s": 1857, "text": "Result :" }, { "code": null, "e": 2094, "s": 1866, "text": "STUDENT-ID : 1 ----- SUBJECT 1 : 98 ----- SUBJECT 2 : 99\nSTUDENT-ID : 2 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 89\nSTUDENT-ID : 3 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 98\nSTUDENT-ID : 4 ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 98" }, { "code": null, "e": 2109, "s": 2094, "text": "2. LEFT JOIN :" }, { "code": null, "e": 2247, "s": 2109, "text": "The LEFT JOIN keyword is used to return all records from the left table (table1), and the matching records from the right table (table2)." }, { "code": null, "e": 2256, "s": 2247, "text": "Syntax :" }, { "code": null, "e": 2363, "s": 2256, "text": "SELECT column1,column2,...columnn\nFROM table1\nLEFT JOIN table2\nON table1.column_name = table2.column_name;" }, { "code": null, "e": 2443, "s": 2363, "text": "Query to display all student_address table based on student id using left join" }, { "code": null, "e": 2538, "s": 2443, "text": "SELECT * from student_address LEFT JOIN student_marks on student_address.sid=student_marks.sid" }, { "code": null, "e": 2547, "s": 2538, "text": "Result :" }, { "code": null, "e": 2854, "s": 2547, "text": "STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu\nSTUDENT-ID : 2 ----- NAME : bobby ----- ADDRESS : kakumanu\nSTUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad\nSTUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad\nSTUDENT-ID : ----- NAME : gnanesh ----- ADDRESS : hyderabad" }, { "code": null, "e": 2932, "s": 2854, "text": "Query to display all student_marks table based on student id using left join" }, { "code": null, "e": 3027, "s": 2932, "text": "SELECT * from student_marks LEFT JOIN student_address on student_address.sid=student_marks.sid" }, { "code": null, "e": 3036, "s": 3027, "text": "Result :" }, { "code": null, "e": 3319, "s": 3036, "text": "STUDENT-ID : 1 ----- SUBJECT 1 : 98 ----- SUBJECT 2 : 99\nSTUDENT-ID : 2 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 89\nSTUDENT-ID : 3 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 98\nSTUDENT-ID : 4 ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 98\nSTUDENT-ID : ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 79" }, { "code": null, "e": 3335, "s": 3319, "text": "3. RIGHT JOIN :" }, { "code": null, "e": 3475, "s": 3335, "text": "The RIGHT JOIN keyword is used to return all records from the right table (table2), and the matching records from the left table (table1). " }, { "code": null, "e": 3484, "s": 3475, "text": "Syntax :" }, { "code": null, "e": 3593, "s": 3484, "text": "SELECT column1,column2,...columnn\nFROM table1\nRIGHT JOIN table2\nON table1.column_name = table2.column_name;" }, { "code": null, "e": 3674, "s": 3593, "text": "Query to display all student_address table based on student id using right join" }, { "code": null, "e": 3770, "s": 3674, "text": "SELECT * from student_address RIGHT JOIN student_marks on student_address.sid=student_marks.sid" }, { "code": null, "e": 3779, "s": 3770, "text": "Result :" }, { "code": null, "e": 4070, "s": 3779, "text": "STUDENT-ID : 1 ----- NAME : sravan kumar ----- ADDRESS : kakumanu\nSTUDENT-ID : 2 ----- NAME : bobby ----- ADDRESS : kakumanu\nSTUDENT-ID : 3 ----- NAME : ojaswi ----- ADDRESS : hyderabad\nSTUDENT-ID : 4 ----- NAME : rohith ----- ADDRESS : hyderabad\nSTUDENT-ID : 7 ----- NAME : ----- ADDRESS :" }, { "code": null, "e": 4149, "s": 4070, "text": "Query to display all student_marks table based on student id using right join" }, { "code": null, "e": 4245, "s": 4149, "text": "SELECT * from student_marks RIGHT JOIN student_address on student_address.sid=student_marks.sid" }, { "code": null, "e": 4254, "s": 4245, "text": "Result :" }, { "code": null, "e": 4533, "s": 4254, "text": "STUDENT-ID : 1 ----- SUBJECT 1 : 98 ----- SUBJECT 2 : 99\nSTUDENT-ID : 2 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 89\nSTUDENT-ID : 3 ----- SUBJECT 1 : 78 ----- SUBJECT 2 : 98\nSTUDENT-ID : 4 ----- SUBJECT 1 : 89 ----- SUBJECT 2 : 98\nSTUDENT-ID : 5 ----- SUBJECT 1 : ----- SUBJECT 2 :" }, { "code": null, "e": 4544, "s": 4533, "text": "Approach :" }, { "code": null, "e": 4630, "s": 4544, "text": "Create a database named database and create tables(student_address and student_marks)" }, { "code": null, "e": 4671, "s": 4630, "text": "Insert records into two tables using PHP" }, { "code": null, "e": 4719, "s": 4671, "text": "Write SQL query to perform all joins using PHP" }, { "code": null, "e": 4740, "s": 4719, "text": "Observe the results." }, { "code": null, "e": 4747, "s": 4740, "text": "Steps:" }, { "code": null, "e": 4766, "s": 4747, "text": "Start xampp server" }, { "code": null, "e": 4912, "s": 4766, "text": "Type “localhost/phpmyadmin” in your browser and create a database named “database” then create two tables named student_address and student_marks" }, { "code": null, "e": 4947, "s": 4912, "text": "Student_address table structure :" }, { "code": null, "e": 4979, "s": 4947, "text": "Student_marks table structure :" }, { "code": null, "e": 5092, "s": 4979, "text": "Insert the records into the student_address table using PHP (data1.php) Run code by typing “localhost/data1.php”" }, { "code": null, "e": 5096, "s": 5092, "text": "PHP" }, { "code": "<?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die(\"Connection failed: \" . $conn->connect_error);}//insert records into table$sql = \"INSERT INTO student_address VALUES (1,'sravan kumar','kakumanu');\";$sql .= \"INSERT INTO student_address VALUES (2,'bobby','kakumanu');\";$sql .= \"INSERT INTO student_address VALUES (3,'ojaswi','hyderabad');\";$sql .= \"INSERT INTO student_address VALUES (4,'rohith','hyderabad');\";$sql .= \"INSERT INTO student_address VALUES (5,'gnanesh','hyderabad');\"; if ($conn->multi_query($sql) === TRUE) { echo \"data stored successfully\";} else { echo \"Error: \" . $sql . \"<br>\" . $conn->error;} $conn->close();?>", "e": 6021, "s": 5096, "text": null }, { "code": null, "e": 6030, "s": 6021, "text": "Output :" }, { "code": null, "e": 6104, "s": 6030, "text": "Write PHP code to insert details in the student_marks table. (data2.PHP) " }, { "code": null, "e": 6108, "s": 6104, "text": "PHP" }, { "code": "<?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);// Check this connectionif ($conn->connect_error) { die(\"Connection failed: \" . $conn->connect_error);}//insert records into table$sql = \"INSERT INTO student_marks VALUES (1,98,99);\";$sql .= \"INSERT INTO student_marks VALUES (2,78,89);\";$sql .= \"INSERT INTO student_marks VALUES (3,78,98);\";$sql .= \"INSERT INTO student_marks VALUES (4,89,98);\";$sql .= \"INSERT INTO student_marks VALUES (7,89,79);\"; if ($conn->multi_query($sql) === TRUE) { echo \"data stored successfully\";} else { echo \"Error: \" . $sql . \"<br>\" . $conn->error;} $conn->close();?>", "e": 6944, "s": 6108, "text": null }, { "code": null, "e": 6953, "s": 6944, "text": "Output :" }, { "code": null, "e": 6998, "s": 6953, "text": "Type “localhost/data2.php” to see the output" }, { "code": null, "e": 7046, "s": 6998, "text": "Write PHP code to perform inner join (form.php)" }, { "code": null, "e": 7050, "s": 7046, "text": "PHP" }, { "code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"inner join on student_address: \";echo \"<br>\";echo \"<br>\";//sql query to display all student_address table based on student id using inner join$sql = \"SELECT * from student_address INNER JOIN student_marks on student_address.sid=student_marks.sid\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } echo \"<br>\";echo \"inner join on student_marks: \";echo \"<br>\";echo \"<br>\";//sql query to display all student_marks table based on student id using inner join$sql1 = \"SELECT * from student_marks INNER JOIN student_address on student_address.sid=student_marks.sid\";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- SUBJECT 1 : \". $row['subject1'] ,\" ----- SUBJECT 2 : \". $row['subject2'] ; echo \"<br>\"; } //close the connection $conn->close();?></body></html>", "e": 8400, "s": 7050, "text": null }, { "code": null, "e": 8409, "s": 8400, "text": "Output :" }, { "code": null, "e": 8452, "s": 8409, "text": "Type “localhost/form.php” in your browser." }, { "code": null, "e": 8497, "s": 8452, "text": "Write code to perform right join (form1.php)" }, { "code": null, "e": 8501, "s": 8497, "text": "PHP" }, { "code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"right join on student_address: \";echo \"<br>\";echo \"<br>\";//sql query to display all student_address table based on student id using right join$sql = \"SELECT * from student_address RIGHT JOIN student_marks on student_address.sid=student_marks.sid\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } echo \"<br>\";echo \"right join on student_marks: \";echo \"<br>\";echo \"<br>\";//sql query to display all student_marks table based on student id using right join$sql1 = \"SELECT * from student_marks RIGHT JOIN student_address on student_address.sid=student_marks.sid\";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- SUBJECT 1 : \". $row['subject1'] ,\" ----- SUBJECT 2 : \". $row['subject2'] ; echo \"<br>\"; } //close the connection $conn->close();?></body></html>", "e": 9851, "s": 8501, "text": null }, { "code": null, "e": 9860, "s": 9851, "text": "Output :" }, { "code": null, "e": 9904, "s": 9860, "text": "Type “localhost/form1.php” in your browser." }, { "code": null, "e": 9952, "s": 9904, "text": "Write PHP code to perform left join (form2.php)" }, { "code": null, "e": 9956, "s": 9952, "text": "PHP" }, { "code": "<html><body><?php//servername$servername = \"localhost\";//username$username = \"root\";//empty password$password = \"\";//database is the database name$dbname = \"database\"; // Create connection by passing these connection parameters$conn = new mysqli($servername, $username, $password, $dbname);echo \"left join on student_address: \";echo \"<br>\";echo \"<br>\";//sql query to display all student_address table based on student id using left join$sql = \"SELECT * from student_address LEFT JOIN student_marks on student_address.sid=student_marks.sid\";$result = $conn->query($sql);//display data on web pagewhile($row = mysqli_fetch_array($result)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- NAME : \". $row['sname'] ,\" ----- ADDRESS : \". $row['saddress'] ; echo \"<br>\"; } echo \"<br>\";echo \"left join on student_marks: \";echo \"<br>\";echo \"<br>\";//sql query to display all student_marks table based on student id using left join$sql1 = \"SELECT * from student_marks LEFT JOIN student_address on student_address.sid=student_marks.sid\";$result1 = $conn->query($sql1);//display data on web pagewhile($row = mysqli_fetch_array($result1)){ echo \" STUDENT-ID : \". $row['sid'], \" ----- SUBJECT 1 : \". $row['subject1'] ,\" ----- SUBJECT 2 : \". $row['subject2'] ; echo \"<br>\"; } //close the connection $conn->close();?></body></html>", "e": 11299, "s": 9956, "text": null }, { "code": null, "e": 11308, "s": 11299, "text": "Output :" }, { "code": null, "e": 11345, "s": 11308, "text": "type localhost/form2.php in browser" }, { "code": null, "e": 11349, "s": 11345, "text": "PHP" }, { "code": null, "e": 11353, "s": 11349, "text": "SQL" }, { "code": null, "e": 11357, "s": 11353, "text": "SQL" }, { "code": null, "e": 11361, "s": 11357, "text": "PHP" }, { "code": null, "e": 11459, "s": 11361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11541, "s": 11459, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 11586, "s": 11541, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 11637, "s": 11586, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 11667, "s": 11637, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 11690, "s": 11667, "text": "PHP | Ternary Operator" }, { "code": null, "e": 11732, "s": 11690, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 11779, "s": 11732, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 11797, "s": 11779, "text": "SQL | WITH clause" }, { "code": null, "e": 11841, "s": 11797, "text": "How to find Nth highest salary from a table" } ]
JavaScript method to get the URL without query string
30 May, 2019 The task is to get the URL name of the page without using a query string with the help of JavaScript. replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to replace with the search value.Return value: It returns a new string where the defines value(s) has been replaced by the new value. Syntax: string.replace(searchVal, newvalue) Parameters: searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value. newvalue: This parameter is required. It specifies the value to replace with the search value. Return value: It returns a new string where the defines value(s) has been replaced by the new value. split() method: This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit)Parameters:separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value: It returns a new Array, having the splitted items. Syntax: string.split(separator, limit) Parameters: separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item). limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array. Return value: It returns a new Array, having the splitted items. Example 1: This example first extracts the all URL’s of the page using href and then gets the first URL by setting index = 0 and then removes the portion after ? using split() method. <!DOCTYPE HTML> <html> <head> <title> JavaScript method to get the URL without query string </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_click()"> Get URL </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get URL"; function functionName(fun) { var val = fun.name; el_down.innerHTML = val; } function GFGFunction() { } function GFG_click() { el_down.innerHTML = window.location.href.split('?')[0]; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example replacing the location.search with empty string with the help of replace() method from the location. <!DOCTYPE HTML> <html> <head> <title> JavaScript method to get the URL without query string </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_click()"> Get URL </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get URL"; function functionName(fun) { var val = fun.name; el_down.innerHTML = val; } function GFGFunction() { } function GFG_click() { el_down.innerHTML = location.toString().replace(location.search, ""); } </script> </body> </html> Output: Before clicking on the button: After clicking on the 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": "\n30 May, 2019" }, { "code": null, "e": 130, "s": 28, "text": "The task is to get the URL name of the page without using a query string with the help of JavaScript." }, { "code": null, "e": 657, "s": 130, "text": "replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to replace with the search value.Return value: It returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 665, "s": 657, "text": "Syntax:" }, { "code": null, "e": 701, "s": 665, "text": "string.replace(searchVal, newvalue)" }, { "code": null, "e": 713, "s": 701, "text": "Parameters:" }, { "code": null, "e": 842, "s": 713, "text": "searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value." }, { "code": null, "e": 937, "s": 842, "text": "newvalue: This parameter is required. It specifies the value to replace with the search value." }, { "code": null, "e": 1038, "s": 937, "text": "Return value: It returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 1622, "s": 1038, "text": "split() method: This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit)Parameters:separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value: It returns a new Array, having the splitted items." }, { "code": null, "e": 1630, "s": 1622, "text": "Syntax:" }, { "code": null, "e": 1661, "s": 1630, "text": "string.split(separator, limit)" }, { "code": null, "e": 1673, "s": 1661, "text": "Parameters:" }, { "code": null, "e": 1878, "s": 1673, "text": "separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)." }, { "code": null, "e": 2037, "s": 1878, "text": "limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array." }, { "code": null, "e": 2102, "s": 2037, "text": "Return value: It returns a new Array, having the splitted items." }, { "code": null, "e": 2286, "s": 2102, "text": "Example 1: This example first extracts the all URL’s of the page using href and then gets the first URL by setting index = 0 and then removes the portion after ? using split() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JavaScript method to get the URL without query string </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_click()\"> Get URL </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get URL\"; function functionName(fun) { var val = fun.name; el_down.innerHTML = val; } function GFGFunction() { } function GFG_click() { el_down.innerHTML = window.location.href.split('?')[0]; } </script> </body> </html> ", "e": 3474, "s": 2286, "text": null }, { "code": null, "e": 3482, "s": 3474, "text": "Output:" }, { "code": null, "e": 3513, "s": 3482, "text": "Before clicking on the button:" }, { "code": null, "e": 3543, "s": 3513, "text": "After clicking on the button:" }, { "code": null, "e": 3668, "s": 3543, "text": "Example 2: This example replacing the location.search with empty string with the help of replace() method from the location." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JavaScript method to get the URL without query string </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_click()\"> Get URL </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get URL\"; function functionName(fun) { var val = fun.name; el_down.innerHTML = val; } function GFGFunction() { } function GFG_click() { el_down.innerHTML = location.toString().replace(location.search, \"\"); } </script> </body> </html> ", "e": 4897, "s": 3668, "text": null }, { "code": null, "e": 4905, "s": 4897, "text": "Output:" }, { "code": null, "e": 4936, "s": 4905, "text": "Before clicking on the button:" }, { "code": null, "e": 4966, "s": 4936, "text": "After clicking on the button:" }, { "code": null, "e": 4977, "s": 4966, "text": "JavaScript" }, { "code": null, "e": 4994, "s": 4977, "text": "Web Technologies" }, { "code": null, "e": 5021, "s": 4994, "text": "Web technologies Questions" }, { "code": null, "e": 5119, "s": 5021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5180, "s": 5119, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5252, "s": 5180, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5292, "s": 5252, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5333, "s": 5292, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5385, "s": 5333, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 5418, "s": 5385, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5480, "s": 5418, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5541, "s": 5480, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5591, "s": 5541, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Push Relabel Algorithm | Set 2 (Implementation)
30 Jun, 2022 We strongly recommend to refer below article before moving on to this article. Push Relabel Algorithm | Set 1 (Introduction and Illustration) Problem Statement: Given a graph that represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints: Flow on an edge doesn’t exceed the given capacity of the edge.Incoming flow is equal to outgoing flow for every vertex except s and t. Flow on an edge doesn’t exceed the given capacity of the edge. Incoming flow is equal to outgoing flow for every vertex except s and t. For example, consider the following graph from CLRS book. The maximum possible flow in the above graph is 23. Push-Relabel Algorithm 1) Initialize PreFlow : Initialize Flows and Heights 2) While it is possible to perform a Push() or Relabel() on a vertex // Or while there is a vertex that has excess flow Do Push() or Relabel() // At this point all vertices have Excess Flow as 0 (Except source // and sink) 3) Return flow. Below are main operations performed in Push Relabel algorithm. There are three main operations in Push-Relabel Algorithm 1. Initialize PreFlow() It initializes heights and flows of all vertices. Preflow() 1) Initialize height and flow of every vertex as 0. 2) Initialize height of source vertex equal to total number of vertices in graph. 3) Initialize flow of every edge as 0. 4) For all vertices adjacent to source s, flow and excess flow is equal to capacity initially. 2. Push() is used to make the flow from a node that has excess flow. If a vertex has excess flow and there is an adjacent with a smaller height (in the residual graph), we push the flow from the vertex to the adjacent with a lower height. The amount of pushed flow through the pipe (edge) is equal to the minimum of excess flow and capacity of the edge. 3. Relabel() operation is used when a vertex has excess flow and none of its adjacents is at the lower height. We basically increase the height of the vertex so that we can perform push(). To increase height, we pick the minimum height adjacent (in residual graph, i.e., an adjacent to whom we can add flow) and add 1 to it. Implementation: The following implementation uses the below structure for representing a flow network. struct Vertex { int h; // Height of node int e_flow; // Excess Flow } struct Edge { int u, v; // Edge is from u to v int flow; // Current flow int capacity; } class Graph { Edge edge[]; // Array of edges Vertex ver[]; // Array of vertices } The below code uses the given graph itself as a flow network and residual graph. We have not created a separate graph for the residual graph and have used the same graph for simplicity. Implementation: C++ // C++ program to implement push-relabel algorithm for// getting maximum flow of graph#include <bits/stdc++.h>using namespace std; struct Edge{ // To store current flow and capacity of edge int flow, capacity; // An edge u--->v has start vertex as u and end // vertex as v. int u, v; Edge(int flow, int capacity, int u, int v) { this->flow = flow; this->capacity = capacity; this->u = u; this->v = v; }}; // Represent a Vertexstruct Vertex{ int h, e_flow; Vertex(int h, int e_flow) { this->h = h; this->e_flow = e_flow; }}; // To represent a flow networkclass Graph{ int V; // No. of vertices vector<Vertex> ver; vector<Edge> edge; // Function to push excess flow from u bool push(int u); // Function to relabel a vertex u void relabel(int u); // This function is called to initialize // preflow void preflow(int s); // Function to reverse edge void updateReverseEdgeFlow(int i, int flow); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // returns maximum flow from s to t int getMaxFlow(int s, int t);}; Graph::Graph(int V){ this->V = V; // all vertices are initialized with 0 height // and 0 excess flow for (int i = 0; i < V; i++) ver.push_back(Vertex(0, 0));} void Graph::addEdge(int u, int v, int capacity){ // flow is initialized with 0 for all edge edge.push_back(Edge(0, capacity, u, v));} void Graph::preflow(int s){ // Making h of source Vertex equal to no. of vertices // Height of other vertices is 0. ver[s].h = ver.size(); // for (int i = 0; i < edge.size(); i++) { // If current edge goes from source if (edge[i].u == s) { // Flow is equal to capacity edge[i].flow = edge[i].capacity; // Initialize excess flow for adjacent v ver[edge[i].v].e_flow += edge[i].flow; // Add an edge from v to s in residual graph with // capacity equal to 0 edge.push_back(Edge(-edge[i].flow, 0, edge[i].v, s)); } }} // returns index of overflowing Vertexint overFlowVertex(vector<Vertex>& ver){ for (int i = 1; i < ver.size() - 1; i++) if (ver[i].e_flow > 0) return i; // -1 if no overflowing Vertex return -1;} // Update reverse flow for flow added on ith Edgevoid Graph::updateReverseEdgeFlow(int i, int flow){ int u = edge[i].v, v = edge[i].u; for (int j = 0; j < edge.size(); j++) { if (edge[j].v == v && edge[j].u == u) { edge[j].flow -= flow; return; } } // adding reverse Edge in residual graph Edge e = Edge(0, flow, u, v); edge.push_back(e);} // To push flow from overflowing vertex ubool Graph::push(int u){ // Traverse through all edges to find an adjacent (of u) // to which flow can be pushed for (int i = 0; i < edge.size(); i++) { // Checks u of current edge is same as given // overflowing vertex if (edge[i].u == u) { // if flow is equal to capacity then no push // is possible if (edge[i].flow == edge[i].capacity) continue; // Push is only possible if height of adjacent // is smaller than height of overflowing vertex if (ver[u].h > ver[edge[i].v].h) { // Flow to be pushed is equal to minimum of // remaining flow on edge and excess flow. int flow = min(edge[i].capacity - edge[i].flow, ver[u].e_flow); // Reduce excess flow for overflowing vertex ver[u].e_flow -= flow; // Increase excess flow for adjacent ver[edge[i].v].e_flow += flow; // Add residual flow (With capacity 0 and negative // flow) edge[i].flow += flow; updateReverseEdgeFlow(i, flow); return true; } } } return false;} // function to relabel vertex uvoid Graph::relabel(int u){ // Initialize minimum height of an adjacent int mh = INT_MAX; // Find the adjacent with minimum height for (int i = 0; i < edge.size(); i++) { if (edge[i].u == u) { // if flow is equal to capacity then no // relabeling if (edge[i].flow == edge[i].capacity) continue; // Update minimum height if (ver[edge[i].v].h < mh) { mh = ver[edge[i].v].h; // updating height of u ver[u].h = mh + 1; } } }} // main function for printing maximum flow of graphint Graph::getMaxFlow(int s, int t){ preflow(s); // loop until none of the Vertex is in overflow while (overFlowVertex(ver) != -1) { int u = overFlowVertex(ver); if (!push(u)) relabel(u); } // ver.back() returns last Vertex, whose // e_flow will be final maximum flow return ver.back().e_flow;} // Driver program to test above functionsint main(){ int V = 6; Graph g(V); // Creating above shown flow network g.addEdge(0, 1, 16); g.addEdge(0, 2, 13); g.addEdge(1, 2, 10); g.addEdge(2, 1, 4); g.addEdge(1, 3, 12); g.addEdge(2, 4, 14); g.addEdge(3, 2, 9); g.addEdge(3, 5, 20); g.addEdge(4, 3, 7); g.addEdge(4, 5, 4); // Initialize source and sink int s = 0, t = 5; cout << "Maximum flow is " << g.getMaxFlow(s, t); return 0;} Maximum flow is 23 The code in this article is contributed by Siddharth Lalwani and Utkarsh Trivedi. avtarkumar719 surinderdawra388 hardikkoriintern Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 194, "s": 52, "text": "We strongly recommend to refer below article before moving on to this article. Push Relabel Algorithm | Set 1 (Introduction and Illustration)" }, { "code": null, "e": 214, "s": 194, "text": "Problem Statement: " }, { "code": null, "e": 425, "s": 214, "text": "Given a graph that represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints:" }, { "code": null, "e": 560, "s": 425, "text": "Flow on an edge doesn’t exceed the given capacity of the edge.Incoming flow is equal to outgoing flow for every vertex except s and t." }, { "code": null, "e": 623, "s": 560, "text": "Flow on an edge doesn’t exceed the given capacity of the edge." }, { "code": null, "e": 696, "s": 623, "text": "Incoming flow is equal to outgoing flow for every vertex except s and t." }, { "code": null, "e": 756, "s": 696, "text": "For example, consider the following graph from CLRS book. " }, { "code": null, "e": 809, "s": 756, "text": "The maximum possible flow in the above graph is 23. " }, { "code": null, "e": 1142, "s": 809, "text": "Push-Relabel Algorithm \n1) Initialize PreFlow : Initialize Flows and Heights \n\n2) While it is possible to perform a Push() or Relabel() on a vertex\n // Or while there is a vertex that has excess flow\n Do Push() or Relabel()\n\n// At this point all vertices have Excess Flow as 0 (Except source\n// and sink)\n3) Return flow." }, { "code": null, "e": 1207, "s": 1142, "text": "Below are main operations performed in Push Relabel algorithm. " }, { "code": null, "e": 1265, "s": 1207, "text": "There are three main operations in Push-Relabel Algorithm" }, { "code": null, "e": 1340, "s": 1265, "text": "1. Initialize PreFlow() It initializes heights and flows of all vertices. " }, { "code": null, "e": 1628, "s": 1340, "text": "Preflow() \n1) Initialize height and flow of every vertex as 0.\n2) Initialize height of source vertex equal to total \n number of vertices in graph.\n3) Initialize flow of every edge as 0.\n4) For all vertices adjacent to source s, flow and \n excess flow is equal to capacity initially." }, { "code": null, "e": 1982, "s": 1628, "text": "2. Push() is used to make the flow from a node that has excess flow. If a vertex has excess flow and there is an adjacent with a smaller height (in the residual graph), we push the flow from the vertex to the adjacent with a lower height. The amount of pushed flow through the pipe (edge) is equal to the minimum of excess flow and capacity of the edge." }, { "code": null, "e": 2307, "s": 1982, "text": "3. Relabel() operation is used when a vertex has excess flow and none of its adjacents is at the lower height. We basically increase the height of the vertex so that we can perform push(). To increase height, we pick the minimum height adjacent (in residual graph, i.e., an adjacent to whom we can add flow) and add 1 to it." }, { "code": null, "e": 2323, "s": 2307, "text": "Implementation:" }, { "code": null, "e": 2411, "s": 2323, "text": "The following implementation uses the below structure for representing a flow network. " }, { "code": null, "e": 2494, "s": 2411, "text": "struct Vertex \n{\n int h; // Height of node\n int e_flow; // Excess Flow \n}" }, { "code": null, "e": 2601, "s": 2494, "text": "struct Edge \n{\n int u, v; // Edge is from u to v \n int flow; // Current flow\n int capacity; \n}" }, { "code": null, "e": 2694, "s": 2601, "text": "class Graph \n{\n Edge edge[]; // Array of edges\n Vertex ver[]; // Array of vertices \n}" }, { "code": null, "e": 2880, "s": 2694, "text": "The below code uses the given graph itself as a flow network and residual graph. We have not created a separate graph for the residual graph and have used the same graph for simplicity." }, { "code": null, "e": 2896, "s": 2880, "text": "Implementation:" }, { "code": null, "e": 2900, "s": 2896, "text": "C++" }, { "code": "// C++ program to implement push-relabel algorithm for// getting maximum flow of graph#include <bits/stdc++.h>using namespace std; struct Edge{ // To store current flow and capacity of edge int flow, capacity; // An edge u--->v has start vertex as u and end // vertex as v. int u, v; Edge(int flow, int capacity, int u, int v) { this->flow = flow; this->capacity = capacity; this->u = u; this->v = v; }}; // Represent a Vertexstruct Vertex{ int h, e_flow; Vertex(int h, int e_flow) { this->h = h; this->e_flow = e_flow; }}; // To represent a flow networkclass Graph{ int V; // No. of vertices vector<Vertex> ver; vector<Edge> edge; // Function to push excess flow from u bool push(int u); // Function to relabel a vertex u void relabel(int u); // This function is called to initialize // preflow void preflow(int s); // Function to reverse edge void updateReverseEdgeFlow(int i, int flow); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // returns maximum flow from s to t int getMaxFlow(int s, int t);}; Graph::Graph(int V){ this->V = V; // all vertices are initialized with 0 height // and 0 excess flow for (int i = 0; i < V; i++) ver.push_back(Vertex(0, 0));} void Graph::addEdge(int u, int v, int capacity){ // flow is initialized with 0 for all edge edge.push_back(Edge(0, capacity, u, v));} void Graph::preflow(int s){ // Making h of source Vertex equal to no. of vertices // Height of other vertices is 0. ver[s].h = ver.size(); // for (int i = 0; i < edge.size(); i++) { // If current edge goes from source if (edge[i].u == s) { // Flow is equal to capacity edge[i].flow = edge[i].capacity; // Initialize excess flow for adjacent v ver[edge[i].v].e_flow += edge[i].flow; // Add an edge from v to s in residual graph with // capacity equal to 0 edge.push_back(Edge(-edge[i].flow, 0, edge[i].v, s)); } }} // returns index of overflowing Vertexint overFlowVertex(vector<Vertex>& ver){ for (int i = 1; i < ver.size() - 1; i++) if (ver[i].e_flow > 0) return i; // -1 if no overflowing Vertex return -1;} // Update reverse flow for flow added on ith Edgevoid Graph::updateReverseEdgeFlow(int i, int flow){ int u = edge[i].v, v = edge[i].u; for (int j = 0; j < edge.size(); j++) { if (edge[j].v == v && edge[j].u == u) { edge[j].flow -= flow; return; } } // adding reverse Edge in residual graph Edge e = Edge(0, flow, u, v); edge.push_back(e);} // To push flow from overflowing vertex ubool Graph::push(int u){ // Traverse through all edges to find an adjacent (of u) // to which flow can be pushed for (int i = 0; i < edge.size(); i++) { // Checks u of current edge is same as given // overflowing vertex if (edge[i].u == u) { // if flow is equal to capacity then no push // is possible if (edge[i].flow == edge[i].capacity) continue; // Push is only possible if height of adjacent // is smaller than height of overflowing vertex if (ver[u].h > ver[edge[i].v].h) { // Flow to be pushed is equal to minimum of // remaining flow on edge and excess flow. int flow = min(edge[i].capacity - edge[i].flow, ver[u].e_flow); // Reduce excess flow for overflowing vertex ver[u].e_flow -= flow; // Increase excess flow for adjacent ver[edge[i].v].e_flow += flow; // Add residual flow (With capacity 0 and negative // flow) edge[i].flow += flow; updateReverseEdgeFlow(i, flow); return true; } } } return false;} // function to relabel vertex uvoid Graph::relabel(int u){ // Initialize minimum height of an adjacent int mh = INT_MAX; // Find the adjacent with minimum height for (int i = 0; i < edge.size(); i++) { if (edge[i].u == u) { // if flow is equal to capacity then no // relabeling if (edge[i].flow == edge[i].capacity) continue; // Update minimum height if (ver[edge[i].v].h < mh) { mh = ver[edge[i].v].h; // updating height of u ver[u].h = mh + 1; } } }} // main function for printing maximum flow of graphint Graph::getMaxFlow(int s, int t){ preflow(s); // loop until none of the Vertex is in overflow while (overFlowVertex(ver) != -1) { int u = overFlowVertex(ver); if (!push(u)) relabel(u); } // ver.back() returns last Vertex, whose // e_flow will be final maximum flow return ver.back().e_flow;} // Driver program to test above functionsint main(){ int V = 6; Graph g(V); // Creating above shown flow network g.addEdge(0, 1, 16); g.addEdge(0, 2, 13); g.addEdge(1, 2, 10); g.addEdge(2, 1, 4); g.addEdge(1, 3, 12); g.addEdge(2, 4, 14); g.addEdge(3, 2, 9); g.addEdge(3, 5, 20); g.addEdge(4, 3, 7); g.addEdge(4, 5, 4); // Initialize source and sink int s = 0, t = 5; cout << \"Maximum flow is \" << g.getMaxFlow(s, t); return 0;}", "e": 8624, "s": 2900, "text": null }, { "code": null, "e": 8643, "s": 8624, "text": "Maximum flow is 23" }, { "code": null, "e": 8725, "s": 8643, "text": "The code in this article is contributed by Siddharth Lalwani and Utkarsh Trivedi." }, { "code": null, "e": 8739, "s": 8725, "text": "avtarkumar719" }, { "code": null, "e": 8756, "s": 8739, "text": "surinderdawra388" }, { "code": null, "e": 8773, "s": 8756, "text": "hardikkoriintern" }, { "code": null, "e": 8779, "s": 8773, "text": "Graph" }, { "code": null, "e": 8785, "s": 8779, "text": "Graph" } ]
Python | os.open() method
06 Sep, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.open() method in Python is used to open a specified file path and set various flags according to the specified flags and its mode according to specified mode.This method returns a file descriptor for newly open file. The returned file descriptor is non-inheritable. Syntax: os.open(path, flags, mode = 0o777, *, dir_fd = None) Parameters:Path: A path-like object representing the file system path. This is the file path to be opened.A path-like object is a string or bytes object which represents a path.flags: This parameter specify the flags to be set for newly opened file.mode (optional): A numeric value representing the mode of the newly opened file. The default value of this parameter is 0o777 (octal).dir_fd (optional): A file descriptor referring to a directory. Return Type: This method returns a file descriptor for newly opened file. # Python program to explain os.open() method # importing os module import os # File path to be openedpath = './file9.txt' # Mode to be set mode = 0o666 # flagsflags = os.O_RDWR | os.O_CREAT # Open the specified file path# using os.open() method# and get the file descriptor for # opened file pathfd = os.open(path, flags, mode) print("File path opened successfully.") # Write a string to the file# using file descriptorstr = "GeeksforGeeks: A computer science portal for geeks."os.write(fd, str.encode())print("String written to the file descriptor.") # Now read the file # from beginningos.lseek(fd, 0, 0)str = os.read(fd, os.path.getsize(fd))print("\nString read from the file descriptor:")print(str.decode()) # Close the file descriptoros.close(fd)print("\nFile descriptor closed successfully.") File path opened successfully. String written to the file descriptor. String read from file descriptor: GeeksforGeeks: A computer science portal for geeks. File descriptor closed successfully. Reference: https://docs.python.org/3/library/os.html#os.open Akanksha_Rai python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 516, "s": 247, "text": "os.open() method in Python is used to open a specified file path and set various flags according to the specified flags and its mode according to specified mode.This method returns a file descriptor for newly open file. The returned file descriptor is non-inheritable." }, { "code": null, "e": 577, "s": 516, "text": "Syntax: os.open(path, flags, mode = 0o777, *, dir_fd = None)" }, { "code": null, "e": 1023, "s": 577, "text": "Parameters:Path: A path-like object representing the file system path. This is the file path to be opened.A path-like object is a string or bytes object which represents a path.flags: This parameter specify the flags to be set for newly opened file.mode (optional): A numeric value representing the mode of the newly opened file. The default value of this parameter is 0o777 (octal).dir_fd (optional): A file descriptor referring to a directory." }, { "code": null, "e": 1097, "s": 1023, "text": "Return Type: This method returns a file descriptor for newly opened file." }, { "code": "# Python program to explain os.open() method # importing os module import os # File path to be openedpath = './file9.txt' # Mode to be set mode = 0o666 # flagsflags = os.O_RDWR | os.O_CREAT # Open the specified file path# using os.open() method# and get the file descriptor for # opened file pathfd = os.open(path, flags, mode) print(\"File path opened successfully.\") # Write a string to the file# using file descriptorstr = \"GeeksforGeeks: A computer science portal for geeks.\"os.write(fd, str.encode())print(\"String written to the file descriptor.\") # Now read the file # from beginningos.lseek(fd, 0, 0)str = os.read(fd, os.path.getsize(fd))print(\"\\nString read from the file descriptor:\")print(str.decode()) # Close the file descriptoros.close(fd)print(\"\\nFile descriptor closed successfully.\")", "e": 1915, "s": 1097, "text": null }, { "code": null, "e": 2111, "s": 1915, "text": "File path opened successfully.\nString written to the file descriptor.\n\nString read from file descriptor:\nGeeksforGeeks: A computer science portal for geeks.\n\nFile descriptor closed successfully.\n" }, { "code": null, "e": 2172, "s": 2111, "text": "Reference: https://docs.python.org/3/library/os.html#os.open" }, { "code": null, "e": 2185, "s": 2172, "text": "Akanksha_Rai" }, { "code": null, "e": 2202, "s": 2185, "text": "python-os-module" }, { "code": null, "e": 2209, "s": 2202, "text": "Python" } ]
Python – Multiply all cross list element pairs
06 Mar, 2020 Sometimes, while working with Python list, we can have a problem in which we need to perform multiplication of each element of list with other list. This can have application in both web development and day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionThis is the most straight forward method to perform this task. In this, we iterate the both the list and perform multiplication of each element with other and store result in new list. # Python3 code to demonstrate # Multiply all cross list element pairs# using list comprehension # Initializing liststest_list1 = [4, 5, 6]test_list2 = [6, 4, 2] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Multiply all cross list element pairs# using list comprehensionres = [i * j for j in test_list1 for i in test_list2] # printing result print ("The multiplication list is : " + str(res)) The original list 1 is : [4, 5, 6] The original list 2 is : [6, 4, 2] The multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12] Method #2 : Using product()This is another way in which this task can be performed. In this, we perform the task of multiplication using product(). # Python3 code to demonstrate # Multiply all cross list element pairs# using product()from itertools import product # Initializing liststest_list1 = [4, 5, 6]test_list2 = [6, 4, 2] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Multiply all cross list element pairs# using product()res = [a * b for a, b in product(test_list1, test_list2)] # printing result print ("The multiplication list is : " + str(res)) The original list 1 is : [4, 5, 6] The original list 2 is : [6, 4, 2] The multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Mar, 2020" }, { "code": null, "e": 315, "s": 28, "text": "Sometimes, while working with Python list, we can have a problem in which we need to perform multiplication of each element of list with other list. This can have application in both web development and day-day programming. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 536, "s": 315, "text": "Method #1 : Using list comprehensionThis is the most straight forward method to perform this task. In this, we iterate the both the list and perform multiplication of each element with other and store result in new list." }, { "code": "# Python3 code to demonstrate # Multiply all cross list element pairs# using list comprehension # Initializing liststest_list1 = [4, 5, 6]test_list2 = [6, 4, 2] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Multiply all cross list element pairs# using list comprehensionres = [i * j for j in test_list1 for i in test_list2] # printing result print (\"The multiplication list is : \" + str(res))", "e": 1031, "s": 536, "text": null }, { "code": null, "e": 1167, "s": 1031, "text": "The original list 1 is : [4, 5, 6]\nThe original list 2 is : [6, 4, 2]\nThe multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12]\n" }, { "code": null, "e": 1317, "s": 1169, "text": "Method #2 : Using product()This is another way in which this task can be performed. In this, we perform the task of multiplication using product()." }, { "code": "# Python3 code to demonstrate # Multiply all cross list element pairs# using product()from itertools import product # Initializing liststest_list1 = [4, 5, 6]test_list2 = [6, 4, 2] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Multiply all cross list element pairs# using product()res = [a * b for a, b in product(test_list1, test_list2)] # printing result print (\"The multiplication list is : \" + str(res))", "e": 1827, "s": 1317, "text": null }, { "code": null, "e": 1963, "s": 1827, "text": "The original list 1 is : [4, 5, 6]\nThe original list 2 is : [6, 4, 2]\nThe multiplication list is : [24, 16, 8, 30, 20, 10, 36, 24, 12]\n" }, { "code": null, "e": 1984, "s": 1963, "text": "Python list-programs" }, { "code": null, "e": 1991, "s": 1984, "text": "Python" }, { "code": null, "e": 2007, "s": 1991, "text": "Python Programs" }, { "code": null, "e": 2105, "s": 2007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2137, "s": 2105, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2164, "s": 2137, "text": "Python Classes and Objects" }, { "code": null, "e": 2185, "s": 2164, "text": "Python OOPs Concepts" }, { "code": null, "e": 2208, "s": 2185, "text": "Introduction To PYTHON" }, { "code": null, "e": 2264, "s": 2208, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2286, "s": 2264, "text": "Defaultdict in Python" }, { "code": null, "e": 2325, "s": 2286, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2363, "s": 2325, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2412, "s": 2363, "text": "Python | Convert string dictionary to dictionary" } ]
Extract Single Column as DataFrame in R
16 May, 2021 In this article, we will see how a single column can be extracted as Dataframe using R programming language. Database in use: Data Frame GFG In this method, a specific column can be extracted from the dataframe using its name using $. Syntax: dataframe$column_name The column returned will be in a form of a vector, but it can be converted to a dataframe explicitly using data.frame() function of R language. Example: R # Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c("Damon","Joe","Jenna","Ryan", "Bonnie","Stefan","William"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c("2021-01-01", "2016-06-27", "2014-1-09", "2017-02-14", "2009-03-26","2019-06-27", "2020-09-27")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extract Specific columns# Convert it explicitly to a dataframespecific_col <- data.frame(gfg.data$ GFG_Name, gfg.data$ GFG_Sal)print(specific_col) Output Here, we can see that two columns are extracted Name & Salary The column can also be extracted as a dataframe using square brackets with an index of the column in the dataframe given to it as input. Example: R # Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c("Damon","Joe","Jenna","Ryan", "Bonnie","Stefan","William"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c("2021-01-01", "2016-06-27", "2014-1-09", "2017-02-14", "2009-03-26","2019-06-27", "2020-09-27")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extract Single Variable as Data Frame# Using Square Bracketsgfg.data[1]gfg.data[2] Output Display the 1st and 2nd column We extract columns as a vector from an R data frame, but sometimes we might need a column as a data frame. Thus, we can use as.data.frame to extract columns that we want to extract as a data frame with single square brackets. The purpose behind this could be merging the column with another data frame. Example: R # Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c("Damon","Joe","Jenna","Ryan", "Bonnie","Stefan","William"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c("2021-01-01", "2016-06-27", "2014-1-09", "2017-02-14", "2009-03-26","2019-06-27", "2020-09-27")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extracting 2nd column as a separate # dataframex2 <-as.data.frame(gfg.data[,2])print(x2) # Extracting 3rd column as a separate # dataframex3 <-as.data.frame(gfg.data[,3])print(x3) Output Extracting 2nd column as a separate data frame Extracting 3rd column as a separate data frame If the drop argument is provided with the value FALSE the columns are not converted to vector objects. Example: R # Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c("Damon","Joe","Jenna","Ryan", "Bonnie","Stefan","William"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c("2021-01-01", "2016-06-27", "2014-1-09", "2017-02-14", "2009-03-26","2019-06-27", "2020-09-27")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extract Single Variable as Data Frame # Using drop Argumentgfg.data[ , 1, drop = FALSE] gfg.data[ , 2, drop = FALSE] Output Displaying the 1st and 2nd column Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2021" }, { "code": null, "e": 137, "s": 28, "text": "In this article, we will see how a single column can be extracted as Dataframe using R programming language." }, { "code": null, "e": 154, "s": 137, "text": "Database in use:" }, { "code": null, "e": 169, "s": 154, "text": "Data Frame GFG" }, { "code": null, "e": 263, "s": 169, "text": "In this method, a specific column can be extracted from the dataframe using its name using $." }, { "code": null, "e": 271, "s": 263, "text": "Syntax:" }, { "code": null, "e": 293, "s": 271, "text": "dataframe$column_name" }, { "code": null, "e": 437, "s": 293, "text": "The column returned will be in a form of a vector, but it can be converted to a dataframe explicitly using data.frame() function of R language." }, { "code": null, "e": 446, "s": 437, "text": "Example:" }, { "code": null, "e": 448, "s": 446, "text": "R" }, { "code": "# Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c(\"Damon\",\"Joe\",\"Jenna\",\"Ryan\", \"Bonnie\",\"Stefan\",\"William\"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c(\"2021-01-01\", \"2016-06-27\", \"2014-1-09\", \"2017-02-14\", \"2009-03-26\",\"2019-06-27\", \"2020-09-27\")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extract Specific columns# Convert it explicitly to a dataframespecific_col <- data.frame(gfg.data$ GFG_Name, gfg.data$ GFG_Sal)print(specific_col)", "e": 1135, "s": 448, "text": null }, { "code": null, "e": 1143, "s": 1135, "text": "Output " }, { "code": null, "e": 1205, "s": 1143, "text": "Here, we can see that two columns are extracted Name & Salary" }, { "code": null, "e": 1342, "s": 1205, "text": "The column can also be extracted as a dataframe using square brackets with an index of the column in the dataframe given to it as input." }, { "code": null, "e": 1351, "s": 1342, "text": "Example:" }, { "code": null, "e": 1353, "s": 1351, "text": "R" }, { "code": "# Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c(\"Damon\",\"Joe\",\"Jenna\",\"Ryan\", \"Bonnie\",\"Stefan\",\"William\"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c(\"2021-01-01\", \"2016-06-27\", \"2014-1-09\", \"2017-02-14\", \"2009-03-26\",\"2019-06-27\", \"2020-09-27\")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extract Single Variable as Data Frame# Using Square Bracketsgfg.data[1]gfg.data[2]", "e": 1950, "s": 1353, "text": null }, { "code": null, "e": 1957, "s": 1950, "text": "Output" }, { "code": null, "e": 1988, "s": 1957, "text": "Display the 1st and 2nd column" }, { "code": null, "e": 2292, "s": 1988, "text": " We extract columns as a vector from an R data frame, but sometimes we might need a column as a data frame. Thus, we can use as.data.frame to extract columns that we want to extract as a data frame with single square brackets. The purpose behind this could be merging the column with another data frame." }, { "code": null, "e": 2301, "s": 2292, "text": "Example:" }, { "code": null, "e": 2303, "s": 2301, "text": "R" }, { "code": "# Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c(\"Damon\",\"Joe\",\"Jenna\",\"Ryan\", \"Bonnie\",\"Stefan\",\"William\"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c(\"2021-01-01\", \"2016-06-27\", \"2014-1-09\", \"2017-02-14\", \"2009-03-26\",\"2019-06-27\", \"2020-09-27\")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extracting 2nd column as a separate # dataframex2 <-as.data.frame(gfg.data[,2])print(x2) # Extracting 3rd column as a separate # dataframex3 <-as.data.frame(gfg.data[,3])print(x3) ", "e": 2996, "s": 2303, "text": null }, { "code": null, "e": 3003, "s": 2996, "text": "Output" }, { "code": null, "e": 3050, "s": 3003, "text": "Extracting 2nd column as a separate data frame" }, { "code": null, "e": 3097, "s": 3050, "text": "Extracting 3rd column as a separate data frame" }, { "code": null, "e": 3200, "s": 3097, "text": "If the drop argument is provided with the value FALSE the columns are not converted to vector objects." }, { "code": null, "e": 3209, "s": 3200, "text": "Example:" }, { "code": null, "e": 3211, "s": 3209, "text": "R" }, { "code": "# Create the data frame.gfg.data <- data.frame( GFG_Id = c (1:7), GFG_Name = c(\"Damon\",\"Joe\",\"Jenna\",\"Ryan\", \"Bonnie\",\"Stefan\",\"William\"), GFG_Sal = c(6200,5152,6110,7290,8485,7654, 2341), Start_date = as.Date(c(\"2021-01-01\", \"2016-06-27\", \"2014-1-09\", \"2017-02-14\", \"2009-03-26\",\"2019-06-27\", \"2020-09-27\")), stringsAsFactors = FALSE) # Print the data frame. print(gfg.data) # Extract Single Variable as Data Frame # Using drop Argumentgfg.data[ , 1, drop = FALSE] gfg.data[ , 2, drop = FALSE] ", "e": 3844, "s": 3211, "text": null }, { "code": null, "e": 3852, "s": 3844, "text": "Output " }, { "code": null, "e": 3886, "s": 3852, "text": "Displaying the 1st and 2nd column" }, { "code": null, "e": 3893, "s": 3886, "text": "Picked" }, { "code": null, "e": 3914, "s": 3893, "text": "R DataFrame-Programs" }, { "code": null, "e": 3926, "s": 3914, "text": "R-DataFrame" }, { "code": null, "e": 3937, "s": 3926, "text": "R Language" }, { "code": null, "e": 3948, "s": 3937, "text": "R Programs" } ]
Find the ordering of tasks from given dependencies
02 Jun, 2022 There are a total of n tasks you have to pick, labeled from 0 to n-1. Some tasks may have prerequisites tasks, for example to pick task 0 you have to first finish tasks 1, which is expressed as a pair: [0, 1] Given the total number of tasks and a list of prerequisite pairs, return the ordering of tasks you should pick to finish all tasks. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all tasks, return an empty array. Examples: Input: 2, [[1, 0]] Output: [0, 1] Explanation: There are a total of 2 tasks to pick. To pick task 1 you should have finished task 0. So the correct task order is [0, 1] . Input: 4, [[1, 0], [2, 0], [3, 1], [3, 2]] Output: [0, 1, 2, 3] or [0, 2, 1, 3] Explanation: There are a total of 4 tasks to pick. To pick task 3 you should have finished both tasks 1 and 2. Both tasks 1 and 2 should be pick after you finished task 0. So one correct task order is [0, 1, 2, 3]. Another correct ordering is [0, 2, 1, 3]. Asked In: Google, Twitter, Amazon and many more companies. Solution: We can consider this problem as a graph (related to topological sorting) problem. All tasks are nodes of the graph and if task u is a prerequisite of task v, we will add a directed edge from node u to node v. Now, this problem is equivalent to finding a topological ordering of nodes/tasks (using topological sorting) in the graph represented by prerequisites. If there is a cycle in the graph, then it is not possible to finish all tasks (because in that case there is no any topological order of tasks). Both BFS and DFS can be used for topological sorting to solve it. Since pair is inconvenient for the implementation of graph algorithms, we first transform it to a graph. If task u is a prerequisite of task v, we will add a directed edge from node u to node v. Topological Sorting using BFS Here we use Kahn’s algorithm for topological sorting. BFS uses the indegrees of each node. We will first try to find a node with 0 indegree. If we fail to do so, there must be a cycle in the graph and we return false. Otherwise we have found one. We set its indegree to be -1 to prevent from visiting it again and reduce the indegrees of all its neighbors by 1. This process will be repeated for n (number of nodes) times. CPP Java // CPP program to find order to process tasks// so that all tasks can be finished. This program// mainly uses Kahn's algorithm.#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation of graph from// given set of pairs.vector<unordered_set<int> > make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // Computes in-degree of every vertexvector<int> compute_indegree(vector<unordered_set<int> >& graph){ vector<int> degrees(graph.size(), 0); for (auto neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees;} // main function for topological sortingvector<int> findOrder(int numTasks, vector<pair<int, int> >& prerequisites){ // Create an adjacency list vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); // Find vertices of zero degree vector<int> degrees = compute_indegree(graph); queue<int> zeros; for (int i = 0; i < numTasks; i++) if (!degrees[i]) zeros.push(i); // Find vertices in topological order // starting with vertices of 0 degree // and reducing degrees of adjacent. vector<int> toposort; for (int i = 0; i < numTasks; i++) { if (zeros.empty()) return {}; int zero = zeros.front(); zeros.pop(); toposort.push_back(zero); for (int neigh : graph[zero]) { if (!--degrees[neigh]) zeros.push(neigh); } } return toposort;} // Driver codeint main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); vector<int> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } return 0;} // Java program to find order to process tasks// so that all tasks can be finished. This program// mainly uses Kahn's algorithm. import java.util.ArrayList;import java.util.HashSet;import java.util.LinkedList;import java.util.Queue; public class Dep { // Returns adjacency list representation of graph from // given set of pairs. static ArrayList<HashSet<Integer> > make_graph(int numTasks, int[][] prerequisites) { ArrayList<HashSet<Integer> > graph = new ArrayList<HashSet<Integer>>(numTasks); for (int i = 0; i < numTasks; i++) graph.add(new HashSet<Integer>()); for (int[] pre : prerequisites) graph.get(pre[1]).add(pre[0]); return graph; } // Computes in-degree of every vertex static int[] compute_indegree( ArrayList<HashSet<Integer> > graph) { int[] degrees = new int[graph.size()]; for (HashSet<Integer> neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees; } // main function for topological sorting static ArrayList<Integer> findOrder(int numTasks, int[][] prerequisites) { // Create an adjacency list ArrayList<HashSet<Integer> > graph = make_graph(numTasks, prerequisites); // Find vertices of zero degree int[] degrees = compute_indegree(graph); Queue<Integer> zeros = new LinkedList<Integer>(); for (int i = 0; i < numTasks; i++) if (degrees[i] == 0) zeros.add(i); // Find vertices in topological order // starting with vertices of 0 degree // and reducing degrees of adjacent. ArrayList<Integer> toposort = new ArrayList<Integer>(); for (int i = 0; i < numTasks; i++) { if (zeros.isEmpty()) return new ArrayList<Integer>(); int zero = zeros.peek(); zeros.poll(); toposort.add(zero); for (int neigh : graph.get(zero)) { if (--degrees[neigh] == 0) zeros.add(neigh); } } return toposort; } // Driver code public static void main(String[] args) { int numTasks = 4; int[][] prerequisites = { { 1, 0 }, { 2, 1 }, { 3, 2 } }; ArrayList<Integer> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { System.out.print(v.get(i) + " "); } }} // This code is contributed by Lovely Jain 0 1 2 3 Topological Sorting using DFS: In this implementation, we use DFS based algorithm for Topological Sort. CPP Java // CPP program to find Topological sorting using// DFS#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation of graph from// given set of pairs.vector<unordered_set<int> > make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // Does DFS and adds nodes to Topological Sortbool dfs(vector<unordered_set<int> >& graph, int node, vector<bool>& onpath, vector<bool>& visited, vector<int>& toposort){ if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph[node]) if (onpath[neigh] || dfs(graph, neigh, onpath, visited, toposort)) return true; toposort.push_back(node); return onpath[node] = false;} // Returns an order of tasks so that all tasks can be// finished.vector<int> findOrder(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); vector<int> toposort; vector<bool> onpath(numTasks, false), visited(numTasks, false); for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs(graph, i, onpath, visited, toposort)) return {}; reverse(toposort.begin(), toposort.end()); return toposort;} int main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); vector<int> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } return 0;} // Java program to find Topological sorting using// DFS import java.util.ArrayList;import java.util.Collections;import java.util.HashSet; public class Dfs1 { // Returns adjacency list representation of graph from // given set of pairs. static ArrayList<HashSet<Integer> > make_graph(int numTasks, int[][] prerequisites) { ArrayList<HashSet<Integer> > graph = new ArrayList(numTasks); for (int i = 0; i < numTasks; i++) graph.add(new HashSet<Integer>()); for (int[] pre : prerequisites) graph.get(pre[1]).add(pre[0]); return graph; } // Does DFS and adds nodes to Topological Sort static boolean dfs(ArrayList<HashSet<Integer> > graph, int node, boolean[] onpath, boolean[] visited, ArrayList<Integer> toposort) { if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph.get(node)) if (onpath[neigh] || dfs(graph, neigh, onpath, visited, toposort)) return true; toposort.add(node); return onpath[node] = false; } // Returns an order of tasks so that all tasks can be // finished. static ArrayList<Integer> findOrder(int numTasks, int[][] prerequisites) { ArrayList<HashSet<Integer> > graph = make_graph(numTasks, prerequisites); ArrayList<Integer> toposort = new ArrayList<Integer>(); boolean[] onpath = new boolean[numTasks]; boolean[] visited = new boolean[numTasks]; for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs(graph, i, onpath, visited, toposort)) return new ArrayList<Integer>(); Collections.reverse(toposort); return toposort; } // Driver code public static void main(String[] args) { int numTasks = 4; int[][] prerequisites = { { 1, 0 }, { 2, 1 }, { 3, 2 } }; ArrayList<Integer> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { System.out.print(v.get(i) + " "); } }} // This code is contributed by Lovely Jain 0 1 2 3 Reference: https://leetcode.com/problems/course-schedule-ii/ jainlovely450 BFS DFS Technical Scripter 2018 Topological Sorting Graph Technical Scripter DFS Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Minimum number of swaps required to sort an array m Coloring Problem | Backtracking-5
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jun, 2022" }, { "code": null, "e": 542, "s": 52, "text": "There are a total of n tasks you have to pick, labeled from 0 to n-1. Some tasks may have prerequisites tasks, for example to pick task 0 you have to first finish tasks 1, which is expressed as a pair: [0, 1] Given the total number of tasks and a list of prerequisite pairs, return the ordering of tasks you should pick to finish all tasks. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all tasks, return an empty array. Examples:" }, { "code": null, "e": 1050, "s": 542, "text": "Input: 2, [[1, 0]] Output: [0, 1] Explanation: There are a total of 2 tasks to pick. To pick task 1 you should have finished task 0. So the correct task order is [0, 1] . Input: 4, [[1, 0], [2, 0], [3, 1], [3, 2]] Output: [0, 1, 2, 3] or [0, 2, 1, 3] Explanation: There are a total of 4 tasks to pick. To pick task 3 you should have finished both tasks 1 and 2. Both tasks 1 and 2 should be pick after you finished task 0. So one correct task order is [0, 1, 2, 3]. Another correct ordering is [0, 2, 1, 3]." }, { "code": null, "e": 2340, "s": 1050, "text": "Asked In: Google, Twitter, Amazon and many more companies. Solution: We can consider this problem as a graph (related to topological sorting) problem. All tasks are nodes of the graph and if task u is a prerequisite of task v, we will add a directed edge from node u to node v. Now, this problem is equivalent to finding a topological ordering of nodes/tasks (using topological sorting) in the graph represented by prerequisites. If there is a cycle in the graph, then it is not possible to finish all tasks (because in that case there is no any topological order of tasks). Both BFS and DFS can be used for topological sorting to solve it. Since pair is inconvenient for the implementation of graph algorithms, we first transform it to a graph. If task u is a prerequisite of task v, we will add a directed edge from node u to node v. Topological Sorting using BFS Here we use Kahn’s algorithm for topological sorting. BFS uses the indegrees of each node. We will first try to find a node with 0 indegree. If we fail to do so, there must be a cycle in the graph and we return false. Otherwise we have found one. We set its indegree to be -1 to prevent from visiting it again and reduce the indegrees of all its neighbors by 1. This process will be repeated for n (number of nodes) times. " }, { "code": null, "e": 2344, "s": 2340, "text": "CPP" }, { "code": null, "e": 2349, "s": 2344, "text": "Java" }, { "code": "// CPP program to find order to process tasks// so that all tasks can be finished. This program// mainly uses Kahn's algorithm.#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation of graph from// given set of pairs.vector<unordered_set<int> > make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // Computes in-degree of every vertexvector<int> compute_indegree(vector<unordered_set<int> >& graph){ vector<int> degrees(graph.size(), 0); for (auto neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees;} // main function for topological sortingvector<int> findOrder(int numTasks, vector<pair<int, int> >& prerequisites){ // Create an adjacency list vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); // Find vertices of zero degree vector<int> degrees = compute_indegree(graph); queue<int> zeros; for (int i = 0; i < numTasks; i++) if (!degrees[i]) zeros.push(i); // Find vertices in topological order // starting with vertices of 0 degree // and reducing degrees of adjacent. vector<int> toposort; for (int i = 0; i < numTasks; i++) { if (zeros.empty()) return {}; int zero = zeros.front(); zeros.pop(); toposort.push_back(zero); for (int neigh : graph[zero]) { if (!--degrees[neigh]) zeros.push(neigh); } } return toposort;} // Driver codeint main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); vector<int> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { cout << v[i] << \" \"; } return 0;}", "e": 4428, "s": 2349, "text": null }, { "code": "// Java program to find order to process tasks// so that all tasks can be finished. This program// mainly uses Kahn's algorithm. import java.util.ArrayList;import java.util.HashSet;import java.util.LinkedList;import java.util.Queue; public class Dep { // Returns adjacency list representation of graph from // given set of pairs. static ArrayList<HashSet<Integer> > make_graph(int numTasks, int[][] prerequisites) { ArrayList<HashSet<Integer> > graph = new ArrayList<HashSet<Integer>>(numTasks); for (int i = 0; i < numTasks; i++) graph.add(new HashSet<Integer>()); for (int[] pre : prerequisites) graph.get(pre[1]).add(pre[0]); return graph; } // Computes in-degree of every vertex static int[] compute_indegree( ArrayList<HashSet<Integer> > graph) { int[] degrees = new int[graph.size()]; for (HashSet<Integer> neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees; } // main function for topological sorting static ArrayList<Integer> findOrder(int numTasks, int[][] prerequisites) { // Create an adjacency list ArrayList<HashSet<Integer> > graph = make_graph(numTasks, prerequisites); // Find vertices of zero degree int[] degrees = compute_indegree(graph); Queue<Integer> zeros = new LinkedList<Integer>(); for (int i = 0; i < numTasks; i++) if (degrees[i] == 0) zeros.add(i); // Find vertices in topological order // starting with vertices of 0 degree // and reducing degrees of adjacent. ArrayList<Integer> toposort = new ArrayList<Integer>(); for (int i = 0; i < numTasks; i++) { if (zeros.isEmpty()) return new ArrayList<Integer>(); int zero = zeros.peek(); zeros.poll(); toposort.add(zero); for (int neigh : graph.get(zero)) { if (--degrees[neigh] == 0) zeros.add(neigh); } } return toposort; } // Driver code public static void main(String[] args) { int numTasks = 4; int[][] prerequisites = { { 1, 0 }, { 2, 1 }, { 3, 2 } }; ArrayList<Integer> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { System.out.print(v.get(i) + \" \"); } }} // This code is contributed by Lovely Jain", "e": 6970, "s": 4428, "text": null }, { "code": null, "e": 6978, "s": 6970, "text": "0 1 2 3" }, { "code": null, "e": 7083, "s": 6978, "text": "Topological Sorting using DFS: In this implementation, we use DFS based algorithm for Topological Sort. " }, { "code": null, "e": 7087, "s": 7083, "text": "CPP" }, { "code": null, "e": 7092, "s": 7087, "text": "Java" }, { "code": "// CPP program to find Topological sorting using// DFS#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation of graph from// given set of pairs.vector<unordered_set<int> > make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // Does DFS and adds nodes to Topological Sortbool dfs(vector<unordered_set<int> >& graph, int node, vector<bool>& onpath, vector<bool>& visited, vector<int>& toposort){ if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph[node]) if (onpath[neigh] || dfs(graph, neigh, onpath, visited, toposort)) return true; toposort.push_back(node); return onpath[node] = false;} // Returns an order of tasks so that all tasks can be// finished.vector<int> findOrder(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); vector<int> toposort; vector<bool> onpath(numTasks, false), visited(numTasks, false); for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs(graph, i, onpath, visited, toposort)) return {}; reverse(toposort.begin(), toposort.end()); return toposort;} int main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); vector<int> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { cout << v[i] << \" \"; } return 0;}", "e": 8930, "s": 7092, "text": null }, { "code": "// Java program to find Topological sorting using// DFS import java.util.ArrayList;import java.util.Collections;import java.util.HashSet; public class Dfs1 { // Returns adjacency list representation of graph from // given set of pairs. static ArrayList<HashSet<Integer> > make_graph(int numTasks, int[][] prerequisites) { ArrayList<HashSet<Integer> > graph = new ArrayList(numTasks); for (int i = 0; i < numTasks; i++) graph.add(new HashSet<Integer>()); for (int[] pre : prerequisites) graph.get(pre[1]).add(pre[0]); return graph; } // Does DFS and adds nodes to Topological Sort static boolean dfs(ArrayList<HashSet<Integer> > graph, int node, boolean[] onpath, boolean[] visited, ArrayList<Integer> toposort) { if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph.get(node)) if (onpath[neigh] || dfs(graph, neigh, onpath, visited, toposort)) return true; toposort.add(node); return onpath[node] = false; } // Returns an order of tasks so that all tasks can be // finished. static ArrayList<Integer> findOrder(int numTasks, int[][] prerequisites) { ArrayList<HashSet<Integer> > graph = make_graph(numTasks, prerequisites); ArrayList<Integer> toposort = new ArrayList<Integer>(); boolean[] onpath = new boolean[numTasks]; boolean[] visited = new boolean[numTasks]; for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs(graph, i, onpath, visited, toposort)) return new ArrayList<Integer>(); Collections.reverse(toposort); return toposort; } // Driver code public static void main(String[] args) { int numTasks = 4; int[][] prerequisites = { { 1, 0 }, { 2, 1 }, { 3, 2 } }; ArrayList<Integer> v = findOrder(numTasks, prerequisites); for (int i = 0; i < v.size(); i++) { System.out.print(v.get(i) + \" \"); } }} // This code is contributed by Lovely Jain", "e": 11206, "s": 8930, "text": null }, { "code": null, "e": 11214, "s": 11206, "text": "0 1 2 3" }, { "code": null, "e": 11275, "s": 11214, "text": "Reference: https://leetcode.com/problems/course-schedule-ii/" }, { "code": null, "e": 11289, "s": 11275, "text": "jainlovely450" }, { "code": null, "e": 11293, "s": 11289, "text": "BFS" }, { "code": null, "e": 11297, "s": 11293, "text": "DFS" }, { "code": null, "e": 11321, "s": 11297, "text": "Technical Scripter 2018" }, { "code": null, "e": 11341, "s": 11321, "text": "Topological Sorting" }, { "code": null, "e": 11347, "s": 11341, "text": "Graph" }, { "code": null, "e": 11366, "s": 11347, "text": "Technical Scripter" }, { "code": null, "e": 11370, "s": 11366, "text": "DFS" }, { "code": null, "e": 11376, "s": 11370, "text": "Graph" }, { "code": null, "e": 11380, "s": 11376, "text": "BFS" }, { "code": null, "e": 11478, "s": 11380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11529, "s": 11478, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 11594, "s": 11529, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 11652, "s": 11594, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 11685, "s": 11652, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 11717, "s": 11685, "text": "Introduction to Data Structures" }, { "code": null, "e": 11785, "s": 11717, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 11849, "s": 11785, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11880, "s": 11849, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 11930, "s": 11880, "text": "Minimum number of swaps required to sort an array" } ]
Merge two BSTs with limited extra space
12 Apr, 2022 Given two Binary Search Trees(BST), print the elements of both BSTs in sorted form. The expected time complexity is O(m+n) where m is the number of nodes in the first tree and n is the number of nodes in the second tree. The maximum allowed auxiliary space is O(height of the first tree + height of the second tree). Examples: First BST 3 / \ 1 5 Second BST 4 / \ 2 6 Output: 1 2 3 4 5 6 First BST 8 / \ 2 10 / 1 Second BST 5 / 3 / 0 Output: 0 1 2 3 5 8 10 Source: Google interview question A similar question has been discussed earlier. Let us first discuss the already discussed methods of the previous post which was for Balanced BSTs. Method 1 can be applied here also, but the time complexity will be O(n^2) in the worst case. Method 2 can also be applied here, but the extra space required will be O(n) which violates the constraint given in this question. Method 3 can be applied here but step 3 of method 3 can’t be done in O(n) for an unbalanced BST.Thanks to Kumar for suggesting the following solution.The idea is to use iterative inorder traversal. We use two auxiliary stacks for two BSTs. Since we need to print the elements in the sorted form, whenever we get a smaller element from any of the trees, we print it. If the element is greater, then we push it back to stack for the next iteration. C++ C Java Python 3 C# Javascript #include <bits/stdc++.h>using namespace std; // Structure of a BST Nodeclass node{ public: int data; node *left; node *right;}; //.................... START OF STACK RELATED STUFF....................// A stack nodeclass snode{ public: node *t; snode *next;}; // Function to add an element k to stackvoid push(snode **s, node *k){ snode *tmp = new snode(); //perform memory check here tmp->t = k; tmp->next = *s; (*s) = tmp;} // Function to pop an element t from stacknode *pop(snode **s){ node *t; snode *st; st=*s; (*s) = (*s)->next; t = st->t; free(st); return t;} // Function to check whether the stack is empty or notint isEmpty(snode *s){ if (s == NULL ) return 1; return 0;}//.................... END OF STACK RELATED STUFF.................... /* Utility function to create a new Binary Tree node */node* newNode (int data){ node *temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* A utility function to print Inorder traversal of a Binary Tree */void inorder(node *root){ if (root != NULL) { inorder(root->left); cout<<root->data<<" "; inorder(root->right); }} // The function to print data of two BSTs in sorted ordervoid merge(node *root1, node *root2){ // s1 is stack to hold nodes of first BST snode *s1 = NULL; // Current node of first BST node *current1 = root1; // s2 is stack to hold nodes of second BST snode *s2 = NULL; // Current node of second BST node *current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == NULL) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == NULL) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != NULL || !isEmpty(s1) || current2 != NULL || !isEmpty(s2)) { // Following steps follow iterative Inorder Traversal if (current1 != NULL || current2 != NULL ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != NULL) { push(&s1, current1); current1 = current1->left; } if (current2 != NULL) { push(&s2, current2); current2 = current2->left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (isEmpty(s1)) { while (!isEmpty(s2)) { current2 = pop (&s2); current2->left = NULL; inorder(current2); } return ; } if (isEmpty(s2)) { while (!isEmpty(s1)) { current1 = pop (&s1); current1->left = NULL; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = pop(&s1); current2 = pop(&s2); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1->data < current2->data) { cout<<current1->data<<" "; current1 = current1->right; push(&s2, current2); current2 = NULL; } else { cout<<current2->data<<" "; current2 = current2->right; push(&s1, current1); current1 = NULL; } } }} /* Driver program to test above functions */int main(){ node *root1 = NULL, *root2 = NULL; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted nodes of both trees merge(root1, root2); return 0;} //This code is contributed by rathbhupendra #include<stdio.h>#include<stdlib.h> // Structure of a BST Nodestruct node{ int data; struct node *left; struct node *right;}; //.................... START OF STACK RELATED STUFF....................// A stack nodestruct snode{ struct node *t; struct snode *next;}; // Function to add an element k to stackvoid push(struct snode **s, struct node *k){ struct snode *tmp = (struct snode *) malloc(sizeof(struct snode)); //perform memory check here tmp->t = k; tmp->next = *s; (*s) = tmp;} // Function to pop an element t from stackstruct node *pop(struct snode **s){ struct node *t; struct snode *st; st=*s; (*s) = (*s)->next; t = st->t; free(st); return t;} // Function to check whether the stack is empty or notint isEmpty(struct snode *s){ if (s == NULL ) return 1; return 0;}//.................... END OF STACK RELATED STUFF.................... /* Utility function to create a new Binary Tree node */struct node* newNode (int data){ struct node *temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* A utility function to print Inorder traversal of a Binary Tree */void inorder(struct node *root){ if (root != NULL) { inorder(root->left); printf("%d ", root->data); inorder(root->right); }} // The function to print data of two BSTs in sorted ordervoid merge(struct node *root1, struct node *root2){ // s1 is stack to hold nodes of first BST struct snode *s1 = NULL; // Current node of first BST struct node *current1 = root1; // s2 is stack to hold nodes of second BST struct snode *s2 = NULL; // Current node of second BST struct node *current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == NULL) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == NULL) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != NULL || !isEmpty(s1) || current2 != NULL || !isEmpty(s2)) { // Following steps follow iterative Inorder Traversal if (current1 != NULL || current2 != NULL ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != NULL) { push(&s1, current1); current1 = current1->left; } if (current2 != NULL) { push(&s2, current2); current2 = current2->left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (isEmpty(s1)) { while (!isEmpty(s2)) { current2 = pop (&s2); current2->left = NULL; inorder(current2); } return ; } if (isEmpty(s2)) { while (!isEmpty(s1)) { current1 = pop (&s1); current1->left = NULL; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = pop(&s1); current2 = pop(&s2); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1->data < current2->data) { printf("%d ", current1->data); current1 = current1->right; push(&s2, current2); current2 = NULL; } else { printf("%d ", current2->data); current2 = current2->right; push(&s1, current1); current1 = NULL; } } }} /* Driver program to test above functions */int main(){ struct node *root1 = NULL, *root2 = NULL; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted nodes of both trees merge(root1, root2); return 0;} public class Merge2BST{ /* A utility function to print Inorder traversal of a Binary Tree */ static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } } // The function to print data of two BSTs in sorted order static void merge(Node root1, Node root2) { // s1 is stack to hold nodes of first BST SNode s1 = new SNode(); // Current node of first BST Node current1 = root1; // s2 is stack to hold nodes of second BST SNode s2 = new SNode(); // Current node of second BST Node current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == null) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == null) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != null || !s1.isEmpty() || current2 != null || !s2.isEmpty()) { // Following steps follow iterative Inorder Traversal if (current1 != null || current2 != null ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != null) { s1.push( current1); current1 = current1.left; } if (current2 != null) { s2.push( current2); current2 = current2.left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (s1.isEmpty()) { while (!s2.isEmpty()) { current2 = s2.pop (); current2.left = null; inorder(current2); } return ; } if (s2.isEmpty()) { while (!s1.isEmpty()) { current1 = s1.pop (); current1.left = null; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = s1.pop(); current2 = s2.pop(); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1.data < current2.data) { System.out.print(current1.data + " "); current1 = current1.right; s2.push( current2); current2 = null; } else { System.out.print(current2.data + " "); current2 = current2.right; s1.push( current1); current1 = null; } } } System.out.println(s1.t); System.out.println(s2.t); } /* Driver code */ public static void main(String[]args) { Node root1 = null, root2 = null; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = new Node(3) ; root1.left = new Node(1); root1.right = new Node(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = new Node(4) ; root2.left = new Node(2); root2.right = new Node(6); // Print sorted nodes of both trees merge(root1, root2); }} // Structure of a BST Nodeclass Node{ int data; Node left; Node right; public Node(int data) { // TODO Auto-generated constructor stub this.data = data; this.left = null; this.right = null; }} // A stack nodeclass SNode{ SNode head; Node t; SNode next; // Function to add an element k to stack void push(Node k) { SNode tmp = new SNode(); // Perform memory check here tmp.t = k; tmp.next = this.head; this.head = tmp; } // Function to pop an element t from stack Node pop() { SNode st; st = this.head; head = head.next; return st.t; } // Function to check whether the stack is empty or not boolean isEmpty( ) { if (this.head == null ) return true; return false; }} // This code is contributed by nidhisebastian008 # Class to create a new Tree Nodeclass newNode: def __init__(self, data: int): self.data = data self.left = None self.right = None def inorder(root: newNode): if root: inorder(root.left) print(root.data, end=" ") inorder(root.right) def merge(root1: newNode, root2: newNode): # s1 is stack to hold nodes of first BST s1 = [] # Current node of first BST current1 = root1 # s2 is stack to hold nodes of first BST s2 = [] # Current node of second BST current2 = root2 # If first BST is empty then the output is the # inorder traversal of the second BST if not root1: return inorder(root2) # If the second BST is empty then the output is the # inorder traversal of the first BST if not root2: return inorder(root1) # Run the loop while there are nodes not yet printed. # The nodes may be in stack(explored, but not printed) # or may be not yet explored while current1 or s1 or current2 or s2: # Following steps follow iterative Inorder Traversal if current1 or current2: # Reach the leftmost node of both BSTs and push ancestors of # leftmost nodes to stack s1 and s2 respectively if current1: s1.append(current1) current1 = current1.left if current2: s2.append(current2) current2 = current2.left else: # If we reach a NULL node and either of the stacks is empty, # then one tree is exhausted, print the other tree if not s1: while s2: current2 = s2.pop() current2.left = None inorder(current2) return if not s2: while s1: current1 = s1.pop() current1.left = None inorder(current1) return # Pop an element from both stacks and compare the # popped elements current1 = s1.pop() current2 = s2.pop() # If element of first tree is smaller, then print it # and push the right subtree. If the element is larger, # then we push it back to the corresponding stack. if current1.data < current2.data: print(current1.data, end=" ") current1 = current1.right s2.append(current2) current2 = None else: print(current2.data, end=" ") current2 = current2.right s1.append(current1) current1 = None # Driver code def main(): # Let us create the following tree as first tree # 3 # / \ # 1 5 root1 = newNode(3) root1.left = newNode(1) root1.right = newNode(5) # Let us create the following tree as second tree # 4 # / \ # 2 6 # root2 = newNode(4) root2.left = newNode(2) root2.right = newNode(6) merge(root1, root2) if __name__ == "__main__": main() # This code is contributed by Koushik Reddy Bukkasamudram // C# program to implement the// above approachusing System;class Merge2BST{ /* A utility function to print Inorder traversal of a Binary Tree */static void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.data + " "); inorder(root.right); }} // The function to print data// of two BSTs in sorted orderstatic void merge(Node root1, Node root2){ // s1 is stack to hold nodes // of first BST SNode s1 = new SNode(); // Current node of first BST Node current1 = root1; // s2 is stack to hold nodes // of second BST SNode s2 = new SNode(); // Current node of second BST Node current2 = root2; // If first BST is empty, then // output is inorder traversal // of second BST if (root1 == null) { inorder(root2); return; } // If second BST is empty, // then output is inorder // traversal of first BST if (root2 == null) { inorder(root1); return ; } // Run the loop while there // are nodes not yet printed. // The nodes may be in stack // (explored, but not printed) // or may be not yet explored while (current1 != null || !s1.isEmpty() || current2 != null || !s2.isEmpty()) { // Following steps follow // iterative Inorder Traversal if (current1 != null || current2 != null) { // Reach the leftmost node of // both BSTs and push ancestors // of leftmost nodes to stack // s1 and s2 respectively if (current1 != null) { s1.push(current1); current1 = current1.left; } if (current2 != null) { s2.push(current2); current2 = current2.left; } } else { // If we reach a NULL node and // either of the stacks is empty, // then one tree is exhausted, // print the other tree if (s1.isEmpty()) { while (!s2.isEmpty()) { current2 = s2.pop (); current2.left = null; inorder(current2); } return; } if (s2.isEmpty()) { while (!s1.isEmpty()) { current1 = s1.pop (); current1.left = null; inorder(current1); } return; } // Pop an element from both // stacks and compare the // popped elements current1 = s1.pop(); current2 = s2.pop(); // If element of first tree is // smaller, then print it // and push the right subtree. // If the element is larger, // then we push it back to the // corresponding stack. if (current1.data < current2.data) { Console.Write(current1.data + " "); current1 = current1.right; s2.push( current2); current2 = null; } else { Console.Write(current2.data + " "); current2 = current2.right; s1.push( current1); current1 = null; } } } Console.Write(s1.t + "\n"); Console.Write(s2.t + "\n");} // Driver codepublic static void Main(string[]args){ Node root1 = null, root2 = null; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = new Node(3) ; root1.left = new Node(1); root1.right = new Node(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = new Node(4) ; root2.left = new Node(2); root2.right = new Node(6); // Print sorted nodes of // both trees merge(root1, root2);}} // Structure of a BST Nodeclass Node{ public int data;public Node left;public Node right; public Node(int data){ // TODO Auto-generated // constructor stub this.data = data; this.left = null; this.right = null;}} // A stack nodeclass SNode{ SNode head;public Node t;SNode next; // Function to add an element// k to stackpublic void push(Node k){ SNode tmp = new SNode(); // Perform memory check here tmp.t = k; tmp.next = this.head; this.head = tmp;} // Function to pop an element// t from stackpublic Node pop(){ SNode st; st = this.head; head = head.next; return st.t;} // Function to check whether// the stack is empty or notpublic bool isEmpty(){ if (this.head == null ) return true; return false;}} // This code is contributed by Rutvik_56 <script> // JavaScript program to implement the // above approach // Structure of a BST Node class Node { constructor(data) { // TODO Auto-generated // constructor stub this.data = data; this.left = null; this.right = null; } } // A stack node class SNode { constructor() { this.head = null; this.t = null; this.next = null; } // Function to add an element // k to stack push(k) { var tmp = new SNode(); // Perform memory check here tmp.t = k; tmp.next = this.head; this.head = tmp; } // Function to pop an element // t from stack pop() { var st; st = this.head; this.head = this.head.next; return st.t; } // Function to check whether // the stack is empty or not isEmpty() { if (this.head == null) return true; return false; } } /* A utility function to print Inorder traversal of a Binary Tree */ function inorder(root) { if (root != null) { inorder(root.left); document.write(root.data + " "); inorder(root.right); } } // The function to print data // of two BSTs in sorted order function merge(root1, root2) { // s1 is stack to hold nodes // of first BST var s1 = new SNode(); // Current node of first BST var current1 = root1; // s2 is stack to hold nodes // of second BST var s2 = new SNode(); // Current node of second BST var current2 = root2; // If first BST is empty, then // output is inorder traversal // of second BST if (root1 == null) { inorder(root2); return; } // If second BST is empty, // then output is inorder // traversal of first BST if (root2 == null) { inorder(root1); return; } // Run the loop while there // are nodes not yet printed. // The nodes may be in stack // (explored, but not printed) // or may be not yet explored while ( current1 != null || !s1.isEmpty() || current2 != null || !s2.isEmpty() ) { // Following steps follow // iterative Inorder Traversal if (current1 != null || current2 != null) { // Reach the leftmost node of // both BSTs and push ancestors // of leftmost nodes to stack // s1 and s2 respectively if (current1 != null) { s1.push(current1); current1 = current1.left; } if (current2 != null) { s2.push(current2); current2 = current2.left; } } else { // If we reach a NULL node and // either of the stacks is empty, // then one tree is exhausted, // print the other tree if (s1.isEmpty()) { while (!s2.isEmpty()) { current2 = s2.pop(); current2.left = null; inorder(current2); } return; } if (s2.isEmpty()) { while (!s1.isEmpty()) { current1 = s1.pop(); current1.left = null; inorder(current1); } return; } // Pop an element from both // stacks and compare the // popped elements current1 = s1.pop(); current2 = s2.pop(); // If element of first tree is // smaller, then print it // and push the right subtree. // If the element is larger, // then we push it back to the // corresponding stack. if (current1.data < current2.data) { document.write(current1.data + " "); current1 = current1.right; s2.push(current2); current2 = null; } else { document.write(current2.data + " "); current2 = current2.right; s1.push(current1); current1 = null; } } } document.write(s1.t + "<br>"); document.write(s2.t + "<br>"); } // Driver code var root1 = null, root2 = null; /* Let us create the following tree as first tree 3 / \ 1 5*/ root1 = new Node(3); root1.left = new Node(1); root1.right = new Node(5); /* Let us create the following tree as second tree 4 / \ 2 6*/ root2 = new Node(4); root2.left = new Node(2); root2.right = new Node(6); // Print sorted nodes of // both trees merge(root1, root2); </script> 1 2 3 4 5 6 Time Complexity: O(m+n) Auxiliary Space: O(height of the first tree + height of the second tree) Another simpler version of solving the problem using two stacks is given below :- In this method I am using inbuilt stack present in the STL library so as to get rid of the implementation of the stack part of code that has done in the previous implementation. Step 1 :- Consider two stacks s1 and s2 which stores the element of the two trees. Step 2 :- Store the left view value of a tree1 in s1 and of tree2 in s2. Step 3 :- Compare the top values present in the stack and push the value accordingly in the result vector. Case 1 :- if s2 is empty then pop s1 and put the popped node value in the answer vector else if both s1 and s2 are not empty then compare their top nodes value if s1.top()->val <= s2.top()->val then in this case push the s1.top()->val in the result vector and push its right child in the stack s1 Case 2 :- if s1 is empty then pop s2 and put the popped node value in the answer vector else if both s1 and s2 are not empty then compare their top nodes value if s2.top()->val >= s1.top()->val then in this case push the s2.top()->val in the result vector and push its right child in the stack s2 Step 4 :- Continue step 3 until both the stacks get empty. Below is the implementation of the above logic :- C++ #include <bits/stdc++.h>using namespace std; // Structure of a BST Nodeclass Node {public: int val; Node* left; Node* right;}; /* Utility function to create a new Binary Tree Node */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = nullptr; temp->right = nullptr; return temp;} vector<int> mergeTwoBST(Node* root1, Node* root2){ vector<int> res; stack<Node*> s1, s2; while (root1 || root2 || !s1.empty() || !s2.empty()) { while (root1) { s1.push(root1); root1 = root1->left; } while (root2) { s2.push(root2); root2 = root2->left; } // Step 3 Case 1:- if (s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)) { root1 = s1.top(); s1.pop(); res.push_back(root1->val); root1 = root1->right; } // Step 3 case 2 :- else { root2 = s2.top(); s2.pop(); res.push_back(root2->val); root2 = root2->right; } } return res;} /* Driver program to test above functions */int main(){ Node *root1 = nullptr, *root2 = nullptr; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted Nodes of both trees vector<int> ans = mergeTwoBST(root1, root2); for (auto it : ans) cout << it << " "; return 0;} // This code is contributed by Aditya kumar (adityakumar129) 1 2 3 4 5 6 Time Complexity: O(m+n) Auxiliary Space: O(height of the first tree + height of the second tree) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rathbhupendra koushikrbukkasamudram nidhisebastian008 rutvik_56 saurabh1990aror rdtank adnanirshad158 gabaa406 sumitgumber28 surinderdawra388 adityakumar129 Amazon Google Merge Sort Microsoft Binary Search Tree Tree Amazon Microsoft Google Binary Search Tree Tree Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. A program to check if a binary tree is BST or not Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Optimal Binary Search Tree | DP-24 Sorted Array to Balanced BST Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Introduction to Data Structures Introduction to Tree Data Structure
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Apr, 2022" }, { "code": null, "e": 379, "s": 52, "text": "Given two Binary Search Trees(BST), print the elements of both BSTs in sorted form. The expected time complexity is O(m+n) where m is the number of nodes in the first tree and n is the number of nodes in the second tree. The maximum allowed auxiliary space is O(height of the first tree + height of the second tree). Examples:" }, { "code": null, "e": 638, "s": 379, "text": "First BST \n 3\n / \\\n 1 5\nSecond BST\n 4\n / \\\n2 6\nOutput: 1 2 3 4 5 6\n\n\nFirst BST \n 8\n / \\\n 2 10\n /\n 1\nSecond BST \n 5\n / \n 3 \n /\n 0\nOutput: 0 1 2 3 5 8 10 " }, { "code": null, "e": 672, "s": 638, "text": "Source: Google interview question" }, { "code": null, "e": 1493, "s": 672, "text": "A similar question has been discussed earlier. Let us first discuss the already discussed methods of the previous post which was for Balanced BSTs. Method 1 can be applied here also, but the time complexity will be O(n^2) in the worst case. Method 2 can also be applied here, but the extra space required will be O(n) which violates the constraint given in this question. Method 3 can be applied here but step 3 of method 3 can’t be done in O(n) for an unbalanced BST.Thanks to Kumar for suggesting the following solution.The idea is to use iterative inorder traversal. We use two auxiliary stacks for two BSTs. Since we need to print the elements in the sorted form, whenever we get a smaller element from any of the trees, we print it. If the element is greater, then we push it back to stack for the next iteration. " }, { "code": null, "e": 1497, "s": 1493, "text": "C++" }, { "code": null, "e": 1499, "s": 1497, "text": "C" }, { "code": null, "e": 1504, "s": 1499, "text": "Java" }, { "code": null, "e": 1513, "s": 1504, "text": "Python 3" }, { "code": null, "e": 1516, "s": 1513, "text": "C#" }, { "code": null, "e": 1527, "s": 1516, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Structure of a BST Nodeclass node{ public: int data; node *left; node *right;}; //.................... START OF STACK RELATED STUFF....................// A stack nodeclass snode{ public: node *t; snode *next;}; // Function to add an element k to stackvoid push(snode **s, node *k){ snode *tmp = new snode(); //perform memory check here tmp->t = k; tmp->next = *s; (*s) = tmp;} // Function to pop an element t from stacknode *pop(snode **s){ node *t; snode *st; st=*s; (*s) = (*s)->next; t = st->t; free(st); return t;} // Function to check whether the stack is empty or notint isEmpty(snode *s){ if (s == NULL ) return 1; return 0;}//.................... END OF STACK RELATED STUFF.................... /* Utility function to create a new Binary Tree node */node* newNode (int data){ node *temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* A utility function to print Inorder traversal of a Binary Tree */void inorder(node *root){ if (root != NULL) { inorder(root->left); cout<<root->data<<\" \"; inorder(root->right); }} // The function to print data of two BSTs in sorted ordervoid merge(node *root1, node *root2){ // s1 is stack to hold nodes of first BST snode *s1 = NULL; // Current node of first BST node *current1 = root1; // s2 is stack to hold nodes of second BST snode *s2 = NULL; // Current node of second BST node *current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == NULL) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == NULL) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != NULL || !isEmpty(s1) || current2 != NULL || !isEmpty(s2)) { // Following steps follow iterative Inorder Traversal if (current1 != NULL || current2 != NULL ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != NULL) { push(&s1, current1); current1 = current1->left; } if (current2 != NULL) { push(&s2, current2); current2 = current2->left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (isEmpty(s1)) { while (!isEmpty(s2)) { current2 = pop (&s2); current2->left = NULL; inorder(current2); } return ; } if (isEmpty(s2)) { while (!isEmpty(s1)) { current1 = pop (&s1); current1->left = NULL; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = pop(&s1); current2 = pop(&s2); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1->data < current2->data) { cout<<current1->data<<\" \"; current1 = current1->right; push(&s2, current2); current2 = NULL; } else { cout<<current2->data<<\" \"; current2 = current2->right; push(&s1, current1); current1 = NULL; } } }} /* Driver program to test above functions */int main(){ node *root1 = NULL, *root2 = NULL; /* Let us create the following tree as first tree 3 / \\ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \\ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted nodes of both trees merge(root1, root2); return 0;} //This code is contributed by rathbhupendra", "e": 6249, "s": 1527, "text": null }, { "code": "#include<stdio.h>#include<stdlib.h> // Structure of a BST Nodestruct node{ int data; struct node *left; struct node *right;}; //.................... START OF STACK RELATED STUFF....................// A stack nodestruct snode{ struct node *t; struct snode *next;}; // Function to add an element k to stackvoid push(struct snode **s, struct node *k){ struct snode *tmp = (struct snode *) malloc(sizeof(struct snode)); //perform memory check here tmp->t = k; tmp->next = *s; (*s) = tmp;} // Function to pop an element t from stackstruct node *pop(struct snode **s){ struct node *t; struct snode *st; st=*s; (*s) = (*s)->next; t = st->t; free(st); return t;} // Function to check whether the stack is empty or notint isEmpty(struct snode *s){ if (s == NULL ) return 1; return 0;}//.................... END OF STACK RELATED STUFF.................... /* Utility function to create a new Binary Tree node */struct node* newNode (int data){ struct node *temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* A utility function to print Inorder traversal of a Binary Tree */void inorder(struct node *root){ if (root != NULL) { inorder(root->left); printf(\"%d \", root->data); inorder(root->right); }} // The function to print data of two BSTs in sorted ordervoid merge(struct node *root1, struct node *root2){ // s1 is stack to hold nodes of first BST struct snode *s1 = NULL; // Current node of first BST struct node *current1 = root1; // s2 is stack to hold nodes of second BST struct snode *s2 = NULL; // Current node of second BST struct node *current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == NULL) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == NULL) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != NULL || !isEmpty(s1) || current2 != NULL || !isEmpty(s2)) { // Following steps follow iterative Inorder Traversal if (current1 != NULL || current2 != NULL ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != NULL) { push(&s1, current1); current1 = current1->left; } if (current2 != NULL) { push(&s2, current2); current2 = current2->left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (isEmpty(s1)) { while (!isEmpty(s2)) { current2 = pop (&s2); current2->left = NULL; inorder(current2); } return ; } if (isEmpty(s2)) { while (!isEmpty(s1)) { current1 = pop (&s1); current1->left = NULL; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = pop(&s1); current2 = pop(&s2); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1->data < current2->data) { printf(\"%d \", current1->data); current1 = current1->right; push(&s2, current2); current2 = NULL; } else { printf(\"%d \", current2->data); current2 = current2->right; push(&s1, current1); current1 = NULL; } } }} /* Driver program to test above functions */int main(){ struct node *root1 = NULL, *root2 = NULL; /* Let us create the following tree as first tree 3 / \\ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \\ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted nodes of both trees merge(root1, root2); return 0;}", "e": 11155, "s": 6249, "text": null }, { "code": "public class Merge2BST{ /* A utility function to print Inorder traversal of a Binary Tree */ static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + \" \"); inorder(root.right); } } // The function to print data of two BSTs in sorted order static void merge(Node root1, Node root2) { // s1 is stack to hold nodes of first BST SNode s1 = new SNode(); // Current node of first BST Node current1 = root1; // s2 is stack to hold nodes of second BST SNode s2 = new SNode(); // Current node of second BST Node current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == null) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == null) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != null || !s1.isEmpty() || current2 != null || !s2.isEmpty()) { // Following steps follow iterative Inorder Traversal if (current1 != null || current2 != null ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != null) { s1.push( current1); current1 = current1.left; } if (current2 != null) { s2.push( current2); current2 = current2.left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (s1.isEmpty()) { while (!s2.isEmpty()) { current2 = s2.pop (); current2.left = null; inorder(current2); } return ; } if (s2.isEmpty()) { while (!s1.isEmpty()) { current1 = s1.pop (); current1.left = null; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = s1.pop(); current2 = s2.pop(); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1.data < current2.data) { System.out.print(current1.data + \" \"); current1 = current1.right; s2.push( current2); current2 = null; } else { System.out.print(current2.data + \" \"); current2 = current2.right; s1.push( current1); current1 = null; } } } System.out.println(s1.t); System.out.println(s2.t); } /* Driver code */ public static void main(String[]args) { Node root1 = null, root2 = null; /* Let us create the following tree as first tree 3 / \\ 1 5 */ root1 = new Node(3) ; root1.left = new Node(1); root1.right = new Node(5); /* Let us create the following tree as second tree 4 / \\ 2 6 */ root2 = new Node(4) ; root2.left = new Node(2); root2.right = new Node(6); // Print sorted nodes of both trees merge(root1, root2); }} // Structure of a BST Nodeclass Node{ int data; Node left; Node right; public Node(int data) { // TODO Auto-generated constructor stub this.data = data; this.left = null; this.right = null; }} // A stack nodeclass SNode{ SNode head; Node t; SNode next; // Function to add an element k to stack void push(Node k) { SNode tmp = new SNode(); // Perform memory check here tmp.t = k; tmp.next = this.head; this.head = tmp; } // Function to pop an element t from stack Node pop() { SNode st; st = this.head; head = head.next; return st.t; } // Function to check whether the stack is empty or not boolean isEmpty( ) { if (this.head == null ) return true; return false; }} // This code is contributed by nidhisebastian008", "e": 16544, "s": 11155, "text": null }, { "code": "# Class to create a new Tree Nodeclass newNode: def __init__(self, data: int): self.data = data self.left = None self.right = None def inorder(root: newNode): if root: inorder(root.left) print(root.data, end=\" \") inorder(root.right) def merge(root1: newNode, root2: newNode): # s1 is stack to hold nodes of first BST s1 = [] # Current node of first BST current1 = root1 # s2 is stack to hold nodes of first BST s2 = [] # Current node of second BST current2 = root2 # If first BST is empty then the output is the # inorder traversal of the second BST if not root1: return inorder(root2) # If the second BST is empty then the output is the # inorder traversal of the first BST if not root2: return inorder(root1) # Run the loop while there are nodes not yet printed. # The nodes may be in stack(explored, but not printed) # or may be not yet explored while current1 or s1 or current2 or s2: # Following steps follow iterative Inorder Traversal if current1 or current2: # Reach the leftmost node of both BSTs and push ancestors of # leftmost nodes to stack s1 and s2 respectively if current1: s1.append(current1) current1 = current1.left if current2: s2.append(current2) current2 = current2.left else: # If we reach a NULL node and either of the stacks is empty, # then one tree is exhausted, print the other tree if not s1: while s2: current2 = s2.pop() current2.left = None inorder(current2) return if not s2: while s1: current1 = s1.pop() current1.left = None inorder(current1) return # Pop an element from both stacks and compare the # popped elements current1 = s1.pop() current2 = s2.pop() # If element of first tree is smaller, then print it # and push the right subtree. If the element is larger, # then we push it back to the corresponding stack. if current1.data < current2.data: print(current1.data, end=\" \") current1 = current1.right s2.append(current2) current2 = None else: print(current2.data, end=\" \") current2 = current2.right s1.append(current1) current1 = None # Driver code def main(): # Let us create the following tree as first tree # 3 # / \\ # 1 5 root1 = newNode(3) root1.left = newNode(1) root1.right = newNode(5) # Let us create the following tree as second tree # 4 # / \\ # 2 6 # root2 = newNode(4) root2.left = newNode(2) root2.right = newNode(6) merge(root1, root2) if __name__ == \"__main__\": main() # This code is contributed by Koushik Reddy Bukkasamudram", "e": 19724, "s": 16544, "text": null }, { "code": "// C# program to implement the// above approachusing System;class Merge2BST{ /* A utility function to print Inorder traversal of a Binary Tree */static void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.data + \" \"); inorder(root.right); }} // The function to print data// of two BSTs in sorted orderstatic void merge(Node root1, Node root2){ // s1 is stack to hold nodes // of first BST SNode s1 = new SNode(); // Current node of first BST Node current1 = root1; // s2 is stack to hold nodes // of second BST SNode s2 = new SNode(); // Current node of second BST Node current2 = root2; // If first BST is empty, then // output is inorder traversal // of second BST if (root1 == null) { inorder(root2); return; } // If second BST is empty, // then output is inorder // traversal of first BST if (root2 == null) { inorder(root1); return ; } // Run the loop while there // are nodes not yet printed. // The nodes may be in stack // (explored, but not printed) // or may be not yet explored while (current1 != null || !s1.isEmpty() || current2 != null || !s2.isEmpty()) { // Following steps follow // iterative Inorder Traversal if (current1 != null || current2 != null) { // Reach the leftmost node of // both BSTs and push ancestors // of leftmost nodes to stack // s1 and s2 respectively if (current1 != null) { s1.push(current1); current1 = current1.left; } if (current2 != null) { s2.push(current2); current2 = current2.left; } } else { // If we reach a NULL node and // either of the stacks is empty, // then one tree is exhausted, // print the other tree if (s1.isEmpty()) { while (!s2.isEmpty()) { current2 = s2.pop (); current2.left = null; inorder(current2); } return; } if (s2.isEmpty()) { while (!s1.isEmpty()) { current1 = s1.pop (); current1.left = null; inorder(current1); } return; } // Pop an element from both // stacks and compare the // popped elements current1 = s1.pop(); current2 = s2.pop(); // If element of first tree is // smaller, then print it // and push the right subtree. // If the element is larger, // then we push it back to the // corresponding stack. if (current1.data < current2.data) { Console.Write(current1.data + \" \"); current1 = current1.right; s2.push( current2); current2 = null; } else { Console.Write(current2.data + \" \"); current2 = current2.right; s1.push( current1); current1 = null; } } } Console.Write(s1.t + \"\\n\"); Console.Write(s2.t + \"\\n\");} // Driver codepublic static void Main(string[]args){ Node root1 = null, root2 = null; /* Let us create the following tree as first tree 3 / \\ 1 5 */ root1 = new Node(3) ; root1.left = new Node(1); root1.right = new Node(5); /* Let us create the following tree as second tree 4 / \\ 2 6 */ root2 = new Node(4) ; root2.left = new Node(2); root2.right = new Node(6); // Print sorted nodes of // both trees merge(root1, root2);}} // Structure of a BST Nodeclass Node{ public int data;public Node left;public Node right; public Node(int data){ // TODO Auto-generated // constructor stub this.data = data; this.left = null; this.right = null;}} // A stack nodeclass SNode{ SNode head;public Node t;SNode next; // Function to add an element// k to stackpublic void push(Node k){ SNode tmp = new SNode(); // Perform memory check here tmp.t = k; tmp.next = this.head; this.head = tmp;} // Function to pop an element// t from stackpublic Node pop(){ SNode st; st = this.head; head = head.next; return st.t;} // Function to check whether// the stack is empty or notpublic bool isEmpty(){ if (this.head == null ) return true; return false;}} // This code is contributed by Rutvik_56", "e": 24012, "s": 19724, "text": null }, { "code": "<script> // JavaScript program to implement the // above approach // Structure of a BST Node class Node { constructor(data) { // TODO Auto-generated // constructor stub this.data = data; this.left = null; this.right = null; } } // A stack node class SNode { constructor() { this.head = null; this.t = null; this.next = null; } // Function to add an element // k to stack push(k) { var tmp = new SNode(); // Perform memory check here tmp.t = k; tmp.next = this.head; this.head = tmp; } // Function to pop an element // t from stack pop() { var st; st = this.head; this.head = this.head.next; return st.t; } // Function to check whether // the stack is empty or not isEmpty() { if (this.head == null) return true; return false; } } /* A utility function to print Inorder traversal of a Binary Tree */ function inorder(root) { if (root != null) { inorder(root.left); document.write(root.data + \" \"); inorder(root.right); } } // The function to print data // of two BSTs in sorted order function merge(root1, root2) { // s1 is stack to hold nodes // of first BST var s1 = new SNode(); // Current node of first BST var current1 = root1; // s2 is stack to hold nodes // of second BST var s2 = new SNode(); // Current node of second BST var current2 = root2; // If first BST is empty, then // output is inorder traversal // of second BST if (root1 == null) { inorder(root2); return; } // If second BST is empty, // then output is inorder // traversal of first BST if (root2 == null) { inorder(root1); return; } // Run the loop while there // are nodes not yet printed. // The nodes may be in stack // (explored, but not printed) // or may be not yet explored while ( current1 != null || !s1.isEmpty() || current2 != null || !s2.isEmpty() ) { // Following steps follow // iterative Inorder Traversal if (current1 != null || current2 != null) { // Reach the leftmost node of // both BSTs and push ancestors // of leftmost nodes to stack // s1 and s2 respectively if (current1 != null) { s1.push(current1); current1 = current1.left; } if (current2 != null) { s2.push(current2); current2 = current2.left; } } else { // If we reach a NULL node and // either of the stacks is empty, // then one tree is exhausted, // print the other tree if (s1.isEmpty()) { while (!s2.isEmpty()) { current2 = s2.pop(); current2.left = null; inorder(current2); } return; } if (s2.isEmpty()) { while (!s1.isEmpty()) { current1 = s1.pop(); current1.left = null; inorder(current1); } return; } // Pop an element from both // stacks and compare the // popped elements current1 = s1.pop(); current2 = s2.pop(); // If element of first tree is // smaller, then print it // and push the right subtree. // If the element is larger, // then we push it back to the // corresponding stack. if (current1.data < current2.data) { document.write(current1.data + \" \"); current1 = current1.right; s2.push(current2); current2 = null; } else { document.write(current2.data + \" \"); current2 = current2.right; s1.push(current1); current1 = null; } } } document.write(s1.t + \"<br>\"); document.write(s2.t + \"<br>\"); } // Driver code var root1 = null, root2 = null; /* Let us create the following tree as first tree 3 / \\ 1 5*/ root1 = new Node(3); root1.left = new Node(1); root1.right = new Node(5); /* Let us create the following tree as second tree 4 / \\ 2 6*/ root2 = new Node(4); root2.left = new Node(2); root2.right = new Node(6); // Print sorted nodes of // both trees merge(root1, root2); </script>", "e": 29059, "s": 24012, "text": null }, { "code": null, "e": 29072, "s": 29059, "text": "1 2 3 4 5 6 " }, { "code": null, "e": 29169, "s": 29072, "text": "Time Complexity: O(m+n) Auxiliary Space: O(height of the first tree + height of the second tree)" }, { "code": null, "e": 29252, "s": 29169, "text": "Another simpler version of solving the problem using two stacks is given below :- " }, { "code": null, "e": 29430, "s": 29252, "text": "In this method I am using inbuilt stack present in the STL library so as to get rid of the implementation of the stack part of code that has done in the previous implementation." }, { "code": null, "e": 29513, "s": 29430, "text": "Step 1 :- Consider two stacks s1 and s2 which stores the element of the two trees." }, { "code": null, "e": 29586, "s": 29513, "text": "Step 2 :- Store the left view value of a tree1 in s1 and of tree2 in s2." }, { "code": null, "e": 29693, "s": 29586, "text": "Step 3 :- Compare the top values present in the stack and push the value accordingly in the result vector." }, { "code": null, "e": 30016, "s": 29693, "text": "Case 1 :- if s2 is empty then pop s1 and put the popped node value in the answer vector else if both s1 and s2 are not empty then compare their top nodes value if s1.top()->val <= s2.top()->val then in this case push the s1.top()->val in the result vector and push its right child in the stack s1" }, { "code": null, "e": 30339, "s": 30016, "text": "Case 2 :- if s1 is empty then pop s2 and put the popped node value in the answer vector else if both s1 and s2 are not empty then compare their top nodes value if s2.top()->val >= s1.top()->val then in this case push the s2.top()->val in the result vector and push its right child in the stack s2" }, { "code": null, "e": 30399, "s": 30339, "text": "Step 4 :- Continue step 3 until both the stacks get empty. " }, { "code": null, "e": 30450, "s": 30399, "text": "Below is the implementation of the above logic :- " }, { "code": null, "e": 30454, "s": 30450, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; // Structure of a BST Nodeclass Node {public: int val; Node* left; Node* right;}; /* Utility function to create a new Binary Tree Node */Node* newNode(int data){ Node* temp = new Node; temp->val = data; temp->left = nullptr; temp->right = nullptr; return temp;} vector<int> mergeTwoBST(Node* root1, Node* root2){ vector<int> res; stack<Node*> s1, s2; while (root1 || root2 || !s1.empty() || !s2.empty()) { while (root1) { s1.push(root1); root1 = root1->left; } while (root2) { s2.push(root2); root2 = root2->left; } // Step 3 Case 1:- if (s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)) { root1 = s1.top(); s1.pop(); res.push_back(root1->val); root1 = root1->right; } // Step 3 case 2 :- else { root2 = s2.top(); s2.pop(); res.push_back(root2->val); root2 = root2->right; } } return res;} /* Driver program to test above functions */int main(){ Node *root1 = nullptr, *root2 = nullptr; /* Let us create the following tree as first tree 3 / \\ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \\ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted Nodes of both trees vector<int> ans = mergeTwoBST(root1, root2); for (auto it : ans) cout << it << \" \"; return 0;} // This code is contributed by Aditya kumar (adityakumar129)", "e": 32193, "s": 30454, "text": null }, { "code": null, "e": 32206, "s": 32193, "text": "1 2 3 4 5 6 " }, { "code": null, "e": 32303, "s": 32206, "text": "Time Complexity: O(m+n) Auxiliary Space: O(height of the first tree + height of the second tree)" }, { "code": null, "e": 32428, "s": 32303, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32442, "s": 32428, "text": "rathbhupendra" }, { "code": null, "e": 32464, "s": 32442, "text": "koushikrbukkasamudram" }, { "code": null, "e": 32482, "s": 32464, "text": "nidhisebastian008" }, { "code": null, "e": 32492, "s": 32482, "text": "rutvik_56" }, { "code": null, "e": 32508, "s": 32492, "text": "saurabh1990aror" }, { "code": null, "e": 32515, "s": 32508, "text": "rdtank" }, { "code": null, "e": 32530, "s": 32515, "text": "adnanirshad158" }, { "code": null, "e": 32539, "s": 32530, "text": "gabaa406" }, { "code": null, "e": 32553, "s": 32539, "text": "sumitgumber28" }, { "code": null, "e": 32570, "s": 32553, "text": "surinderdawra388" }, { "code": null, "e": 32585, "s": 32570, "text": "adityakumar129" }, { "code": null, "e": 32592, "s": 32585, "text": "Amazon" }, { "code": null, "e": 32599, "s": 32592, "text": "Google" }, { "code": null, "e": 32610, "s": 32599, "text": "Merge Sort" }, { "code": null, "e": 32620, "s": 32610, "text": "Microsoft" }, { "code": null, "e": 32639, "s": 32620, "text": "Binary Search Tree" }, { "code": null, "e": 32644, "s": 32639, "text": "Tree" }, { "code": null, "e": 32651, "s": 32644, "text": "Amazon" }, { "code": null, "e": 32661, "s": 32651, "text": "Microsoft" }, { "code": null, "e": 32668, "s": 32661, "text": "Google" }, { "code": null, "e": 32687, "s": 32668, "text": "Binary Search Tree" }, { "code": null, "e": 32692, "s": 32687, "text": "Tree" }, { "code": null, "e": 32703, "s": 32692, "text": "Merge Sort" }, { "code": null, "e": 32801, "s": 32703, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32851, "s": 32801, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 32907, "s": 32851, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 32977, "s": 32907, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 33012, "s": 32977, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 33041, "s": 33012, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 33091, "s": 33041, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 33126, "s": 33091, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 33160, "s": 33126, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 33192, "s": 33160, "text": "Introduction to Data Structures" } ]
Sum of maximum of all subarrays | Divide and Conquer
09 Nov, 2021 Given an array arr[] of length N, the task is to find the sum of the maximum elements of every possible sub-array of the array.Examples: Input : arr[] = {1, 3, 1, 7} Output : 42 Max of all sub-arrays: {1} - 1 {1, 3} - 3 {1, 3, 1} - 3 {1, 3, 1, 7} - 7 {3} - 3 {3, 1} - 3 {3, 1, 7} - 7 {1} - 1 {1, 7} - 7 {7} - 7 1 + 3 + 3 + 7 + 3 + 3 + 7 + 1 + 7 + 7 = 42 Input : arr[] = {1, 1, 1, 1, 1} Output : 15 We have already discussed an O(N) approach using stack for this problem in this article.Approach : In this article, we will learn how to solve this problem using divide and conquer. Let’s assume that element at ith index is largest of all. For any sub-array that contains index ‘i’, the element at ‘i’ will always be maximum in the sub-array. If element at ith index is largest, we can safely say, that element ith index will be largest in (i+1)*(N-i) subarrays. So, its total contribution will be arr[i]*(i+1)*(N-i). Now, we will divide the array in two parts, (0, i-1) and (i+1, N-1) and apply the same algorithms to both of them separately.So our general recurrence relation will be: maxSumSubarray(arr, l, r) = arr[i]*(r-i+1)*(i-l+1) + maxSumSubarray(arr, l, i-1) + maxSumSubarray(arr, i+1, r) where i is index of maximum element in range [l, r]. Now, we need a way to efficiently answer rangeMax() queries. Segment tree will be an efficient way to answer this query. We will need to answer this query at most N times. Thus, the time complexity of our divide and conquer algorithm will O(Nlog(N)). If we have to answer the problem “Sum of minimum of all subarrays” then we will use the segment tree to answer rangeMin() queries. For this, you can go through the article segment tree range minimum.Below is the implementation code: C++ Java Python3 C# Javascript // C++ implementation of the above approach #include <bits/stdc++.h>#define seg_max 51using namespace std; // Array to store segment tree.// In first we will store the maximum// of a range// In second, we will store index of// that rangepair<int, int> seg_tree[seg_max]; // Size of array declared global// to maintain simplicity in codeint n; // Function to build segment treepair<int, int> buildMaxTree(int l, int r, int i, int arr[]){ // Base case if (l == r) { seg_tree[i] = { arr[l], l }; return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, (l + r) / 2, 2 * i + 1, arr), buildMaxTree((l + r) / 2 + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i];} // Function to perform range-max query in segment treepair<int, int> rangeMax(int l, int r, int arr[], int i = 0, int sl = 0, int sr = n - 1){ // Base cases if (sr < l || sl > r) return { INT_MIN, -1 }; if (sl >= l and sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, (sl + sr) / 2), rangeMax(l, r, arr, 2 * i + 2, (sl + sr) / 2 + 1, sr));} // Function to find maximum sum subarrayint maxSumSubarray(int arr[], int l = 0, int r = n - 1){ // base case if (l > r) return 0; // range-max query to determine // largest in the range. pair<int, int> a = rangeMax(l, r, arr); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r);} // Driver Codeint main(){ // Input array int arr[] = { 1, 3, 1, 7 }; // Size of array n = sizeof(arr) / sizeof(int); // Builind the segment-tree buildMaxTree(0, n - 1, 0, arr); cout << maxSumSubarray(arr); return 0;} // Java implementation of the above approachclass GFG { static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static final int seg_max = 51; // Array to store segment tree. // In first we will store the maximum // of a range // In second, we will store index of // that range static pair[] seg_tree = new pair[seg_max]; // Size of array declared global // to maintain simplicity in code static int n; // Function to build segment tree static pair buildMaxTree(int l, int r, int i, int arr[]) { // Base case if (l == r) { seg_tree[i] = new pair(arr[l], l); return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, (l + r) / 2, 2 * i + 1, arr), buildMaxTree((l + r) / 2 + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i]; } // Function to perform range-max query in segment tree static pair rangeMax(int l, int r, int arr[], int i, int sl, int sr) { // Base cases if (sr < l || sl > r) return new pair(Integer.MIN_VALUE, -1); if (sl >= l && sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, (sl + sr) / 2), rangeMax(l, r, arr, 2 * i + 2, (sl + sr) / 2 + 1, sr)); } static pair max(pair f, pair s) { if (f.first > s.first) return f; else return s; } // Function to find maximum sum subarray static int maxSumSubarray(int arr[], int l, int r) { // base case if (l > r) return 0; // range-max query to determine // largest in the range. pair a = rangeMax(l, r, arr, 0, 0, n - 1); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r); } // Driver Code public static void main(String[] args) { // Input array int arr[] = { 1, 3, 1, 7 }; // Size of array n = arr.length; // Builind the segment-tree buildMaxTree(0, n - 1, 0, arr); System.out.print(maxSumSubarray(arr, 0, n - 1)); }} // This code is contributed by 29AjayKumar # Python3 implementation of the above approachimport sys seg_max = 51 # Array to store segment tree.# In first we will store the maximum# of a range# In second, we will store index of# that rangeseg_tree = [[] for i in range(seg_max)] # Function to build segment treedef buildMaxTree(l, r, i, arr): global n, seg_tree, seg_max # Base case if l == r: seg_tree[i] = [arr[l], l] return seg_tree[i] # Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, int((l + r) / 2), 2 * i + 1, arr), buildMaxTree(int((l + r) / 2) + 1, r, 2 * i + 2, arr)) # Returning the maximum to parent return seg_tree[i] # Function to perform range-max query in segment treedef rangeMax(l, r, arr, i, sl, sr): global n, seg_tree, seg_max # Base cases if sr < l or sl > r: return [-sys.maxsize, -1] if sl >= l and sr <= r: return seg_tree[i] # Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, int((sl + sr) / 2)), rangeMax(l, r, arr, 2 * i + 2, int((sl + sr) / 2) + 1, sr)) def Max(f, s): if f[0] > s[0]: return f else: return s # Function to find maximum sum subarraydef maxSumSubarray(arr, l, r): # base case if l > r: return 0 # range-max query to determine # largest in the range. a = rangeMax(l, r, arr, 0, 0, n - 1) # divide the array in two parts return a[0] * (r - a[1] + 1) * (a[1] - l + 1) + maxSumSubarray(arr, l, a[1] - 1) + maxSumSubarray(arr, a[1] + 1, r) # Input arrayarr = [ 1, 3, 1, 7 ] # Size of arrayn = len(arr) # Builind the segment-treebuildMaxTree(0, n - 1, 0, arr) print(maxSumSubarray(arr, 0, n - 1)) # This code is contributed by decode2207. // C# implementation of the above approachusing System; class GFG { class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static readonly int seg_max = 51; // Array to store segment tree. // In first we will store the maximum // of a range // In second, we will store index of // that range static pair[] seg_tree = new pair[seg_max]; // Size of array declared global // to maintain simplicity in code static int n; // Function to build segment tree static pair buildMaxTree(int l, int r, int i, int []arr) { // Base case if (l == r) { seg_tree[i] = new pair(arr[l], l); return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, (l + r) / 2, 2 * i + 1, arr), buildMaxTree((l + r) / 2 + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i]; } // Function to perform range-max query in segment tree static pair rangeMax(int l, int r, int []arr, int i, int sl, int sr) { // Base cases if (sr < l || sl > r) return new pair(int.MinValue, -1); if (sl >= l && sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, (sl + sr) / 2), rangeMax(l, r, arr, 2 * i + 2, (sl + sr) / 2 + 1, sr)); } static pair max(pair f, pair s) { if (f.first > s.first) return f; else return s; } // Function to find maximum sum subarray static int maxSumSubarray(int []arr, int l, int r) { // base case if (l > r) return 0; // range-max query to determine // largest in the range. pair a = rangeMax(l, r, arr, 0, 0, n - 1); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r); } // Driver Code public static void Main(String[] args) { // Input array int []arr = { 1, 3, 1, 7 }; // Size of array n = arr.Length; // Builind the segment-tree buildMaxTree(0, n - 1, 0, arr); Console.Write(maxSumSubarray(arr, 0, n - 1)); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation of the above approach class pair{ constructor(first,second) { this.first = first; this.second = second; }} let seg_max = 51; // Array to store segment tree. // In first we will store the maximum // of a range // In second, we will store index of // that rangelet seg_tree = new Array(seg_max); // Size of array declared global // to maintain simplicity in codelet n; // Function to build segment treefunction buildMaxTree(l,r,i,arr){ // Base case if (l == r) { seg_tree[i] = new pair(arr[l], l); return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, Math.floor((l + r) / 2), 2 * i + 1, arr), buildMaxTree(Math.floor((l + r) / 2) + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i];} // Function to perform range-max query in segment treefunction rangeMax(l,r,arr,i,sl,sr){ // Base cases if (sr < l || sl > r) return new pair(Number.MIN_VALUE, -1); if (sl >= l && sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, Math.floor((sl + sr) / 2)), rangeMax(l, r, arr, 2 * i + 2, Math.floor((sl + sr) / 2) + 1, sr));} function max(f,s){ if (f.first > s.first) return f; else return s;} // Function to find maximum sum subarrayfunction maxSumSubarray(arr,l,r){ // base case if (l > r) return 0; // range-max query to determine // largest in the range. let a = rangeMax(l, r, arr, 0, 0, n - 1); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r);} // Driver Code// Input arraylet arr = [ 1, 3, 1, 7 ]; // Size of arrayn = arr.length; // Builind the segment-treebuildMaxTree(0, n - 1, 0, arr); document.write(maxSumSubarray(arr, 0, n - 1)); // This code is contributed by rag2127 </script> 42 Time complexity : O(Nlog(N)) ManasChhabra2 29AjayKumar princiraj1992 rag2127 decode2207 Segment-Tree subarray subarray-sum Arrays Divide and Conquer Recursion Arrays Recursion Divide and Conquer Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Merge Sort QuickSort Binary Search Maximum and minimum of an array using minimum number of comparisons Count Inversions in an array | Set 1 (Using Merge Sort)
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Nov, 2021" }, { "code": null, "e": 191, "s": 52, "text": "Given an array arr[] of length N, the task is to find the sum of the maximum elements of every possible sub-array of the array.Examples: " }, { "code": null, "e": 454, "s": 191, "text": "Input : arr[] = {1, 3, 1, 7}\nOutput : 42\nMax of all sub-arrays:\n{1} - 1\n{1, 3} - 3\n{1, 3, 1} - 3\n{1, 3, 1, 7} - 7\n{3} - 3\n{3, 1} - 3\n{3, 1, 7} - 7 \n{1} - 1\n{1, 7} - 7\n{7} - 7\n1 + 3 + 3 + 7 + 3 + 3 + 7 + 1 + 7 + 7 = 42\n\nInput : arr[] = {1, 1, 1, 1, 1}\nOutput : 15" }, { "code": null, "e": 1145, "s": 456, "text": "We have already discussed an O(N) approach using stack for this problem in this article.Approach : In this article, we will learn how to solve this problem using divide and conquer. Let’s assume that element at ith index is largest of all. For any sub-array that contains index ‘i’, the element at ‘i’ will always be maximum in the sub-array. If element at ith index is largest, we can safely say, that element ith index will be largest in (i+1)*(N-i) subarrays. So, its total contribution will be arr[i]*(i+1)*(N-i). Now, we will divide the array in two parts, (0, i-1) and (i+1, N-1) and apply the same algorithms to both of them separately.So our general recurrence relation will be: " }, { "code": null, "e": 1366, "s": 1145, "text": "maxSumSubarray(arr, l, r) = arr[i]*(r-i+1)*(i-l+1) \n + maxSumSubarray(arr, l, i-1)\n + maxSumSubarray(arr, i+1, r)\nwhere i is index of maximum element in range [l, r]." }, { "code": null, "e": 1852, "s": 1366, "text": "Now, we need a way to efficiently answer rangeMax() queries. Segment tree will be an efficient way to answer this query. We will need to answer this query at most N times. Thus, the time complexity of our divide and conquer algorithm will O(Nlog(N)). If we have to answer the problem “Sum of minimum of all subarrays” then we will use the segment tree to answer rangeMin() queries. For this, you can go through the article segment tree range minimum.Below is the implementation code: " }, { "code": null, "e": 1856, "s": 1852, "text": "C++" }, { "code": null, "e": 1861, "s": 1856, "text": "Java" }, { "code": null, "e": 1869, "s": 1861, "text": "Python3" }, { "code": null, "e": 1872, "s": 1869, "text": "C#" }, { "code": null, "e": 1883, "s": 1872, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include <bits/stdc++.h>#define seg_max 51using namespace std; // Array to store segment tree.// In first we will store the maximum// of a range// In second, we will store index of// that rangepair<int, int> seg_tree[seg_max]; // Size of array declared global// to maintain simplicity in codeint n; // Function to build segment treepair<int, int> buildMaxTree(int l, int r, int i, int arr[]){ // Base case if (l == r) { seg_tree[i] = { arr[l], l }; return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, (l + r) / 2, 2 * i + 1, arr), buildMaxTree((l + r) / 2 + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i];} // Function to perform range-max query in segment treepair<int, int> rangeMax(int l, int r, int arr[], int i = 0, int sl = 0, int sr = n - 1){ // Base cases if (sr < l || sl > r) return { INT_MIN, -1 }; if (sl >= l and sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, (sl + sr) / 2), rangeMax(l, r, arr, 2 * i + 2, (sl + sr) / 2 + 1, sr));} // Function to find maximum sum subarrayint maxSumSubarray(int arr[], int l = 0, int r = n - 1){ // base case if (l > r) return 0; // range-max query to determine // largest in the range. pair<int, int> a = rangeMax(l, r, arr); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r);} // Driver Codeint main(){ // Input array int arr[] = { 1, 3, 1, 7 }; // Size of array n = sizeof(arr) / sizeof(int); // Builind the segment-tree buildMaxTree(0, n - 1, 0, arr); cout << maxSumSubarray(arr); return 0;}", "e": 3854, "s": 1883, "text": null }, { "code": "// Java implementation of the above approachclass GFG { static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static final int seg_max = 51; // Array to store segment tree. // In first we will store the maximum // of a range // In second, we will store index of // that range static pair[] seg_tree = new pair[seg_max]; // Size of array declared global // to maintain simplicity in code static int n; // Function to build segment tree static pair buildMaxTree(int l, int r, int i, int arr[]) { // Base case if (l == r) { seg_tree[i] = new pair(arr[l], l); return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, (l + r) / 2, 2 * i + 1, arr), buildMaxTree((l + r) / 2 + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i]; } // Function to perform range-max query in segment tree static pair rangeMax(int l, int r, int arr[], int i, int sl, int sr) { // Base cases if (sr < l || sl > r) return new pair(Integer.MIN_VALUE, -1); if (sl >= l && sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, (sl + sr) / 2), rangeMax(l, r, arr, 2 * i + 2, (sl + sr) / 2 + 1, sr)); } static pair max(pair f, pair s) { if (f.first > s.first) return f; else return s; } // Function to find maximum sum subarray static int maxSumSubarray(int arr[], int l, int r) { // base case if (l > r) return 0; // range-max query to determine // largest in the range. pair a = rangeMax(l, r, arr, 0, 0, n - 1); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r); } // Driver Code public static void main(String[] args) { // Input array int arr[] = { 1, 3, 1, 7 }; // Size of array n = arr.length; // Builind the segment-tree buildMaxTree(0, n - 1, 0, arr); System.out.print(maxSumSubarray(arr, 0, n - 1)); }} // This code is contributed by 29AjayKumar", "e": 6418, "s": 3854, "text": null }, { "code": "# Python3 implementation of the above approachimport sys seg_max = 51 # Array to store segment tree.# In first we will store the maximum# of a range# In second, we will store index of# that rangeseg_tree = [[] for i in range(seg_max)] # Function to build segment treedef buildMaxTree(l, r, i, arr): global n, seg_tree, seg_max # Base case if l == r: seg_tree[i] = [arr[l], l] return seg_tree[i] # Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, int((l + r) / 2), 2 * i + 1, arr), buildMaxTree(int((l + r) / 2) + 1, r, 2 * i + 2, arr)) # Returning the maximum to parent return seg_tree[i] # Function to perform range-max query in segment treedef rangeMax(l, r, arr, i, sl, sr): global n, seg_tree, seg_max # Base cases if sr < l or sl > r: return [-sys.maxsize, -1] if sl >= l and sr <= r: return seg_tree[i] # Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, int((sl + sr) / 2)), rangeMax(l, r, arr, 2 * i + 2, int((sl + sr) / 2) + 1, sr)) def Max(f, s): if f[0] > s[0]: return f else: return s # Function to find maximum sum subarraydef maxSumSubarray(arr, l, r): # base case if l > r: return 0 # range-max query to determine # largest in the range. a = rangeMax(l, r, arr, 0, 0, n - 1) # divide the array in two parts return a[0] * (r - a[1] + 1) * (a[1] - l + 1) + maxSumSubarray(arr, l, a[1] - 1) + maxSumSubarray(arr, a[1] + 1, r) # Input arrayarr = [ 1, 3, 1, 7 ] # Size of arrayn = len(arr) # Builind the segment-treebuildMaxTree(0, n - 1, 0, arr) print(maxSumSubarray(arr, 0, n - 1)) # This code is contributed by decode2207.", "e": 8160, "s": 6418, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG { class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } static readonly int seg_max = 51; // Array to store segment tree. // In first we will store the maximum // of a range // In second, we will store index of // that range static pair[] seg_tree = new pair[seg_max]; // Size of array declared global // to maintain simplicity in code static int n; // Function to build segment tree static pair buildMaxTree(int l, int r, int i, int []arr) { // Base case if (l == r) { seg_tree[i] = new pair(arr[l], l); return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, (l + r) / 2, 2 * i + 1, arr), buildMaxTree((l + r) / 2 + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i]; } // Function to perform range-max query in segment tree static pair rangeMax(int l, int r, int []arr, int i, int sl, int sr) { // Base cases if (sr < l || sl > r) return new pair(int.MinValue, -1); if (sl >= l && sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, (sl + sr) / 2), rangeMax(l, r, arr, 2 * i + 2, (sl + sr) / 2 + 1, sr)); } static pair max(pair f, pair s) { if (f.first > s.first) return f; else return s; } // Function to find maximum sum subarray static int maxSumSubarray(int []arr, int l, int r) { // base case if (l > r) return 0; // range-max query to determine // largest in the range. pair a = rangeMax(l, r, arr, 0, 0, n - 1); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r); } // Driver Code public static void Main(String[] args) { // Input array int []arr = { 1, 3, 1, 7 }; // Size of array n = arr.Length; // Builind the segment-tree buildMaxTree(0, n - 1, 0, arr); Console.Write(maxSumSubarray(arr, 0, n - 1)); }} // This code is contributed by PrinciRaj1992", "e": 10750, "s": 8160, "text": null }, { "code": "<script> // JavaScript implementation of the above approach class pair{ constructor(first,second) { this.first = first; this.second = second; }} let seg_max = 51; // Array to store segment tree. // In first we will store the maximum // of a range // In second, we will store index of // that rangelet seg_tree = new Array(seg_max); // Size of array declared global // to maintain simplicity in codelet n; // Function to build segment treefunction buildMaxTree(l,r,i,arr){ // Base case if (l == r) { seg_tree[i] = new pair(arr[l], l); return seg_tree[i]; } // Finding the maximum among left and right child seg_tree[i] = max(buildMaxTree(l, Math.floor((l + r) / 2), 2 * i + 1, arr), buildMaxTree(Math.floor((l + r) / 2) + 1, r, 2 * i + 2, arr)); // Returning the maximum to parent return seg_tree[i];} // Function to perform range-max query in segment treefunction rangeMax(l,r,arr,i,sl,sr){ // Base cases if (sr < l || sl > r) return new pair(Number.MIN_VALUE, -1); if (sl >= l && sr <= r) return seg_tree[i]; // Finding the maximum among left and right child return max(rangeMax(l, r, arr, 2 * i + 1, sl, Math.floor((sl + sr) / 2)), rangeMax(l, r, arr, 2 * i + 2, Math.floor((sl + sr) / 2) + 1, sr));} function max(f,s){ if (f.first > s.first) return f; else return s;} // Function to find maximum sum subarrayfunction maxSumSubarray(arr,l,r){ // base case if (l > r) return 0; // range-max query to determine // largest in the range. let a = rangeMax(l, r, arr, 0, 0, n - 1); // divide the array in two parts return a.first * (r - a.second + 1) * (a.second - l + 1) + maxSumSubarray(arr, l, a.second - 1) + maxSumSubarray(arr, a.second + 1, r);} // Driver Code// Input arraylet arr = [ 1, 3, 1, 7 ]; // Size of arrayn = arr.length; // Builind the segment-treebuildMaxTree(0, n - 1, 0, arr); document.write(maxSumSubarray(arr, 0, n - 1)); // This code is contributed by rag2127 </script>", "e": 12997, "s": 10750, "text": null }, { "code": null, "e": 13000, "s": 12997, "text": "42" }, { "code": null, "e": 13032, "s": 13002, "text": "Time complexity : O(Nlog(N)) " }, { "code": null, "e": 13046, "s": 13032, "text": "ManasChhabra2" }, { "code": null, "e": 13058, "s": 13046, "text": "29AjayKumar" }, { "code": null, "e": 13072, "s": 13058, "text": "princiraj1992" }, { "code": null, "e": 13080, "s": 13072, "text": "rag2127" }, { "code": null, "e": 13091, "s": 13080, "text": "decode2207" }, { "code": null, "e": 13104, "s": 13091, "text": "Segment-Tree" }, { "code": null, "e": 13113, "s": 13104, "text": "subarray" }, { "code": null, "e": 13126, "s": 13113, "text": "subarray-sum" }, { "code": null, "e": 13133, "s": 13126, "text": "Arrays" }, { "code": null, "e": 13152, "s": 13133, "text": "Divide and Conquer" }, { "code": null, "e": 13162, "s": 13152, "text": "Recursion" }, { "code": null, "e": 13169, "s": 13162, "text": "Arrays" }, { "code": null, "e": 13179, "s": 13169, "text": "Recursion" }, { "code": null, "e": 13198, "s": 13179, "text": "Divide and Conquer" }, { "code": null, "e": 13211, "s": 13198, "text": "Segment-Tree" }, { "code": null, "e": 13309, "s": 13211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13377, "s": 13309, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 13421, "s": 13377, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 13453, "s": 13421, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 13501, "s": 13453, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 13515, "s": 13501, "text": "Linear Search" }, { "code": null, "e": 13526, "s": 13515, "text": "Merge Sort" }, { "code": null, "e": 13536, "s": 13526, "text": "QuickSort" }, { "code": null, "e": 13550, "s": 13536, "text": "Binary Search" }, { "code": null, "e": 13618, "s": 13550, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
BigInteger compareTo() Method in Java
12 May, 2022 The java.math.BigInteger.compareTo(BigInteger value) method Compares this BigInteger with the BigInteger passed as the parameter. Syntax: public int compareTo(BigInteger val) Parameter: This method accepts a single mandatory parameter val which is the BigInteger to compare with BigInteger object. Return Type: This method returns the following: 0: if the value of this BigInteger is equal to that of the BigInteger object passed as a parameter. 1: if the value of this BigInteger is greater than that of the BigInteger object passed as a parameter. -1: if the value of this BigInteger is less than that of the BigInteger object passed as a parameter. Examples: Input: BigInteger1=2345, BigInteger2=7456 Output: -1 Explanation: BigInteger1.compareTo(BigInteger2)=-1. Input: BigInteger1=9834, BigInteger2=7456 Output: 1 Explanation: BigInteger1.compareTo(BigInteger2)=1. Example 1: Below programs illustrate the compareTo() method of BigInteger class when both BigIntegers are equal Java // Java program to demonstrate// compareTo() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("321456"); b2 = new BigInteger("321456"); // apply compareTo() method int comparevalue = b1.compareTo(b2); // print result if (comparevalue == 0) { System.out.println("BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are equal"); } }} BigInteger1 321456 and BigInteger2 321456 are equal Example 2: when BigInteger1 is greater than BigInteger2 Java // Java program to demonstrate// compareTo() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("654321"); b2 = new BigInteger("321456"); // apply compareTo() method int comparevalue = b1.compareTo(b2); // print result if (comparevalue == 1) { System.out.println("BigInteger1 " + b1 + " is greater than BigInteger2 " + b2); } }} BigInteger1 654321 is greater than BigInteger2 321456 Example 3: When BigInteger1 is lesser than BigInteger2 Java // Java program to demonstrate// compareTo() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("321456"); b2 = new BigInteger("564321"); // apply compareTo() method int comparevalue = b1.compareTo(b2); // print result if(comparevalue == -1) { System.out.println("BigInteger1 " + b1 + " is lesser than BigInteger2 " + b2); } }} BigInteger1 321456 is lesser than BigInteger2 564321 nk0187912 Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger Java 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": 159, "s": 28, "text": "The java.math.BigInteger.compareTo(BigInteger value) method Compares this BigInteger with the BigInteger passed as the parameter. " }, { "code": null, "e": 167, "s": 159, "text": "Syntax:" }, { "code": null, "e": 204, "s": 167, "text": "public int compareTo(BigInteger val)" }, { "code": null, "e": 328, "s": 204, "text": "Parameter: This method accepts a single mandatory parameter val which is the BigInteger to compare with BigInteger object. " }, { "code": null, "e": 376, "s": 328, "text": "Return Type: This method returns the following:" }, { "code": null, "e": 476, "s": 376, "text": "0: if the value of this BigInteger is equal to that of the BigInteger object passed as a parameter." }, { "code": null, "e": 580, "s": 476, "text": "1: if the value of this BigInteger is greater than that of the BigInteger object passed as a parameter." }, { "code": null, "e": 682, "s": 580, "text": "-1: if the value of this BigInteger is less than that of the BigInteger object passed as a parameter." }, { "code": null, "e": 692, "s": 682, "text": "Examples:" }, { "code": null, "e": 901, "s": 692, "text": "Input: BigInteger1=2345, BigInteger2=7456\nOutput: -1\nExplanation: BigInteger1.compareTo(BigInteger2)=-1.\n\nInput: BigInteger1=9834, BigInteger2=7456\nOutput: 1\nExplanation: BigInteger1.compareTo(BigInteger2)=1." }, { "code": null, "e": 1014, "s": 901, "text": "Example 1: Below programs illustrate the compareTo() method of BigInteger class when both BigIntegers are equal " }, { "code": null, "e": 1019, "s": 1014, "text": "Java" }, { "code": "// Java program to demonstrate// compareTo() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"321456\"); b2 = new BigInteger(\"321456\"); // apply compareTo() method int comparevalue = b1.compareTo(b2); // print result if (comparevalue == 0) { System.out.println(\"BigInteger1 \" + b1 + \" and BigInteger2 \" + b2 + \" are equal\"); } }}", "e": 1636, "s": 1019, "text": null }, { "code": null, "e": 1688, "s": 1636, "text": "BigInteger1 321456 and BigInteger2 321456 are equal" }, { "code": null, "e": 1745, "s": 1688, "text": "Example 2: when BigInteger1 is greater than BigInteger2 " }, { "code": null, "e": 1750, "s": 1745, "text": "Java" }, { "code": "// Java program to demonstrate// compareTo() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"654321\"); b2 = new BigInteger(\"321456\"); // apply compareTo() method int comparevalue = b1.compareTo(b2); // print result if (comparevalue == 1) { System.out.println(\"BigInteger1 \" + b1 + \" is greater than BigInteger2 \" + b2); } }}", "e": 2321, "s": 1750, "text": null }, { "code": null, "e": 2375, "s": 2321, "text": "BigInteger1 654321 is greater than BigInteger2 321456" }, { "code": null, "e": 2431, "s": 2375, "text": "Example 3: When BigInteger1 is lesser than BigInteger2 " }, { "code": null, "e": 2436, "s": 2431, "text": "Java" }, { "code": "// Java program to demonstrate// compareTo() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"321456\"); b2 = new BigInteger(\"564321\"); // apply compareTo() method int comparevalue = b1.compareTo(b2); // print result if(comparevalue == -1) { System.out.println(\"BigInteger1 \" + b1 + \" is lesser than BigInteger2 \" + b2); } }}", "e": 3006, "s": 2436, "text": null }, { "code": null, "e": 3059, "s": 3006, "text": "BigInteger1 321456 is lesser than BigInteger2 564321" }, { "code": null, "e": 3069, "s": 3059, "text": "nk0187912" }, { "code": null, "e": 3085, "s": 3069, "text": "Java-BigInteger" }, { "code": null, "e": 3100, "s": 3085, "text": "Java-Functions" }, { "code": null, "e": 3110, "s": 3100, "text": "java-math" }, { "code": null, "e": 3128, "s": 3110, "text": "Java-math-package" }, { "code": null, "e": 3133, "s": 3128, "text": "Java" }, { "code": null, "e": 3149, "s": 3133, "text": "Java-BigInteger" }, { "code": null, "e": 3154, "s": 3149, "text": "Java" } ]
Indexed Sequential Search
14 Mar, 2022 In this searching method, first of all, an index file is created, that contains some specific group or division of required record when the index is obtained, then the partial indexing takes less time cause it is located in a specified group. Note: When the user makes a request for specific records it will find that index group first where that specific record is recorded. In Indexed Sequential Search a sorted index is set aside in addition to the array. Each element in the index points to a block of elements in the array or another expanded index. The index is searched 1st then the array and guides the search in the array. Note: Indexed Sequential Search actually does the indexing multiple time, like creating the index of an index. C Java Python3 C# PHP // C program for Indexed Sequential Search#include <stdio.h>#include <stdlib.h> void indexedSequentialSearch(int arr[], int n, int k){ int GN = 3; // GN is group number that is number of // elements in a group int elements[GN], indices[GN], i, set = 0; int j = 0, ind = 0, start, end; for (i = 0; i < n; i += 3) { // Storing element elements[ind] = arr[i]; // Storing the index indices[ind] = i; ind++; } if (k < elements[0]) { printf("Not found"); exit(0); } else { for (i = 1; i <= ind; i++) if (k <= elements[i]) { start = indices[i - 1]; end = indices[i]; set = 1; break; } } if (set == 0) { start = indices[GN - 1]; end = GN; } for (i = start; i <= end; i++) { if (k == arr[i]) { j = 1; break; } } if (j == 1) printf("Found at index %d", i); else printf("Not found");} // Driver codevoid main(){ int arr[] = { 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // Element to search int k = 8; indexedSequentialSearch(arr, n, k);} // Java program for Indexed Sequential Search import java.io.*; class GFG { static void indexedSequentialSearch(int arr[], int n, int k) { int elements[] = new int[20]; int indices[] = new int[20]; int temp, i; int j = 0, ind = 0, start = 0, end = 0, set = 0; for (i = 0; i < n; i += 3) { // Storing element elements[ind] = arr[i]; // Storing the index indices[ind] = i; ind++; } if (k < elements[0]) { System.out.println("Not found"); return; } else { for (i = 1; i <= ind; i++) if (k <= elements[i]) { start = indices[i - 1]; set = 1; end = indices[i]; break; } } if (set == 0) { start = indices[i - 1]; end = n; } for (i = start; i <= end; i++) { if (k == arr[i]) { j = 1; break; } } if (j == 1) System.out.println("Found at index " + i); else System.out.println("Not found"); } // Driver code public static void main(String[] args) { int arr[] = { 6, 7, 8, 9, 10 }; int n = arr.length; // Element to search int k = 8; indexedSequentialSearch(arr, n, k); }}// This code is contributed by shs.. # Python program for Indexed# Sequential Search def indexedSequentialSearch(arr, n, k): elements = [0] * 20 indices = [0] * 20 j, ind, start, end = 0, 0, 0, 0 set_flag = 0 for i in range(0, n, 3): # Storing element elements[ind] = arr[i] # Storing the index indices[ind] = i ind += 1 if k < elements[0]: print("Not found") exit(0) else: for i in range(1, ind + 1): if k <= elements[i]: start = indices[i - 1] end = indices[i] set_flag = 1 break if set_flag == 0: start = indices[i-1] end = n for i in range(start, end + 1): if k == arr[i]: j = 1 break if j == 1: print("Found at index", i) else: print("Not found") # Driver codeif __name__ == "__main__": arr = [6, 7, 8, 9, 10] n = len(arr) # Element to search k = 8 # Function call indexedSequentialSearch(arr, n, k) # This code is contributed by Ryuga // C# program for Indexed Sequential Search using System; class GFG { static void indexedSequentialSearch(int []arr, int n, int k){ int []elements = new int[20]; int []indices = new int[20]; int i; int j = 0, ind = 0, start=0, end=0, set = 0; for (i = 0; i < n; i += 3) { // Storing element elements[ind] = arr[i]; // Storing the index indices[ind] = i; ind++; } if (k < elements[0]) { Console.Write("Not found"); return; } else { for (i = 1; i <= ind; i++) if (k <= elements[i]) { start = indices[i - 1]; set = 1; end = indices[i]; break; } } if(set == 0) { start = indices[i-1]; end = n-1; } for (i = start; i <= end; i++) { if (k == arr[i]) { j = 1; break; } } if (j == 1) Console.WriteLine("Found at index "+ i); else Console.WriteLine("Not found");} // Driver code public static void Main () { int []arr = { 6, 7, 8, 9, 10 }; int n = arr.Length; // Element to search int k = 10; indexedSequentialSearch(arr, n, k); }}// This code is contributed by shs.. <?php// PHP program for Indexed Sequential Search function indexedSequentialSearch($arr, $n, $k){ $elements = array(); $indices = array(); $temp = array(); $j = 0; $ind = 0; $start=0; $end=0; $set = 0; for ($i = 0; $i < $n; $i += 3) { // Storing element $elements[$ind] = $arr[$i]; // Storing the index $indices[$ind] = $i; $ind++; } if ($k < $elements[0]) { echo "Not found"; } else { for ($i = 1; $i <=$ind; $i++) if ($k < $elements[$i]) { $start = $indices[$i - 1]; $set = 1; $end = $indices[$i]; break; } } if($set == 1) { $start = $indices[$i-1]; $end = $n; } for ($i = $start; $i <=$end; $i++) { if ($k == $arr[$i]) { $j = 1; break; } } if ($j == 1) echo "Found at index ", $i; else echo "Not found";} // Driver code$arr = array( 6, 7, 8, 9, 10 );$n = count($arr); // Element to search$k = 10;indexedSequentialSearch($arr, $n, $k); // This code is contributed by shs..?> Found at index 2 Shashank12 ankthon raunaksrivastava22 anjalijoshi710 Picked Technical Scripter 2018 Searching Technical Scripter Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Search, insert and delete in a sorted array Given a sorted and rotated array, find if there is a pair with a given sum Allocate minimum number of pages Find common elements in three sorted arrays 3 Different ways to print Fibonacci series in Java Find whether an array is subset of another array Next Smaller Element Find a pair with the given difference
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Mar, 2022" }, { "code": null, "e": 295, "s": 52, "text": "In this searching method, first of all, an index file is created, that contains some specific group or division of required record when the index is obtained, then the partial indexing takes less time cause it is located in a specified group." }, { "code": null, "e": 428, "s": 295, "text": "Note: When the user makes a request for specific records it will find that index group first where that specific record is recorded." }, { "code": null, "e": 511, "s": 428, "text": "In Indexed Sequential Search a sorted index is set aside in addition to the array." }, { "code": null, "e": 607, "s": 511, "text": "Each element in the index points to a block of elements in the array or another expanded index." }, { "code": null, "e": 684, "s": 607, "text": "The index is searched 1st then the array and guides the search in the array." }, { "code": null, "e": 797, "s": 684, "text": "Note: Indexed Sequential Search actually does the indexing multiple time, like creating the index of an index. " }, { "code": null, "e": 805, "s": 803, "text": "C" }, { "code": null, "e": 810, "s": 805, "text": "Java" }, { "code": null, "e": 818, "s": 810, "text": "Python3" }, { "code": null, "e": 821, "s": 818, "text": "C#" }, { "code": null, "e": 825, "s": 821, "text": "PHP" }, { "code": "// C program for Indexed Sequential Search#include <stdio.h>#include <stdlib.h> void indexedSequentialSearch(int arr[], int n, int k){ int GN = 3; // GN is group number that is number of // elements in a group int elements[GN], indices[GN], i, set = 0; int j = 0, ind = 0, start, end; for (i = 0; i < n; i += 3) { // Storing element elements[ind] = arr[i]; // Storing the index indices[ind] = i; ind++; } if (k < elements[0]) { printf(\"Not found\"); exit(0); } else { for (i = 1; i <= ind; i++) if (k <= elements[i]) { start = indices[i - 1]; end = indices[i]; set = 1; break; } } if (set == 0) { start = indices[GN - 1]; end = GN; } for (i = start; i <= end; i++) { if (k == arr[i]) { j = 1; break; } } if (j == 1) printf(\"Found at index %d\", i); else printf(\"Not found\");} // Driver codevoid main(){ int arr[] = { 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int n = sizeof(arr) / sizeof(arr[0]); // Element to search int k = 8; indexedSequentialSearch(arr, n, k);}", "e": 2066, "s": 825, "text": null }, { "code": "// Java program for Indexed Sequential Search import java.io.*; class GFG { static void indexedSequentialSearch(int arr[], int n, int k) { int elements[] = new int[20]; int indices[] = new int[20]; int temp, i; int j = 0, ind = 0, start = 0, end = 0, set = 0; for (i = 0; i < n; i += 3) { // Storing element elements[ind] = arr[i]; // Storing the index indices[ind] = i; ind++; } if (k < elements[0]) { System.out.println(\"Not found\"); return; } else { for (i = 1; i <= ind; i++) if (k <= elements[i]) { start = indices[i - 1]; set = 1; end = indices[i]; break; } } if (set == 0) { start = indices[i - 1]; end = n; } for (i = start; i <= end; i++) { if (k == arr[i]) { j = 1; break; } } if (j == 1) System.out.println(\"Found at index \" + i); else System.out.println(\"Not found\"); } // Driver code public static void main(String[] args) { int arr[] = { 6, 7, 8, 9, 10 }; int n = arr.length; // Element to search int k = 8; indexedSequentialSearch(arr, n, k); }}// This code is contributed by shs..", "e": 3566, "s": 2066, "text": null }, { "code": "# Python program for Indexed# Sequential Search def indexedSequentialSearch(arr, n, k): elements = [0] * 20 indices = [0] * 20 j, ind, start, end = 0, 0, 0, 0 set_flag = 0 for i in range(0, n, 3): # Storing element elements[ind] = arr[i] # Storing the index indices[ind] = i ind += 1 if k < elements[0]: print(\"Not found\") exit(0) else: for i in range(1, ind + 1): if k <= elements[i]: start = indices[i - 1] end = indices[i] set_flag = 1 break if set_flag == 0: start = indices[i-1] end = n for i in range(start, end + 1): if k == arr[i]: j = 1 break if j == 1: print(\"Found at index\", i) else: print(\"Not found\") # Driver codeif __name__ == \"__main__\": arr = [6, 7, 8, 9, 10] n = len(arr) # Element to search k = 8 # Function call indexedSequentialSearch(arr, n, k) # This code is contributed by Ryuga", "e": 4622, "s": 3566, "text": null }, { "code": "// C# program for Indexed Sequential Search using System; class GFG { static void indexedSequentialSearch(int []arr, int n, int k){ int []elements = new int[20]; int []indices = new int[20]; int i; int j = 0, ind = 0, start=0, end=0, set = 0; for (i = 0; i < n; i += 3) { // Storing element elements[ind] = arr[i]; // Storing the index indices[ind] = i; ind++; } if (k < elements[0]) { Console.Write(\"Not found\"); return; } else { for (i = 1; i <= ind; i++) if (k <= elements[i]) { start = indices[i - 1]; set = 1; end = indices[i]; break; } } if(set == 0) { start = indices[i-1]; end = n-1; } for (i = start; i <= end; i++) { if (k == arr[i]) { j = 1; break; } } if (j == 1) Console.WriteLine(\"Found at index \"+ i); else Console.WriteLine(\"Not found\");} // Driver code public static void Main () { int []arr = { 6, 7, 8, 9, 10 }; int n = arr.Length; // Element to search int k = 10; indexedSequentialSearch(arr, n, k); }}// This code is contributed by shs..", "e": 5903, "s": 4622, "text": null }, { "code": "<?php// PHP program for Indexed Sequential Search function indexedSequentialSearch($arr, $n, $k){ $elements = array(); $indices = array(); $temp = array(); $j = 0; $ind = 0; $start=0; $end=0; $set = 0; for ($i = 0; $i < $n; $i += 3) { // Storing element $elements[$ind] = $arr[$i]; // Storing the index $indices[$ind] = $i; $ind++; } if ($k < $elements[0]) { echo \"Not found\"; } else { for ($i = 1; $i <=$ind; $i++) if ($k < $elements[$i]) { $start = $indices[$i - 1]; $set = 1; $end = $indices[$i]; break; } } if($set == 1) { $start = $indices[$i-1]; $end = $n; } for ($i = $start; $i <=$end; $i++) { if ($k == $arr[$i]) { $j = 1; break; } } if ($j == 1) echo \"Found at index \", $i; else echo \"Not found\";} // Driver code$arr = array( 6, 7, 8, 9, 10 );$n = count($arr); // Element to search$k = 10;indexedSequentialSearch($arr, $n, $k); // This code is contributed by shs..?>", "e": 7071, "s": 5903, "text": null }, { "code": null, "e": 7088, "s": 7071, "text": "Found at index 2" }, { "code": null, "e": 7101, "s": 7090, "text": "Shashank12" }, { "code": null, "e": 7109, "s": 7101, "text": "ankthon" }, { "code": null, "e": 7128, "s": 7109, "text": "raunaksrivastava22" }, { "code": null, "e": 7143, "s": 7128, "text": "anjalijoshi710" }, { "code": null, "e": 7150, "s": 7143, "text": "Picked" }, { "code": null, "e": 7174, "s": 7150, "text": "Technical Scripter 2018" }, { "code": null, "e": 7184, "s": 7174, "text": "Searching" }, { "code": null, "e": 7203, "s": 7184, "text": "Technical Scripter" }, { "code": null, "e": 7213, "s": 7203, "text": "Searching" }, { "code": null, "e": 7311, "s": 7213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7355, "s": 7311, "text": "Search, insert and delete in a sorted array" }, { "code": null, "e": 7430, "s": 7355, "text": "Given a sorted and rotated array, find if there is a pair with a given sum" }, { "code": null, "e": 7463, "s": 7430, "text": "Allocate minimum number of pages" }, { "code": null, "e": 7507, "s": 7463, "text": "Find common elements in three sorted arrays" }, { "code": null, "e": 7558, "s": 7507, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 7607, "s": 7558, "text": "Find whether an array is subset of another array" }, { "code": null, "e": 7628, "s": 7607, "text": "Next Smaller Element" } ]
How to change the TextBox Border Style in C#?
29 Nov, 2019 In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to style the border of the TextBox control with the help of BorderStyle property which makes your textbox more attractive. The default value of this property is Fixed3D. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the BorderStyle property of the TextBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You are allowed to place a TextBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the TextBox control to set the BorderStyle property of the TextBox.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the BorderStyle property of the TextBox programmatically with the help of given syntax: public System.Windows.Forms.BorderStyle BorderStyle { get; set; } Here, BorderStyle is used to represent the border type of TextBox control. And it will throw an InvalidEnumArgumentException if the value of the assigned to the property is not within the range of valid values for the enumeration. Following steps are used to set the BorderStyle property of the TextBox: Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox TextBox Mytextbox = new TextBox(); // Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the BorderStyle property of the TextBox provided by the TextBox class.// Set BorderStyle property Mytextbox.BorderStyle = BorderStyle.FixedSingle; // Set BorderStyle property Mytextbox.BorderStyle = BorderStyle.FixedSingle; Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form this.Controls.Add(Mytextbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Name"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.BorderStyle = BorderStyle.FixedSingle; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output: // Add this textbox to form this.Controls.Add(Mytextbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Name"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.BorderStyle = BorderStyle.FixedSingle; // Add this textbox to form this.Controls.Add(Mytextbox); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | Class and Object Extension Method in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 462, "s": 28, "text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to style the border of the TextBox control with the help of BorderStyle property which makes your textbox more attractive. The default value of this property is Fixed3D. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 581, "s": 462, "text": "1. Design-Time: It is the simplest way to set the BorderStyle property of the TextBox as shown in the following steps:" }, { "code": null, "e": 697, "s": 581, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 876, "s": 697, "text": "Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You are allowed to place a TextBox control anywhere on the windows form according to your need." }, { "code": null, "e": 1012, "s": 876, "text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the BorderStyle property of the TextBox.Output:" }, { "code": null, "e": 1020, "s": 1012, "text": "Output:" }, { "code": null, "e": 1200, "s": 1020, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the BorderStyle property of the TextBox programmatically with the help of given syntax:" }, { "code": null, "e": 1266, "s": 1200, "text": "public System.Windows.Forms.BorderStyle BorderStyle { get; set; }" }, { "code": null, "e": 1570, "s": 1266, "text": "Here, BorderStyle is used to represent the border type of TextBox control. And it will throw an InvalidEnumArgumentException if the value of the assigned to the property is not within the range of valid values for the enumeration. Following steps are used to set the BorderStyle property of the TextBox:" }, { "code": null, "e": 1714, "s": 1570, "text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1770, "s": 1714, "text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1955, "s": 1770, "text": "Step 2 : After creating TextBox, set the BorderStyle property of the TextBox provided by the TextBox class.// Set BorderStyle property\nMytextbox.BorderStyle = BorderStyle.FixedSingle;\n" }, { "code": null, "e": 2033, "s": 1955, "text": "// Set BorderStyle property\nMytextbox.BorderStyle = BorderStyle.FixedSingle;\n" }, { "code": null, "e": 3286, "s": 2033, "text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Name\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.BorderStyle = BorderStyle.FixedSingle; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:" }, { "code": null, "e": 3345, "s": 3286, "text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n" }, { "code": null, "e": 3354, "s": 3345, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Name\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.BorderStyle = BorderStyle.FixedSingle; // Add this textbox to form this.Controls.Add(Mytextbox); }}}", "e": 4464, "s": 3354, "text": null }, { "code": null, "e": 4472, "s": 4464, "text": "Output:" }, { "code": null, "e": 4503, "s": 4472, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 4506, "s": 4503, "text": "C#" }, { "code": null, "e": 4604, "s": 4506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4632, "s": 4604, "text": "C# Dictionary with examples" }, { "code": null, "e": 4663, "s": 4632, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4678, "s": 4663, "text": "C# | Delegates" }, { "code": null, "e": 4721, "s": 4678, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4770, "s": 4721, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4793, "s": 4770, "text": "C# | Method Overriding" }, { "code": null, "e": 4809, "s": 4793, "text": "C# | Data Types" }, { "code": null, "e": 4827, "s": 4809, "text": "C# | Constructors" }, { "code": null, "e": 4849, "s": 4827, "text": "C# | Class and Object" } ]
PHPunit | assertEmpty() Function
31 Jul, 2019 The assertEmpty() function is a builtin function in PHPUnit and is used to assert whether the data holder specified is empty or not. This assertion will return true in the case if the data holder provided is empty else return false. In case of true the asserted test case got passed else test case got failed. Syntax: assertEmpty( mixed $dataHolder, string $message = '' ) Parameters: This function accepts two parameters as shown in the above syntax. The parameters are described below: $dataHolder: This parameter is of any type which represent the data holder to be asserted. $message: This parameter takes string value. When the testcase got failed this string message got displayed as error message. Below programs illustrate the assertEmpty() function in PHPUnit: Program 1: <?phpuse PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testNegativeTestcaseForAssertEmpty() { $dataHolder = 'test data'; // Assert function to test whether given // data holder (variable) is empty or not $this->assertEmpty( $dataHolder, "data holder is not empty" ); }} ?> Output: PHPUnit 8.2.5 by Sebastian Bergmann and contributors. F 1 / 1 (100%) Time: 69 ms, Memory: 10.00 MB There was 1 failure: 1) GeeksPhpunitTestCase::testNegativeTestcaseForAssertEmpty data holder is not empty Failed asserting that a string is empty. /home/shivam/Documents/geeks/phpunit/abc.php:13 FAILURES! Tests: 1, Assertions: 1, Failures: 1. Program 2: <?phpuse PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testPositiveTestcaseForAssertEmpty() { $dataHolder = ''; // Assert function to test whether given // data holder (variable) is empty or not $this->assertEmpty( $dataHolder, "data holder is not empty" ); }} ?> Output: PHPUnit 8.2.5 by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time: 67 ms, Memory: 10.00 MB OK (1 test, 1 assertion) Note: To run testcases with phpunit follow steps from here. Also, assertEmpty() is supported by phpunit 7 and above. PHP-function PHP-PHPUnit PHP Web Technologies 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 check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2019" }, { "code": null, "e": 338, "s": 28, "text": "The assertEmpty() function is a builtin function in PHPUnit and is used to assert whether the data holder specified is empty or not. This assertion will return true in the case if the data holder provided is empty else return false. In case of true the asserted test case got passed else test case got failed." }, { "code": null, "e": 346, "s": 338, "text": "Syntax:" }, { "code": null, "e": 402, "s": 346, "text": "assertEmpty( mixed $dataHolder, string $message = '' )\n" }, { "code": null, "e": 517, "s": 402, "text": "Parameters: This function accepts two parameters as shown in the above syntax. The parameters are described below:" }, { "code": null, "e": 608, "s": 517, "text": "$dataHolder: This parameter is of any type which represent the data holder to be asserted." }, { "code": null, "e": 734, "s": 608, "text": "$message: This parameter takes string value. When the testcase got failed this string message got displayed as error message." }, { "code": null, "e": 799, "s": 734, "text": "Below programs illustrate the assertEmpty() function in PHPUnit:" }, { "code": null, "e": 810, "s": 799, "text": "Program 1:" }, { "code": "<?phpuse PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testNegativeTestcaseForAssertEmpty() { $dataHolder = 'test data'; // Assert function to test whether given // data holder (variable) is empty or not $this->assertEmpty( $dataHolder, \"data holder is not empty\" ); }} ?>", "e": 1196, "s": 810, "text": null }, { "code": null, "e": 1204, "s": 1196, "text": "Output:" }, { "code": null, "e": 1619, "s": 1204, "text": "PHPUnit 8.2.5 by Sebastian Bergmann and contributors.\n\nF 1 / 1 (100%)\n\nTime: 69 ms, Memory: 10.00 MB\n\nThere was 1 failure:\n\n1) GeeksPhpunitTestCase::testNegativeTestcaseForAssertEmpty\ndata holder is not empty\nFailed asserting that a string is empty.\n\n/home/shivam/Documents/geeks/phpunit/abc.php:13\n\nFAILURES!\nTests: 1, Assertions: 1, Failures: 1.\n" }, { "code": null, "e": 1630, "s": 1619, "text": "Program 2:" }, { "code": "<?phpuse PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase{ public function testPositiveTestcaseForAssertEmpty() { $dataHolder = ''; // Assert function to test whether given // data holder (variable) is empty or not $this->assertEmpty( $dataHolder, \"data holder is not empty\" ); }} ?>", "e": 2007, "s": 1630, "text": null }, { "code": null, "e": 2015, "s": 2007, "text": "Output:" }, { "code": null, "e": 2209, "s": 2015, "text": "PHPUnit 8.2.5 by Sebastian Bergmann and contributors.\n\n. 1 / 1 (100%)\n\nTime: 67 ms, Memory: 10.00 MB\n\nOK (1 test, 1 assertion)\n" }, { "code": null, "e": 2326, "s": 2209, "text": "Note: To run testcases with phpunit follow steps from here. Also, assertEmpty() is supported by phpunit 7 and above." }, { "code": null, "e": 2339, "s": 2326, "text": "PHP-function" }, { "code": null, "e": 2351, "s": 2339, "text": "PHP-PHPUnit" }, { "code": null, "e": 2355, "s": 2351, "text": "PHP" }, { "code": null, "e": 2372, "s": 2355, "text": "Web Technologies" }, { "code": null, "e": 2376, "s": 2372, "text": "PHP" }, { "code": null, "e": 2474, "s": 2376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2524, "s": 2474, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2564, "s": 2524, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2614, "s": 2564, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2659, "s": 2614, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2686, "s": 2659, "text": "Comparing two dates in PHP" }, { "code": null, "e": 2719, "s": 2686, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2781, "s": 2719, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2842, "s": 2781, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2892, "s": 2842, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Extract Text from Images with Python?
26 Dec, 2020 OCR (Optical Character Recognition) is the process of electronical conversion of Digital images into machine-encoded text. Where the digital image is generally an image that contains regions that resemble characters of a language. OCR is a field of research in pattern recognition, artificial intelligence and computer vision. This is due to the fact that newer OCR’s are trained by providing them sample data which is ran over a machine learning algorithm. This technique of extracting text from images is generally carried out in work environments where it is certain that the image would be containing text data. In this article, we would learn about extracting text from images. We would be utilizing python programming language for doing so. For enabling our python program to have Character recognition capabilities, we would be making use of pytesseract OCR library. The library could be installed onto our python environment by executing the following command in the command interpreter of the OS:- pip install pytesseract The library (if used on Windows OS) requires the tesseract.exe binary to be also present for proper installation of the library. During the installation of the aforementioned executable, we would be prompted to specify a path for it. This path needs to be remembered as it would be utilized later on in the code. For most installations the path would be C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe. Explanation: Firstly we imported the Image module from PIL library (for opening an image) and then pytesseract module from pytesseract library(for text extraction). Then after we defined the path_to_tesseract variable which contains the path to the executable binary (tesseract.exe) that we installed in the prerequisite (this path would depend on the location where the binary is installed). Then we defined the image_path variable which contains the path to the image file. This path is passed to the open() function to create an image object out of our image. After this, we assigned the pytesseract.tesseract_cmd variable the path stored in path_to_tesseract variable (this would be used by the library to find the executable and use it for extraction). After which we passed the image object (img) to image_to_string() function. This function takes in argument an image object and returns the text recognized inside it. In the end, we displayed the text which was found in the image using text[:-1] (due to a additional character (^L) that gets appended by default). Example 1: Image for demonstration: An image of white text with black background Below is the full implementation: Python3 from PIL import Imagefrom pytesseract import pytesseract # Defining paths to tesseract.exe# and the image we would be usingpath_to_tesseract = r"C:\Program Files\Tesseract-OCR\tesseract.exe"image_path = r"csv\sample_text.png" # Opening the image & storing it in an image objectimg = Image.open(image_path) # Providing the tesseract executable# location to pytesseract librarypytesseract.tesseract_cmd = path_to_tesseract # Passing the image object to image_to_string() function# This function will extract the text from the imagetext = pytesseract.image_to_string(img) # Displaying the extracted textprint(text[:-1]) Output: now children state should after above same long made such point run take call together few being would walk give Example 2: Image for demonstration: Code: Python3 from PIL import Imagefrom pytesseract import pytesseract # Defining paths to tesseract.exe # and the image we would be usingpath_to_tesseract = r"C:\Program Files\Tesseract-OCR\tesseract.exe"image_path = r"csv\d.jpg" # Opening the image & storing it in an image objectimg = Image.open(image_path) # Providing the tesseract # executable location to pytesseract librarypytesseract.tesseract_cmd = path_to_tesseract # Passing the image object to # image_to_string() function# This function will# extract the text from the imagetext = pytesseract.image_to_string(img) # Displaying the extracted textprint(text[:-1]) Output: Geeksforgeeks Image-Processing Picked Python-pil 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 ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Dec, 2020" }, { "code": null, "e": 802, "s": 54, "text": "OCR (Optical Character Recognition) is the process of electronical conversion of Digital images into machine-encoded text. Where the digital image is generally an image that contains regions that resemble characters of a language. OCR is a field of research in pattern recognition, artificial intelligence and computer vision. This is due to the fact that newer OCR’s are trained by providing them sample data which is ran over a machine learning algorithm. This technique of extracting text from images is generally carried out in work environments where it is certain that the image would be containing text data. In this article, we would learn about extracting text from images. We would be utilizing python programming language for doing so. " }, { "code": null, "e": 1062, "s": 802, "text": "For enabling our python program to have Character recognition capabilities, we would be making use of pytesseract OCR library. The library could be installed onto our python environment by executing the following command in the command interpreter of the OS:-" }, { "code": null, "e": 1086, "s": 1062, "text": "pip install pytesseract" }, { "code": null, "e": 1496, "s": 1086, "text": "The library (if used on Windows OS) requires the tesseract.exe binary to be also present for proper installation of the library. During the installation of the aforementioned executable, we would be prompted to specify a path for it. This path needs to be remembered as it would be utilized later on in the code. For most installations the path would be C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tesseract.exe. " }, { "code": null, "e": 1509, "s": 1496, "text": "Explanation:" }, { "code": null, "e": 2568, "s": 1509, "text": "Firstly we imported the Image module from PIL library (for opening an image) and then pytesseract module from pytesseract library(for text extraction). Then after we defined the path_to_tesseract variable which contains the path to the executable binary (tesseract.exe) that we installed in the prerequisite (this path would depend on the location where the binary is installed). Then we defined the image_path variable which contains the path to the image file. This path is passed to the open() function to create an image object out of our image. After this, we assigned the pytesseract.tesseract_cmd variable the path stored in path_to_tesseract variable (this would be used by the library to find the executable and use it for extraction). After which we passed the image object (img) to image_to_string() function. This function takes in argument an image object and returns the text recognized inside it. In the end, we displayed the text which was found in the image using text[:-1] (due to a additional character (^L) that gets appended by default)." }, { "code": null, "e": 2579, "s": 2568, "text": "Example 1:" }, { "code": null, "e": 2604, "s": 2579, "text": "Image for demonstration:" }, { "code": null, "e": 2649, "s": 2604, "text": "An image of white text with black background" }, { "code": null, "e": 2683, "s": 2649, "text": "Below is the full implementation:" }, { "code": null, "e": 2691, "s": 2683, "text": "Python3" }, { "code": "from PIL import Imagefrom pytesseract import pytesseract # Defining paths to tesseract.exe# and the image we would be usingpath_to_tesseract = r\"C:\\Program Files\\Tesseract-OCR\\tesseract.exe\"image_path = r\"csv\\sample_text.png\" # Opening the image & storing it in an image objectimg = Image.open(image_path) # Providing the tesseract executable# location to pytesseract librarypytesseract.tesseract_cmd = path_to_tesseract # Passing the image object to image_to_string() function# This function will extract the text from the imagetext = pytesseract.image_to_string(img) # Displaying the extracted textprint(text[:-1])", "e": 3313, "s": 2691, "text": null }, { "code": null, "e": 3321, "s": 3313, "text": "Output:" }, { "code": null, "e": 3379, "s": 3321, "text": "now children state should after above same long made such" }, { "code": null, "e": 3434, "s": 3379, "text": "point run take call together few being would walk give" }, { "code": null, "e": 3445, "s": 3434, "text": "Example 2:" }, { "code": null, "e": 3470, "s": 3445, "text": "Image for demonstration:" }, { "code": null, "e": 3476, "s": 3470, "text": "Code:" }, { "code": null, "e": 3484, "s": 3476, "text": "Python3" }, { "code": "from PIL import Imagefrom pytesseract import pytesseract # Defining paths to tesseract.exe # and the image we would be usingpath_to_tesseract = r\"C:\\Program Files\\Tesseract-OCR\\tesseract.exe\"image_path = r\"csv\\d.jpg\" # Opening the image & storing it in an image objectimg = Image.open(image_path) # Providing the tesseract # executable location to pytesseract librarypytesseract.tesseract_cmd = path_to_tesseract # Passing the image object to # image_to_string() function# This function will# extract the text from the imagetext = pytesseract.image_to_string(img) # Displaying the extracted textprint(text[:-1])", "e": 4101, "s": 3484, "text": null }, { "code": null, "e": 4109, "s": 4101, "text": "Output:" }, { "code": null, "e": 4123, "s": 4109, "text": "Geeksforgeeks" }, { "code": null, "e": 4140, "s": 4123, "text": "Image-Processing" }, { "code": null, "e": 4147, "s": 4140, "text": "Picked" }, { "code": null, "e": 4158, "s": 4147, "text": "Python-pil" }, { "code": null, "e": 4165, "s": 4158, "text": "Python" }, { "code": null, "e": 4263, "s": 4165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4281, "s": 4263, "text": "Python Dictionary" }, { "code": null, "e": 4323, "s": 4281, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4345, "s": 4323, "text": "Enumerate() in Python" }, { "code": null, "e": 4380, "s": 4345, "text": "Read a file line by line in Python" }, { "code": null, "e": 4412, "s": 4380, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4438, "s": 4412, "text": "Python String | replace()" }, { "code": null, "e": 4467, "s": 4438, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4494, "s": 4467, "text": "Python Classes and Objects" }, { "code": null, "e": 4515, "s": 4494, "text": "Python OOPs Concepts" } ]
Rearrange string such that no pair of adjacent characters are of the same type
21 Jun, 2021 Given alphanumeric string str, the task is to rearrange the string such that no two adjacent characters are of the same type, i.e., no two adjacent characters can be alphabets or digits. If no such arrangement is possible, print -1. Examples: Input: str = “geeks2020”Output: g2e0e2k0s Input: str = “IPL20”Output: I2P0L Naive Approach: The simplest approach is to generate all possible permutation of the given string and for every permutation, check if it satisfies the given conditions or not. If fount to be true for any permutation, print that permutation. If no such permutation exists, then print -1. Time Complexity: O(2N)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, the idea is to store all the alphabets and the digits separately and rearrange them by placing them alternatively in the resultant string. If the count of the alphabets and the digits differ by more than 1, print -1 as no desired arrangement is possible. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to rearrange given// alphanumeric string such that// no two adjacent characters// are of the same typestring rearrange(string s){ // Stores alphabets and digits string s1 = "", s2 = ""; // Store the alphabets and digits // separately in the strings for (char x : s) { isalpha(x) ? s1.push_back(x) : s2.push_back(x); } // Stores the count of // alphabets and digits int n = s1.size(); int m = s2.size(); // If respective counts // differ by 1 if (abs(n - m) > 1) // Desired arrangement // not possible return "-1"; // Stores the indexes int i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit int flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n and j < m) { // If current character // needs to be alphabet if (flag) s[k++] = s1[i++]; // If current character // needs to be a digit else s[k++] = s2[j++]; // Flip flag for alternate // arrangement flag = !flag; } // Return resultant string return s;} // Driver Codeint main(){ // Given String string str = "geeks2020"; // Function Call cout << rearrange(str) << endl; return 0;} // Java program to implement// the above approachclass GFG{ // Function to rearrange given// alphanumeric String such that// no two adjacent characters// are of the same typestatic String rearrange(String s){ // Stores alphabets and digits String s1 = "", s2 = "", ans = ""; char []s3 = s.toCharArray(); // Store the alphabets and digits // separately in the Strings for (char x : s3) { if(x >= 'a' && x <= 'z') s1 += x ; else s2 += x; } // Stores the count of // alphabets and digits int n = s1.length(); int m = s2.length(); // If respective counts // differ by 1 if (Math.abs(n - m) > 1) // Desired arrangement // not possible return "-1"; // Stores the indexes int i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit int flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n && j < m) { // If current character // needs to be alphabet if (flag != 0) ans += s1.charAt(i++); // If current character // needs to be a digit else ans += s2.charAt(j++); // Flip flag for alternate // arrangement if(flag == 1) flag = 0; else flag = 1; } // Return resultant String return ans;} // Driver Codepublic static void main(String[] args){ // Given String String str = "geeks2020"; // Function Call System.out.print(rearrange(str) + "\n");}} // This code is contributed by gauravrajput1 # Python3 program to implement# the above approach # Function to rearrange given# alphanumeric such that no# two adjacent characters# are of the same typedef rearrange(s): # Stores alphabets and digits s1 = [] s2 = [] # Store the alphabets and digits # separately in the strings for x in s: if x.isalpha(): s1.append(x) else: s2.append(x) # Stores the count of # alphabets and digits n = len(s1) m = len(s2) # If respective counts # differ by 1 if (abs(n - m) > 1): # Desired arrangement # not possible return "-1" # Stores the indexes i = 0 j = 0 k = 0 # Check if first character # should be alphabet or digit flag = 0 if (n >= m): flag = 1 else: flag = 0 # Place alphabets and digits # alternatively while (i < n and j < m): # If current character # needs to be alphabet if (flag): s[k] = s1[i] k += 1 i += 1 # If current character # needs to be a digit else: s[k] = s2[j] k += 1 j += 1 # Flip flag for alternate # arrangement flag = not flag # Return resultant string return "".join(s) # Driver Codeif __name__ == '__main__': # Given String str = "geeks2020" str1 = [i for i in str] # Function call print(rearrange(str1)) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System;class GFG{ // Function to rearrange given// alphanumeric String such that// no two adjacent characters// are of the same typestatic String rearrange(String s){ // Stores alphabets and digits String s1 = "", s2 = "", ans = ""; char []s3 = s.ToCharArray(); // Store the alphabets and digits // separately in the Strings foreach (char x in s3) { if(x >= 'a' && x <= 'z') s1 += x ; else s2 += x; } // Stores the count of // alphabets and digits int n = s1.Length; int m = s2.Length; // If respective counts // differ by 1 if (Math.Abs(n - m) > 1) // Desired arrangement // not possible return "-1"; // Stores the indexes int i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit int flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n && j < m) { // If current character // needs to be alphabet if (flag != 0) ans += s1[i++]; // If current character // needs to be a digit else ans += s2[j++]; // Flip flag for alternate // arrangement if(flag == 1) flag = 0; else flag = 1; } // Return resultant String return ans;} // Driver Codepublic static void Main(String[] args){ // Given String String str = "geeks2020"; // Function Call Console.Write(rearrange(str) + "\n");}} // This code is contributed by 29AjayKumar <script>// Javascript program to implement// the above approach // Function to rearrange given// alphanumeric String such that// no two adjacent characters// are of the same typefunction rearrange(s){ // Stores alphabets and digits let s1 = "", s2 = "", ans = ""; let s3 = s.split(""); // Store the alphabets and digits // separately in the Strings for (let x = 0; x < s3.length; x++) { if(s3[x] >= 'a' && s3[x] <= 'z') s1 += s3[x] ; else s2 += s3[x]; } // Stores the count of // alphabets and digits let n = s1.length; let m = s2.length; // If respective counts // differ by 1 if (Math.abs(n - m) > 1) // Desired arrangement // not possible return "-1"; // Stores the indexes let i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit let flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n && j < m) { // If current character // needs to be alphabet if (flag != 0) ans += s1[i++]; // If current character // needs to be a digit else ans += s2[j++]; // Flip flag for alternate // arrangement if(flag == 1) flag = 0; else flag = 1; } // Return resultant String return ans;} // Driver Code// Given Stringlet str = "geeks2020"; // Function Calldocument.write(rearrange(str) + "<br>"); // This code is contributed by patel2127</script> g2e0e2k00 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 GauravRajput1 29AjayKumar patel2127 frequency-counting permutation Hash Strings Hash Strings permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Real-time application of Data Structures Find k numbers with most occurrences in the given array Find the length of largest subarray with 0 sum Non-Repeating Element 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": 53, "s": 25, "text": "\n21 Jun, 2021" }, { "code": null, "e": 286, "s": 53, "text": "Given alphanumeric string str, the task is to rearrange the string such that no two adjacent characters are of the same type, i.e., no two adjacent characters can be alphabets or digits. If no such arrangement is possible, print -1." }, { "code": null, "e": 296, "s": 286, "text": "Examples:" }, { "code": null, "e": 338, "s": 296, "text": "Input: str = “geeks2020”Output: g2e0e2k0s" }, { "code": null, "e": 372, "s": 338, "text": "Input: str = “IPL20”Output: I2P0L" }, { "code": null, "e": 659, "s": 372, "text": "Naive Approach: The simplest approach is to generate all possible permutation of the given string and for every permutation, check if it satisfies the given conditions or not. If fount to be true for any permutation, print that permutation. If no such permutation exists, then print -1." }, { "code": null, "e": 703, "s": 659, "text": "Time Complexity: O(2N)Auxiliary Space: O(1)" }, { "code": null, "e": 1011, "s": 703, "text": "Efficient Approach: To optimize the above approach, the idea is to store all the alphabets and the digits separately and rearrange them by placing them alternatively in the resultant string. If the count of the alphabets and the digits differ by more than 1, print -1 as no desired arrangement is possible." }, { "code": null, "e": 1062, "s": 1011, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1066, "s": 1062, "text": "C++" }, { "code": null, "e": 1071, "s": 1066, "text": "Java" }, { "code": null, "e": 1079, "s": 1071, "text": "Python3" }, { "code": null, "e": 1082, "s": 1079, "text": "C#" }, { "code": null, "e": 1093, "s": 1082, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to rearrange given// alphanumeric string such that// no two adjacent characters// are of the same typestring rearrange(string s){ // Stores alphabets and digits string s1 = \"\", s2 = \"\"; // Store the alphabets and digits // separately in the strings for (char x : s) { isalpha(x) ? s1.push_back(x) : s2.push_back(x); } // Stores the count of // alphabets and digits int n = s1.size(); int m = s2.size(); // If respective counts // differ by 1 if (abs(n - m) > 1) // Desired arrangement // not possible return \"-1\"; // Stores the indexes int i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit int flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n and j < m) { // If current character // needs to be alphabet if (flag) s[k++] = s1[i++]; // If current character // needs to be a digit else s[k++] = s2[j++]; // Flip flag for alternate // arrangement flag = !flag; } // Return resultant string return s;} // Driver Codeint main(){ // Given String string str = \"geeks2020\"; // Function Call cout << rearrange(str) << endl; return 0;}", "e": 2522, "s": 1093, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to rearrange given// alphanumeric String such that// no two adjacent characters// are of the same typestatic String rearrange(String s){ // Stores alphabets and digits String s1 = \"\", s2 = \"\", ans = \"\"; char []s3 = s.toCharArray(); // Store the alphabets and digits // separately in the Strings for (char x : s3) { if(x >= 'a' && x <= 'z') s1 += x ; else s2 += x; } // Stores the count of // alphabets and digits int n = s1.length(); int m = s2.length(); // If respective counts // differ by 1 if (Math.abs(n - m) > 1) // Desired arrangement // not possible return \"-1\"; // Stores the indexes int i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit int flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n && j < m) { // If current character // needs to be alphabet if (flag != 0) ans += s1.charAt(i++); // If current character // needs to be a digit else ans += s2.charAt(j++); // Flip flag for alternate // arrangement if(flag == 1) flag = 0; else flag = 1; } // Return resultant String return ans;} // Driver Codepublic static void main(String[] args){ // Given String String str = \"geeks2020\"; // Function Call System.out.print(rearrange(str) + \"\\n\");}} // This code is contributed by gauravrajput1", "e": 3974, "s": 2522, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to rearrange given# alphanumeric such that no# two adjacent characters# are of the same typedef rearrange(s): # Stores alphabets and digits s1 = [] s2 = [] # Store the alphabets and digits # separately in the strings for x in s: if x.isalpha(): s1.append(x) else: s2.append(x) # Stores the count of # alphabets and digits n = len(s1) m = len(s2) # If respective counts # differ by 1 if (abs(n - m) > 1): # Desired arrangement # not possible return \"-1\" # Stores the indexes i = 0 j = 0 k = 0 # Check if first character # should be alphabet or digit flag = 0 if (n >= m): flag = 1 else: flag = 0 # Place alphabets and digits # alternatively while (i < n and j < m): # If current character # needs to be alphabet if (flag): s[k] = s1[i] k += 1 i += 1 # If current character # needs to be a digit else: s[k] = s2[j] k += 1 j += 1 # Flip flag for alternate # arrangement flag = not flag # Return resultant string return \"\".join(s) # Driver Codeif __name__ == '__main__': # Given String str = \"geeks2020\" str1 = [i for i in str] # Function call print(rearrange(str1)) # This code is contributed by mohit kumar 29", "e": 5463, "s": 3974, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to rearrange given// alphanumeric String such that// no two adjacent characters// are of the same typestatic String rearrange(String s){ // Stores alphabets and digits String s1 = \"\", s2 = \"\", ans = \"\"; char []s3 = s.ToCharArray(); // Store the alphabets and digits // separately in the Strings foreach (char x in s3) { if(x >= 'a' && x <= 'z') s1 += x ; else s2 += x; } // Stores the count of // alphabets and digits int n = s1.Length; int m = s2.Length; // If respective counts // differ by 1 if (Math.Abs(n - m) > 1) // Desired arrangement // not possible return \"-1\"; // Stores the indexes int i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit int flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n && j < m) { // If current character // needs to be alphabet if (flag != 0) ans += s1[i++]; // If current character // needs to be a digit else ans += s2[j++]; // Flip flag for alternate // arrangement if(flag == 1) flag = 0; else flag = 1; } // Return resultant String return ans;} // Driver Codepublic static void Main(String[] args){ // Given String String str = \"geeks2020\"; // Function Call Console.Write(rearrange(str) + \"\\n\");}} // This code is contributed by 29AjayKumar", "e": 6908, "s": 5463, "text": null }, { "code": "<script>// Javascript program to implement// the above approach // Function to rearrange given// alphanumeric String such that// no two adjacent characters// are of the same typefunction rearrange(s){ // Stores alphabets and digits let s1 = \"\", s2 = \"\", ans = \"\"; let s3 = s.split(\"\"); // Store the alphabets and digits // separately in the Strings for (let x = 0; x < s3.length; x++) { if(s3[x] >= 'a' && s3[x] <= 'z') s1 += s3[x] ; else s2 += s3[x]; } // Stores the count of // alphabets and digits let n = s1.length; let m = s2.length; // If respective counts // differ by 1 if (Math.abs(n - m) > 1) // Desired arrangement // not possible return \"-1\"; // Stores the indexes let i = 0, j = 0, k = 0; // Check if first character // should be alphabet or digit let flag = (n >= m) ? 1 : 0; // Place alphabets and digits // alternatively while (i < n && j < m) { // If current character // needs to be alphabet if (flag != 0) ans += s1[i++]; // If current character // needs to be a digit else ans += s2[j++]; // Flip flag for alternate // arrangement if(flag == 1) flag = 0; else flag = 1; } // Return resultant String return ans;} // Driver Code// Given Stringlet str = \"geeks2020\"; // Function Calldocument.write(rearrange(str) + \"<br>\"); // This code is contributed by patel2127</script>", "e": 8324, "s": 6908, "text": null }, { "code": null, "e": 8334, "s": 8324, "text": "g2e0e2k00" }, { "code": null, "e": 8379, "s": 8336, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 8394, "s": 8379, "text": "mohit kumar 29" }, { "code": null, "e": 8408, "s": 8394, "text": "GauravRajput1" }, { "code": null, "e": 8420, "s": 8408, "text": "29AjayKumar" }, { "code": null, "e": 8430, "s": 8420, "text": "patel2127" }, { "code": null, "e": 8449, "s": 8430, "text": "frequency-counting" }, { "code": null, "e": 8461, "s": 8449, "text": "permutation" }, { "code": null, "e": 8466, "s": 8461, "text": "Hash" }, { "code": null, "e": 8474, "s": 8466, "text": "Strings" }, { "code": null, "e": 8479, "s": 8474, "text": "Hash" }, { "code": null, "e": 8487, "s": 8479, "text": "Strings" }, { "code": null, "e": 8499, "s": 8487, "text": "permutation" }, { "code": null, "e": 8597, "s": 8499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8635, "s": 8597, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 8676, "s": 8635, "text": "Real-time application of Data Structures" }, { "code": null, "e": 8732, "s": 8676, "text": "Find k numbers with most occurrences in the given array" }, { "code": null, "e": 8779, "s": 8732, "text": "Find the length of largest subarray with 0 sum" }, { "code": null, "e": 8801, "s": 8779, "text": "Non-Repeating Element" }, { "code": null, "e": 8847, "s": 8801, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 8872, "s": 8847, "text": "Reverse a string in Java" }, { "code": null, "e": 8932, "s": 8872, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8947, "s": 8932, "text": "C++ Data Types" } ]
Python Pickling
Python pickle module is used for serializing and de-serializing python object structures. The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s and 1s) is called pickling or serialization or flattening or marshalling. We can converts the byte stream (generated through pickling) back into python objects by a process called as unpickling. Why Pickle?: In real world sceanario, the use pickling and unpickling are widespread as they allow us to easily transfer data from one server/system to another and then store it in a file or database. Precaution: It is advisable not to unpickle data received from an untrusted source as they may pose security threat. However, the pickle module has no way of knowing or raise alarm while pickling malicious data. Only after importing pickle module we can do pickling and unpickling. Importing pickle can be done using the following command − import pickle Pickle examples: Below is a simple program on how to pickle a list: Pickle a simple list: Pickle_list1.py import pickle mylist = ['a', 'b', 'c', 'd'] with open('datafile.txt', 'wb') as fh: pickle.dump(mylist, fh) In the above code, list – “mylist” contains four elements (‘a’, ‘b’, ‘c’, ‘d’). We open the file in “wb” mode instead of “w” as all the operations are done using bytes in the current working directory. A new file named “datafile.txt” is created, which converts the mylist data in the byte stream. Unpickle a simple list: unpickle_list1.py import pickle pickle_off = open ("datafile.txt", "rb") emp = pickle.load(pickle_off) print(emp) Output: On running above scripts, you can see your mylist data again as output. ['a', 'b', 'c', 'd'] Pickle a simple dictionary − import pickle EmpID = {1:"Zack",2:"53050",3:"IT",4:"38",5:"Flipkart"} pickling_on = open("EmpID.pickle","wb") pickle.dump(EmpID, pickling_on) pickling_on.close() Unpickle a dictionary − import pickle pickle_off = open("EmpID.pickle", 'rb') EmpID = pickle.load(pickle_off) print(EmpID) On running above script(unpickle) we get our dictionary back as we initialized earlier. Also, please note because we are reading bytes here, we have used “rb” instead of “r”. {1: 'Zack', 2: '53050', 3: 'IT', 4: '38', 5: 'Flipkart'} Below are some of the common exceptions raised while dealing with pickle module − Pickle.PicklingError: If the pickle object doesn’t support pickling, this exception is raised. Pickle.PicklingError: If the pickle object doesn’t support pickling, this exception is raised. Pickle.UnpicklingError: In case the file contains bad or corrupted data. Pickle.UnpicklingError: In case the file contains bad or corrupted data. EOFError: In case the end of file is detected, this exception is raised. EOFError: In case the end of file is detected, this exception is raised. Prons: Comes handy to save complicated data. Comes handy to save complicated data. Easy to use, lighter and doesn’t require several lines of code. Easy to use, lighter and doesn’t require several lines of code. The pickled file generated is not easily readable and thus provide some security. The pickled file generated is not easily readable and thus provide some security. Cons: Languages other than python may not able to reconstruct pickled python objects. Languages other than python may not able to reconstruct pickled python objects. Risk of unpickling data from malicious sources. Risk of unpickling data from malicious sources.
[ { "code": null, "e": 1564, "s": 1187, "text": "Python pickle module is used for serializing and de-serializing python object structures. The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s and 1s) is called pickling or serialization or flattening or marshalling. We can converts the byte stream (generated through pickling) back into python objects by a process called as unpickling." }, { "code": null, "e": 1765, "s": 1564, "text": "Why Pickle?: In real world\nsceanario, the use pickling and unpickling are widespread as they allow us to easily transfer data from one server/system to another and then store it in a file or database." }, { "code": null, "e": 1977, "s": 1765, "text": "Precaution: It is advisable not to unpickle data received from an untrusted source as they may pose security threat. However, the pickle module has no way of knowing or raise alarm while pickling malicious data." }, { "code": null, "e": 2106, "s": 1977, "text": "Only after importing pickle module we can do pickling and unpickling. Importing pickle can be done using the following command −" }, { "code": null, "e": 2120, "s": 2106, "text": "import pickle" }, { "code": null, "e": 2137, "s": 2120, "text": "Pickle examples:" }, { "code": null, "e": 2188, "s": 2137, "text": "Below is a simple program on how to pickle a list:" }, { "code": null, "e": 2226, "s": 2188, "text": "Pickle a simple list: Pickle_list1.py" }, { "code": null, "e": 2336, "s": 2226, "text": "import pickle\nmylist = ['a', 'b', 'c', 'd']\nwith open('datafile.txt', 'wb') as fh:\n pickle.dump(mylist, fh)" }, { "code": null, "e": 2633, "s": 2336, "text": "In the above code, list – “mylist” contains four elements (‘a’, ‘b’, ‘c’, ‘d’). We open the file in “wb” mode instead of “w” as all the operations are done using bytes in the current working directory. A new file named “datafile.txt” is created, which converts the mylist data in the byte stream." }, { "code": null, "e": 2675, "s": 2633, "text": "Unpickle a simple list: unpickle_list1.py" }, { "code": null, "e": 2771, "s": 2675, "text": "import pickle\npickle_off = open (\"datafile.txt\", \"rb\")\nemp = pickle.load(pickle_off)\nprint(emp)" }, { "code": null, "e": 2851, "s": 2771, "text": "Output: On running above scripts, you can see your mylist data again as output." }, { "code": null, "e": 2872, "s": 2851, "text": "['a', 'b', 'c', 'd']" }, { "code": null, "e": 2901, "s": 2872, "text": "Pickle a simple dictionary −" }, { "code": null, "e": 3063, "s": 2901, "text": "import pickle\nEmpID = {1:\"Zack\",2:\"53050\",3:\"IT\",4:\"38\",5:\"Flipkart\"}\npickling_on = open(\"EmpID.pickle\",\"wb\")\npickle.dump(EmpID, pickling_on)\npickling_on.close()" }, { "code": null, "e": 3087, "s": 3063, "text": "Unpickle a dictionary −" }, { "code": null, "e": 3186, "s": 3087, "text": "import pickle\npickle_off = open(\"EmpID.pickle\", 'rb')\nEmpID = pickle.load(pickle_off)\nprint(EmpID)" }, { "code": null, "e": 3361, "s": 3186, "text": "On running above script(unpickle) we get our dictionary back as we initialized earlier. Also, please note because we are reading bytes here, we have used “rb” instead of “r”." }, { "code": null, "e": 3418, "s": 3361, "text": "{1: 'Zack', 2: '53050', 3: 'IT', 4: '38', 5: 'Flipkart'}" }, { "code": null, "e": 3500, "s": 3418, "text": "Below are some of the common exceptions raised while dealing with pickle module −" }, { "code": null, "e": 3595, "s": 3500, "text": "Pickle.PicklingError: If the pickle object doesn’t support pickling, this exception is raised." }, { "code": null, "e": 3690, "s": 3595, "text": "Pickle.PicklingError: If the pickle object doesn’t support pickling, this exception is raised." }, { "code": null, "e": 3763, "s": 3690, "text": "Pickle.UnpicklingError: In case the file contains bad or corrupted data." }, { "code": null, "e": 3836, "s": 3763, "text": "Pickle.UnpicklingError: In case the file contains bad or corrupted data." }, { "code": null, "e": 3909, "s": 3836, "text": "EOFError: In case the end of file is detected, this exception is raised." }, { "code": null, "e": 3982, "s": 3909, "text": "EOFError: In case the end of file is detected, this exception is raised." }, { "code": null, "e": 3989, "s": 3982, "text": "Prons:" }, { "code": null, "e": 4027, "s": 3989, "text": "Comes handy to save complicated data." }, { "code": null, "e": 4065, "s": 4027, "text": "Comes handy to save complicated data." }, { "code": null, "e": 4129, "s": 4065, "text": "Easy to use, lighter and doesn’t require several lines of code." }, { "code": null, "e": 4193, "s": 4129, "text": "Easy to use, lighter and doesn’t require several lines of code." }, { "code": null, "e": 4275, "s": 4193, "text": "The pickled file generated is not easily readable and thus provide some security." }, { "code": null, "e": 4357, "s": 4275, "text": "The pickled file generated is not easily readable and thus provide some security." }, { "code": null, "e": 4363, "s": 4357, "text": "Cons:" }, { "code": null, "e": 4443, "s": 4363, "text": "Languages other than python may not able to reconstruct pickled python objects." }, { "code": null, "e": 4523, "s": 4443, "text": "Languages other than python may not able to reconstruct pickled python objects." }, { "code": null, "e": 4571, "s": 4523, "text": "Risk of unpickling data from malicious sources." }, { "code": null, "e": 4619, "s": 4571, "text": "Risk of unpickling data from malicious sources." } ]
jQuery | Autocomplete Selection Event
03 Aug, 2021 In the web world, it is a very common practice to use autocomplete typeahead input. For example user address field. For this, a very common UI feature is available in jQuery.In the process of searching a specific value, the jQuery UI autocomplete selection feature provides the user with some string suggestions for the input area which effectively saves time.The autocomplete select action is triggered when the user selects one of the options from the pre-populated list.The very common universal example is google suggestion box used by millions of users all around. The very basic purpose of this feature is to replace the value of the text field with the selected value from the list by the user. It triggers multiple events like on focus, key-up event or on change of user entry which are used to call different functions returning objects describing the focused or selected item.The implementation is done using various ways like fetching data from the database table for populating values for the user entry field. It selects the strings from the related database which starts with user-entered keywords. Unlike dynamic implementation, you can do the static implementation. For example using an XML file or list is taken from an array of variables. select( event, ui ) This function triggered whenever any option from the pop-up list is selected. It contains two parameters which are listed below: event: This parameter mentions the event triggered by the user. ui: This parameter mentions the object which contains the name and value properties of the selected items. Code snippet: $( ".selector" ).autocomplete({ select: function( event, ui ) {} }); Example 1: <!doctype html><html> <head> <title> jQuery Autocomplete Selection Event </title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"> </script></head> <body> <label>Select Technology : </label> <input id="autocompleteInput"> <script> var tags = [ "jQuery", "java", "php", "MySQL", "javascript", "html", "C#", "C", "MongoDB" ]; $("#autocompleteInput").autocomplete({ source: tags }); </script></body> </html> Output: Note: In the above example, source code actually defines the data to be used for selection. Example 2: <!DOCTYPE html> <html> <head> <title> jQuery AutoComplete selection </title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/ui-lightness/jquery-ui.css"/> <script src= "http://code.jquery.com/jquery-2.1.3.js"> </script> <script src= "http://code.jquery.com/ui/1.11.2/jquery-ui.js"> </script> <script> $(document).ready(function() { var tags = [ "Washington", "Cincinnati", "Dubai", "Dublin", "Colombo", "Culcutta" ]; $('#input').autocomplete({ source : tags, select : showResult, focus : showResult, change :showResult }) function showResult(event, ui) { $('#cityName').text(ui.item.label) } }); </script></head> <body> <form> <div class="ui-widget"> <label for="input">City Name : </label> <input id="input"/><br> Label of City Name: <div id="cityName"></div> </div> </form></body> </html> Output: Note: From the above two code examples, you can observe that source parameter takes up list of string options such as array or result from a function callback. jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using Checkboxes ? How to redirect to a particular section of a page using HTML or jQuery? How to get the value in an input text box using jQuery ? How to Dynamically Add/Remove Table Rows using jQuery ? jQuery | children() with Examples How to insert spaces/tabs in text using HTML/CSS? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 1285, "s": 28, "text": "In the web world, it is a very common practice to use autocomplete typeahead input. For example user address field. For this, a very common UI feature is available in jQuery.In the process of searching a specific value, the jQuery UI autocomplete selection feature provides the user with some string suggestions for the input area which effectively saves time.The autocomplete select action is triggered when the user selects one of the options from the pre-populated list.The very common universal example is google suggestion box used by millions of users all around. The very basic purpose of this feature is to replace the value of the text field with the selected value from the list by the user. It triggers multiple events like on focus, key-up event or on change of user entry which are used to call different functions returning objects describing the focused or selected item.The implementation is done using various ways like fetching data from the database table for populating values for the user entry field. It selects the strings from the related database which starts with user-entered keywords. Unlike dynamic implementation, you can do the static implementation. For example using an XML file or list is taken from an array of variables." }, { "code": null, "e": 1434, "s": 1285, "text": "select( event, ui ) This function triggered whenever any option from the pop-up list is selected. It contains two parameters which are listed below:" }, { "code": null, "e": 1498, "s": 1434, "text": "event: This parameter mentions the event triggered by the user." }, { "code": null, "e": 1605, "s": 1498, "text": "ui: This parameter mentions the object which contains the name and value properties of the selected items." }, { "code": null, "e": 1619, "s": 1605, "text": "Code snippet:" }, { "code": null, "e": 1693, "s": 1619, "text": "$( \".selector\" ).autocomplete({\n select: function( event, ui ) {}\n});\n" }, { "code": null, "e": 1704, "s": 1693, "text": "Example 1:" }, { "code": "<!doctype html><html> <head> <title> jQuery Autocomplete Selection Event </title> <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css\"> <script src=\"//code.jquery.com/jquery-1.12.4.js\"></script> <script src=\"//code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script></head> <body> <label>Select Technology : </label> <input id=\"autocompleteInput\"> <script> var tags = [ \"jQuery\", \"java\", \"php\", \"MySQL\", \"javascript\", \"html\", \"C#\", \"C\", \"MongoDB\" ]; $(\"#autocompleteInput\").autocomplete({ source: tags }); </script></body> </html>", "e": 2408, "s": 1704, "text": null }, { "code": null, "e": 2416, "s": 2408, "text": "Output:" }, { "code": null, "e": 2508, "s": 2416, "text": "Note: In the above example, source code actually defines the data to be used for selection." }, { "code": null, "e": 2519, "s": 2508, "text": "Example 2:" }, { "code": "<!DOCTYPE html> <html> <head> <title> jQuery AutoComplete selection </title> <link rel=\"stylesheet\" href=\"http://code.jquery.com/ui/1.11.3/themes/ui-lightness/jquery-ui.css\"/> <script src= \"http://code.jquery.com/jquery-2.1.3.js\"> </script> <script src= \"http://code.jquery.com/ui/1.11.2/jquery-ui.js\"> </script> <script> $(document).ready(function() { var tags = [ \"Washington\", \"Cincinnati\", \"Dubai\", \"Dublin\", \"Colombo\", \"Culcutta\" ]; $('#input').autocomplete({ source : tags, select : showResult, focus : showResult, change :showResult }) function showResult(event, ui) { $('#cityName').text(ui.item.label) } }); </script></head> <body> <form> <div class=\"ui-widget\"> <label for=\"input\">City Name : </label> <input id=\"input\"/><br> Label of City Name: <div id=\"cityName\"></div> </div> </form></body> </html>", "e": 3753, "s": 2519, "text": null }, { "code": null, "e": 3761, "s": 3753, "text": "Output:" }, { "code": null, "e": 3921, "s": 3761, "text": "Note: From the above two code examples, you can observe that source parameter takes up list of string options such as array or result from a function callback." }, { "code": null, "e": 4189, "s": 3921, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 4201, "s": 4189, "text": "jQuery-Misc" }, { "code": null, "e": 4208, "s": 4201, "text": "Picked" }, { "code": null, "e": 4215, "s": 4208, "text": "JQuery" }, { "code": null, "e": 4232, "s": 4215, "text": "Web Technologies" }, { "code": null, "e": 4259, "s": 4232, "text": "Web technologies Questions" }, { "code": null, "e": 4357, "s": 4259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4410, "s": 4357, "text": "How to Show and Hide div elements using Checkboxes ?" }, { "code": null, "e": 4482, "s": 4410, "text": "How to redirect to a particular section of a page using HTML or jQuery?" }, { "code": null, "e": 4539, "s": 4482, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 4595, "s": 4539, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 4629, "s": 4595, "text": "jQuery | children() with Examples" }, { "code": null, "e": 4679, "s": 4629, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4712, "s": 4679, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4774, "s": 4712, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4807, "s": 4774, "text": "Node.js fs.readFileSync() Method" } ]
How to use superscript with ggplot2 in R?
17 Jun, 2021 In this article, we will see how to use superscript with ggplot2 in the R programming language. You can use Superscript anywhere in the plot where you want. The function will remain the same to use superscript values at all places. Here we will use superscript value at ggplot2 title and at the Label of Axis. For that, the first ggplot2 package is loaded using the library() function. Data in Use: To create an R plot, we use ggplot() function and to make a line graph, add geom_line() function to ggplot() function. Let us first plot it regularly so that the difference is apparent. Example: R # Load Packagelibrary("ggplot2") # Create a DataFrame DF <- data.frame(X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Y = c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)) # Create a LineGraphggplot(DF,aes(X, Y))+ geom_line(size = 2, color = "green") Output: Simple Line Graph Here bquote() function is uses to produce a superscript label. Syntax : bquote(expr) Parameter : expr : language object bquote() For SuperScript : bquote(‘string'(math superscript Notation)) For assigning the labels to X and Y axis, we will use xlab() and ylab() function to give labels to X and Y Axis respectively. Syntax : xlab(“Label for X-Axis”) Syntax : ylab(“Label for Y-Axis”) Example: R # Load ggplot2 Packagelibrary("ggplot2") # Create a DataFrame For PlottingDF <- data.frame(X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Y = c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)) # Create ggplot2 Line Graph with # SuperScripted value of Label of # Y Axis.ggplot(DF,aes(X, Y))+ geom_line(size = 2, color = "green")+ xlab('X-axis (number)')+ ylab(bquote('Y-axis '(number^2))) Output: ggplot2 plot with superscripted label of Y Axis To add superscript as a title add bquote function with value inside ggtitle(). Syntax : ggtitle(“Title for Plot”) Parameter : like xlab and ylab functions, we can give the title for plot directly using this function. Here we will bquote() function for writing Superscript value ( Number VS Number2 ) as a title of plot. Return : Title to plot. Example: R # Load ggplot2 Packagelibrary("ggplot2") # Create a DataFrame For PlottingDF <- data.frame(X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Y = c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)) # Create ggplot2 Line Graph with SuperScripted# value of Title of plotggplot(DF,aes(X, Y))+ geom_line(size = 2, color = "green")+ ggtitle(bquote('Number VS'~Number^2)) Output: ggplot2 plot with superscripted Title Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 338, "s": 28, "text": "In this article, we will see how to use superscript with ggplot2 in the R programming language. You can use Superscript anywhere in the plot where you want. The function will remain the same to use superscript values at all places. Here we will use superscript value at ggplot2 title and at the Label of Axis." }, { "code": null, "e": 414, "s": 338, "text": "For that, the first ggplot2 package is loaded using the library() function." }, { "code": null, "e": 427, "s": 414, "text": "Data in Use:" }, { "code": null, "e": 613, "s": 427, "text": "To create an R plot, we use ggplot() function and to make a line graph, add geom_line() function to ggplot() function. Let us first plot it regularly so that the difference is apparent." }, { "code": null, "e": 622, "s": 613, "text": "Example:" }, { "code": null, "e": 624, "s": 622, "text": "R" }, { "code": "# Load Packagelibrary(\"ggplot2\") # Create a DataFrame DF <- data.frame(X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Y = c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)) # Create a LineGraphggplot(DF,aes(X, Y))+ geom_line(size = 2, color = \"green\")", "e": 950, "s": 624, "text": null }, { "code": null, "e": 958, "s": 950, "text": "Output:" }, { "code": null, "e": 976, "s": 958, "text": "Simple Line Graph" }, { "code": null, "e": 1040, "s": 976, "text": "Here bquote() function is uses to produce a superscript label." }, { "code": null, "e": 1062, "s": 1040, "text": "Syntax : bquote(expr)" }, { "code": null, "e": 1074, "s": 1062, "text": "Parameter :" }, { "code": null, "e": 1097, "s": 1074, "text": "expr : language object" }, { "code": null, "e": 1124, "s": 1097, "text": "bquote() For SuperScript :" }, { "code": null, "e": 1168, "s": 1124, "text": "bquote(‘string'(math superscript Notation))" }, { "code": null, "e": 1295, "s": 1168, "text": "For assigning the labels to X and Y axis, we will use xlab() and ylab() function to give labels to X and Y Axis respectively. " }, { "code": null, "e": 1329, "s": 1295, "text": "Syntax : xlab(“Label for X-Axis”)" }, { "code": null, "e": 1363, "s": 1329, "text": "Syntax : ylab(“Label for Y-Axis”)" }, { "code": null, "e": 1372, "s": 1363, "text": "Example:" }, { "code": null, "e": 1374, "s": 1372, "text": "R" }, { "code": "# Load ggplot2 Packagelibrary(\"ggplot2\") # Create a DataFrame For PlottingDF <- data.frame(X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Y = c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)) # Create ggplot2 Line Graph with # SuperScripted value of Label of # Y Axis.ggplot(DF,aes(X, Y))+ geom_line(size = 2, color = \"green\")+ xlab('X-axis (number)')+ ylab(bquote('Y-axis '(number^2)))", "e": 1834, "s": 1374, "text": null }, { "code": null, "e": 1842, "s": 1834, "text": "Output:" }, { "code": null, "e": 1891, "s": 1842, "text": "ggplot2 plot with superscripted label of Y Axis " }, { "code": null, "e": 1970, "s": 1891, "text": "To add superscript as a title add bquote function with value inside ggtitle()." }, { "code": null, "e": 2005, "s": 1970, "text": "Syntax : ggtitle(“Title for Plot”)" }, { "code": null, "e": 2017, "s": 2005, "text": "Parameter :" }, { "code": null, "e": 2211, "s": 2017, "text": "like xlab and ylab functions, we can give the title for plot directly using this function. Here we will bquote() function for writing Superscript value ( Number VS Number2 ) as a title of plot." }, { "code": null, "e": 2235, "s": 2211, "text": "Return : Title to plot." }, { "code": null, "e": 2244, "s": 2235, "text": "Example:" }, { "code": null, "e": 2246, "s": 2244, "text": "R" }, { "code": "# Load ggplot2 Packagelibrary(\"ggplot2\") # Create a DataFrame For PlottingDF <- data.frame(X = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Y = c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)) # Create ggplot2 Line Graph with SuperScripted# value of Title of plotggplot(DF,aes(X, Y))+ geom_line(size = 2, color = \"green\")+ ggtitle(bquote('Number VS'~Number^2))", "e": 2678, "s": 2246, "text": null }, { "code": null, "e": 2686, "s": 2678, "text": "Output:" }, { "code": null, "e": 2725, "s": 2686, "text": "ggplot2 plot with superscripted Title " }, { "code": null, "e": 2732, "s": 2725, "text": "Picked" }, { "code": null, "e": 2741, "s": 2732, "text": "R-ggplot" }, { "code": null, "e": 2752, "s": 2741, "text": "R Language" }, { "code": null, "e": 2850, "s": 2752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2902, "s": 2850, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2960, "s": 2902, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 3012, "s": 2960, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3070, "s": 3012, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3102, "s": 3070, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 3137, "s": 3102, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3181, "s": 3137, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 3219, "s": 3181, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3268, "s": 3219, "text": "How to filter R DataFrame by values in a column?" } ]
Python | Convert Numpy Arrays to Tuples
04 Oct, 2021 Given a numpy array, write a program to convert numpy array into tuples.Examples – Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]]) Output: ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1)) Input: ([['manjeet', 'akshat'], ['nikhil', 'akash']]) Output: (('manjeet', 'akshat'), ('nikhil', 'akash')) Given below are various methods to convert numpy array into tuples.Method #1: Using tuple and map Python3 # Python code to demonstrate# deletion of columns from numpy array import numpy as np # initialising numpy arrayini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']]) # convert numpy arrays into tuplesresult = tuple(map(tuple, ini_array)) # print resultprint ("Resultant Array :"+str(result)) Output: Result:(('manjeet', 'akshat'), ('nikhil', 'akash')) Method #2: Using Naive Approach Python3 # Python code to demonstrate# deletion of columns from numpy array import numpy as np # initialising numpy arrayini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']]) # convert numpy arrays into tuplesresult = tuple([tuple(row) for row in ini_array]) # print resultprint ("Result:"+str(result)) Output: Result:(('manjeet', 'akshat'), ('nikhil', 'akash')) anikakapoor Python numpy-arrayManipulation Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Oct, 2021" }, { "code": null, "e": 137, "s": 53, "text": "Given a numpy array, write a program to convert numpy array into tuples.Examples – " }, { "code": null, "e": 335, "s": 137, "text": "Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]])\nOutput: ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1))\n\nInput: ([['manjeet', 'akshat'], ['nikhil', 'akash']])\nOutput: (('manjeet', 'akshat'), ('nikhil', 'akash'))" }, { "code": null, "e": 435, "s": 335, "text": " Given below are various methods to convert numpy array into tuples.Method #1: Using tuple and map " }, { "code": null, "e": 443, "s": 435, "text": "Python3" }, { "code": "# Python code to demonstrate# deletion of columns from numpy array import numpy as np # initialising numpy arrayini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']]) # convert numpy arrays into tuplesresult = tuple(map(tuple, ini_array)) # print resultprint (\"Resultant Array :\"+str(result))", "e": 773, "s": 443, "text": null }, { "code": null, "e": 783, "s": 773, "text": "Output: " }, { "code": null, "e": 835, "s": 783, "text": "Result:(('manjeet', 'akshat'), ('nikhil', 'akash'))" }, { "code": null, "e": 869, "s": 835, "text": "Method #2: Using Naive Approach " }, { "code": null, "e": 877, "s": 869, "text": "Python3" }, { "code": "# Python code to demonstrate# deletion of columns from numpy array import numpy as np # initialising numpy arrayini_array = np.array([['manjeet', 'akshat'], ['nikhil', 'akash']]) # convert numpy arrays into tuplesresult = tuple([tuple(row) for row in ini_array]) # print resultprint (\"Result:\"+str(result))", "e": 1209, "s": 877, "text": null }, { "code": null, "e": 1218, "s": 1209, "text": "Output: " }, { "code": null, "e": 1270, "s": 1218, "text": "Result:(('manjeet', 'akshat'), ('nikhil', 'akash'))" }, { "code": null, "e": 1282, "s": 1270, "text": "anikakapoor" }, { "code": null, "e": 1313, "s": 1282, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 1320, "s": 1313, "text": "Python" }, { "code": null, "e": 1336, "s": 1320, "text": "Python Programs" }, { "code": null, "e": 1434, "s": 1336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1476, "s": 1434, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1498, "s": 1476, "text": "Enumerate() in Python" }, { "code": null, "e": 1524, "s": 1498, "text": "Python String | replace()" }, { "code": null, "e": 1556, "s": 1524, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1585, "s": 1556, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1628, "s": 1585, "text": "Python program to convert a list to string" }, { "code": null, "e": 1650, "s": 1628, "text": "Defaultdict in Python" }, { "code": null, "e": 1689, "s": 1650, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1727, "s": 1689, "text": "Python | Convert a list to dictionary" } ]
Split DataFrame Variable into Multiple Columns in R
19 Nov, 2021 In this article, we will discuss how to split dataframe variables into multiple columns using R programming language. The strsplit() method in R is used to split the specified column string vector into corresponding parts. The pattern is used to divide the string into subparts. Syntax: strsplit(str, pattern) Parameter : str: The string vector to be split. pattern: Pattern to split up the string by. The do.call() method is used to call a function from within a method name. The rbind() method can then be used to combine the columns obtained as vectors as a result of the application of strsplit method. Syntax: do.call(what, args) Parameter: what – The function to execute args – Additional arguments to execute. Example: Split Dataframe variable into multiple columns R # creating a dataframedata_frame <- data.frame( col1 = c("val_1","val_2","val_3","val_4") )print("Original DataFrame")print(data_frame) # splitting values in columnprint("Modified DataFrame") # splitting the values of col1 using underscore characterdata.frame(do.call("rbind", strsplit(as.character(data_frame$col1), "_", fixed = TRUE))) Output: [1] "Original DataFrame" col1 1 val_1 2 val_2 3 val_3 4 val_4 [1] "Modified DataFrame" X1 X2 1 val 1 2 val 2 3 val 3 4 val 4 The tidyr package in R is used to mutate and visualize the data. It is used to tidy up the data. The package can be downloaded and installed into the working space using the following command: install.packages("tidyr") The separate method in R can be used to split up the specified string column or vector into corresponding sub-parts. The length of the second argument vector is equivalent to the number of pieces to split up the data into. Syntax: separate(str, n, pattern) Parameter: str: The string vector to be split. n: The names of pieces to split the string into. pattern: Pattern to split up the string by. Example: Split dataframe variable into multiple columns R library("tidyr") # creating a dataframedata_frame <- data.frame( col1 = c("val_1","val_2","val_3","val_4") ) print("Original DataFrame")print(data_frame) # splitting values in columnprint("Modified DataFrame") data_frame %>% separate(col1, c("col1", "col2"), "_") Output: [1] "Original DataFrame" col1 1 val_1 2 val_2 3 val_3 4 val_4 [1] "Modified DataFrame" col1 col2 1 val 1 2 val 2 3 val 3 4 val 4 The stringr package in R is used to carry out string manipulations. It helps us perform modifications related to string. The package can be download and installed into the working space using the following command : install.packages("stringr") The str_split_fixed method in stringr package is used to split up a string into a fixed number of pieces. The method transforms strings into the specified number of substrings. The specified pattern should be of unit length. Syntax: str_split_fixed(str, pattern , n Parameter : str: The string vector to be split. pattern: Pattern to split up the string by. n: The number of pieces to split the string into. Example: Split dataframe variable into multiple columns R library("stringr") # creating a dataframedata_frame <- data.frame( col1 = c("val_1","val_2","val_3","val_4") )print("Original DataFrame")print(data_frame) # splitting values in columnprint("Modified DataFrame")str_split_fixed(data_frame$col1, "_", 2) Output: [1] "Original DataFrame" col1 1 val_1 2 val_2 3 val_3 4 val_4 [1] "Modified DataFrame" [,1] [,2] [1,] "val" "1" [2,] "val" "2" [3,] "val" "3" [4,] "val" "4" surindertarika1234 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2021" }, { "code": null, "e": 146, "s": 28, "text": "In this article, we will discuss how to split dataframe variables into multiple columns using R programming language." }, { "code": null, "e": 308, "s": 146, "text": "The strsplit() method in R is used to split the specified column string vector into corresponding parts. The pattern is used to divide the string into subparts. " }, { "code": null, "e": 316, "s": 308, "text": "Syntax:" }, { "code": null, "e": 339, "s": 316, "text": "strsplit(str, pattern)" }, { "code": null, "e": 351, "s": 339, "text": "Parameter :" }, { "code": null, "e": 387, "s": 351, "text": "str: The string vector to be split." }, { "code": null, "e": 431, "s": 387, "text": "pattern: Pattern to split up the string by." }, { "code": null, "e": 637, "s": 431, "text": "The do.call() method is used to call a function from within a method name. The rbind() method can then be used to combine the columns obtained as vectors as a result of the application of strsplit method. " }, { "code": null, "e": 645, "s": 637, "text": "Syntax:" }, { "code": null, "e": 665, "s": 645, "text": "do.call(what, args)" }, { "code": null, "e": 677, "s": 665, "text": "Parameter: " }, { "code": null, "e": 708, "s": 677, "text": "what – The function to execute" }, { "code": null, "e": 748, "s": 708, "text": "args – Additional arguments to execute." }, { "code": null, "e": 804, "s": 748, "text": "Example: Split Dataframe variable into multiple columns" }, { "code": null, "e": 806, "s": 804, "text": "R" }, { "code": "# creating a dataframedata_frame <- data.frame( col1 = c(\"val_1\",\"val_2\",\"val_3\",\"val_4\") )print(\"Original DataFrame\")print(data_frame) # splitting values in columnprint(\"Modified DataFrame\") # splitting the values of col1 using underscore characterdata.frame(do.call(\"rbind\", strsplit(as.character(data_frame$col1), \"_\", fixed = TRUE)))", "e": 1228, "s": 806, "text": null }, { "code": null, "e": 1236, "s": 1228, "text": "Output:" }, { "code": null, "e": 1369, "s": 1236, "text": "[1] \"Original DataFrame\"\n col1\n1 val_1\n2 val_2\n3 val_3\n4 val_4\n[1] \"Modified DataFrame\"\n X1 X2\n1 val 1\n2 val 2\n3 val 3\n4 val 4" }, { "code": null, "e": 1562, "s": 1369, "text": "The tidyr package in R is used to mutate and visualize the data. It is used to tidy up the data. The package can be downloaded and installed into the working space using the following command:" }, { "code": null, "e": 1588, "s": 1562, "text": "install.packages(\"tidyr\")" }, { "code": null, "e": 1812, "s": 1588, "text": "The separate method in R can be used to split up the specified string column or vector into corresponding sub-parts. The length of the second argument vector is equivalent to the number of pieces to split up the data into. " }, { "code": null, "e": 1820, "s": 1812, "text": "Syntax:" }, { "code": null, "e": 1846, "s": 1820, "text": "separate(str, n, pattern)" }, { "code": null, "e": 1857, "s": 1846, "text": "Parameter:" }, { "code": null, "e": 1893, "s": 1857, "text": "str: The string vector to be split." }, { "code": null, "e": 1942, "s": 1893, "text": "n: The names of pieces to split the string into." }, { "code": null, "e": 1986, "s": 1942, "text": "pattern: Pattern to split up the string by." }, { "code": null, "e": 2043, "s": 1986, "text": "Example: Split dataframe variable into multiple columns " }, { "code": null, "e": 2045, "s": 2043, "text": "R" }, { "code": "library(\"tidyr\") # creating a dataframedata_frame <- data.frame( col1 = c(\"val_1\",\"val_2\",\"val_3\",\"val_4\") ) print(\"Original DataFrame\")print(data_frame) # splitting values in columnprint(\"Modified DataFrame\") data_frame %>% separate(col1, c(\"col1\", \"col2\"), \"_\")", "e": 2358, "s": 2045, "text": null }, { "code": null, "e": 2366, "s": 2358, "text": "Output:" }, { "code": null, "e": 2514, "s": 2366, "text": "[1] \"Original DataFrame\"\n col1\n1 val_1\n2 val_2\n3 val_3\n4 val_4\n[1] \"Modified DataFrame\"\n col1 col2\n1 val 1\n2 val 2\n3 val 3\n4 val 4" }, { "code": null, "e": 2731, "s": 2514, "text": "The stringr package in R is used to carry out string manipulations. It helps us perform modifications related to string. The package can be download and installed into the working space using the following command : " }, { "code": null, "e": 2759, "s": 2731, "text": "install.packages(\"stringr\")" }, { "code": null, "e": 2985, "s": 2759, "text": "The str_split_fixed method in stringr package is used to split up a string into a fixed number of pieces. The method transforms strings into the specified number of substrings. The specified pattern should be of unit length. " }, { "code": null, "e": 2993, "s": 2985, "text": "Syntax:" }, { "code": null, "e": 3026, "s": 2993, "text": "str_split_fixed(str, pattern , n" }, { "code": null, "e": 3039, "s": 3026, "text": "Parameter : " }, { "code": null, "e": 3075, "s": 3039, "text": "str: The string vector to be split." }, { "code": null, "e": 3119, "s": 3075, "text": "pattern: Pattern to split up the string by." }, { "code": null, "e": 3169, "s": 3119, "text": "n: The number of pieces to split the string into." }, { "code": null, "e": 3225, "s": 3169, "text": "Example: Split dataframe variable into multiple columns" }, { "code": null, "e": 3227, "s": 3225, "text": "R" }, { "code": "library(\"stringr\") # creating a dataframedata_frame <- data.frame( col1 = c(\"val_1\",\"val_2\",\"val_3\",\"val_4\") )print(\"Original DataFrame\")print(data_frame) # splitting values in columnprint(\"Modified DataFrame\")str_split_fixed(data_frame$col1, \"_\", 2)", "e": 3526, "s": 3227, "text": null }, { "code": null, "e": 3534, "s": 3526, "text": "Output:" }, { "code": null, "e": 3698, "s": 3534, "text": "[1] \"Original DataFrame\"\n col1\n1 val_1\n2 val_2\n3 val_3\n4 val_4\n[1] \"Modified DataFrame\"\n [,1] [,2]\n[1,] \"val\" \"1\"\n[2,] \"val\" \"2\"\n[3,] \"val\" \"3\"\n[4,] \"val\" \"4\"" }, { "code": null, "e": 3717, "s": 3698, "text": "surindertarika1234" }, { "code": null, "e": 3724, "s": 3717, "text": "Picked" }, { "code": null, "e": 3745, "s": 3724, "text": "R DataFrame-Programs" }, { "code": null, "e": 3757, "s": 3745, "text": "R-DataFrame" }, { "code": null, "e": 3768, "s": 3757, "text": "R Language" }, { "code": null, "e": 3779, "s": 3768, "text": "R Programs" }, { "code": null, "e": 3877, "s": 3779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3929, "s": 3877, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3987, "s": 3929, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4022, "s": 3987, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 4060, "s": 4022, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 4109, "s": 4060, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 4167, "s": 4109, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4216, "s": 4167, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 4259, "s": 4216, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 4297, "s": 4259, "text": "Merge DataFrames by Column Names in R" } ]
Combinations in a String of Digits
06 May, 2021 Given an input string of numbers, find all combinations of numbers that can be formed using digits in the same order.Examples: Input : 123 Output :1 2 3 1 23 12 3 123 Input : 1234 Output : 1 2 3 4 1 2 34 1 23 4 1 234 12 3 4 12 34 123 4 1234 The problem can be solved using recursion. We keep track of the current index in the given input string and the length of the output string so far. In each call to the function, if there are no digits remaining in the input string print the current output string and return. Otherwise, copy the current digit to output. From here make two calls, one considering the next digit as part of the next number(including a space in output string) and one considering the next digit as part of the current number( no space included). If there are no digits remaining after the current digit the second call to the function is omitted because a trailing space doesn’t count as a new combination. C++ Java Python3 C# Javascript // CPP program to find all combination of numbers// from a given string of digits#include <iostream>#include <cstring>using namespace std; // function to print combinations of numbers// in given input stringvoid printCombinations(char* input, int index, char* output, int outLength){ // no more digits left in input string if (input[index] == '\0') { // print output string & return output[outLength] = '\0'; cout << output << endl; return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input[index + 1] != '\0') printCombinations(input, index + 1, output, outLength + 1); } // driver function to test above functionint main(){ char input[] = "1214"; char *output = new char[100]; // initialize output with empty string output[0] = '\0'; printCombinations(input, 0, output, 0); return 0;} // Java program to find all combinations// of numbers from a given string of digitsclass GFG{ // function to print combinations of numbers// in given input stringstatic void printCombinations(char[] input, int index, char[] output, int outLength){ // no more digits left in input string if (input.length == index) { // print output string & return System.out.println(String.valueOf(output)); return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input.length!=index + 1) printCombinations(input, index + 1, output, outLength + 1);} // Driver Codepublic static void main(String[] args){ char input[] = "1214".toCharArray(); char []output = new char[100]; printCombinations(input, 0, output, 0);}} // This code is contributed by Rajput-Ji # Python3 program to find all combination of numbers# from a given string of digits # function to print combinations of numbers# in given input stringdef printCombinations(input, index, output, outLength): # no more digits left in input string if (len(input) == index): # print output string & return output[outLength] = '\0' print(*output[:outLength], sep = "") return # place current digit in input string output[outLength] = input[index] # separate next digit with a space output[outLength + 1] = ' ' printCombinations(input, index + 1, output, outLength + 2) # if next digit exists make a # call without including space if(len(input) != (index + 1)): printCombinations(input, index + 1, output, outLength + 1) # Driver codeinput = "1214"output = [0]*100 # initialize output with empty stringoutput[0] = '\0' printCombinations(input, 0, output, 0) # This code is contributed by SHUBHAMSINGH10 // C# program to find all combinations// of numbers from a given string of digitsusing System; class GFG{ // function to print combinations of numbers// in given input stringstatic void printCombinations(char[] input, int index, char[] output, int outLength){ // no more digits left in input string if (input.Length == index) { // print output string & return Console.WriteLine(String.Join("", output)); return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input.Length!=index + 1) printCombinations(input, index + 1, output, outLength + 1);} // Driver Codepublic static void Main(String[] args){ char []input = "1214".ToCharArray(); char []output = new char[100]; printCombinations(input, 0, output, 0);}} // This code is contributed by 29AjayKumar <script>// Javascript program to find all combinations// of numbers from a given string of digits // function to print combinations of numbers// in given input string function printCombinations(input,index,output,outLength) { // no more digits left in input string if (input.length == index) { // print output string & return document.write(output.join("")+"<br>"); return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input.length != index + 1) printCombinations(input, index + 1, output, outLength + 1); } // Driver Code let input = "1214".split(""); let output = new Array(100); printCombinations(input, 0, output, 0); // This code is contributed by avanitrachhadiya2155</script> Output: 1 2 1 4 1 2 14 1 21 4 1 214 12 1 4 12 14 121 4 1214 Alternative Solution: C++ Java Python3 C# Javascript // CPP program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of string#include <bits/stdc++.h>using namespace std; // function to print combinations of// numbers in given input stringvoid printCombinations(char s[]){ // find length of char array int l = strlen(s); // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(int i = 0; i < pow(2, l - 1); i++){ int k = i, x = 0; // first character will be printed // as well cout << s[x]; x++; for(int j = 0; j < strlen(s) - 1; j++){ // if bit is set, means provide // space if(k & 1) cout << " "; k = k >> 1; cout << s[x]; // always increment index of // input string x++; } cout << "\n"; }} // driver codeint main() { char input[] = "1214"; printCombinations(input); return 0;}// This code is contributed by PRINCE Gupta 2 // Java program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of stringimport java.util.*; class GFG{ // function to print combinations of// numbers in given input stringstatic void printCombinations(char s[]){ // find length of char array int l = s.length; // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(int i = 0; i < Math.pow(2, l - 1); i++) { int k = i, x = 0; // first character will be printed // as well System.out.print(s[x]); x++; for(int j = 0; j < s.length - 1; j++) { // if bit is set, means provide // space if(k % 2 == 1) System.out.print(" "); k = k >> 1; System.out.print(s[x]); // always increment index of // input string x++; } System.out.print("\n"); }} // Driver Codepublic static void main(String[] args){ char input[] = "1214".toCharArray(); printCombinations(input);}} // This code is contributed by PrinciRaj1992 # Python 3 program to find all# combination of numbers from# a given string of digits using# bit algorithm used same logic# as to print power set of string # Function to print combinations of# numbers in given input stringdef printCombinations(s): # find length of char array l = len(s); # we can give space between # characters ex. ('1' & '2') # or ('2' & '3') or ('3' & '4') # or ('3' & '4') or all that`s # why here we have maximum # space length - 1 for i in range(pow(2, l - 1)): k = i x = 0 # first character will # be printed as well print(s[x], end = "") x += 1 for j in range(len(s) - 1): # if bit is set, means # provide space if(k & 1): print(" ", end = "") k = k >> 1 print(s[x], end = "") # always increment index of # input string x += 1 print() # Driver codeif __name__ == "__main__": inp = "1214"; printCombinations(inp); # This code is contributed by Chitranayal // C# program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of stringusing System; class GFG{ // function to print combinations of// numbers in given input stringstatic void printCombinations(char []s){ // find length of char array int l = s.Length; // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(int i = 0; i < Math.Pow(2, l - 1); i++) { int k = i, x = 0; // first character will be printed // as well Console.Write(s[x]); x++; for(int j = 0; j < s.Length - 1; j++) { // if bit is set, means provide // space if(k % 2 == 1) Console.Write(" "); k = k >> 1; Console.Write(s[x]); // always increment index of // input string x++; } Console.Write("\n"); }} // Driver Codepublic static void Main(String[] args){ char []input = "1214".ToCharArray(); printCombinations(input);}} // This code is contributed by Rajput-Ji <script> // Javascript program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of string // function to print combinations of // numbers in given input string function printCombinations(s) { // find length of char array let l = s.length; // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(let i = 0; i < Math.pow(2, l - 1); i++) { let k = i, x = 0; // first character will be printed // as well document.write(s[x]); x++; for(let j = 0; j < s.length - 1; j++) { // if bit is set, means provide // space if(k % 2 == 1) document.write(" "); k = k >> 1; document.write(s[x]); // always increment index of // input string x++; } document.write("<br>"); } } // Driver Code let input= "1214".split(""); printCombinations(input); // This code is contributed by rag2127 </script> Output: 1214 1 214 12 14 1 2 14 121 4 1 21 4 12 1 4 1 2 1 4 This article is contributed by aditi sharma 2. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. Chaitanya Tyagi princiraj1992 Rajput-Ji 29AjayKumar SHUBHAMSINGH10 ukasp avanitrachhadiya2155 rag2127 Combinatorial Recursion Recursion Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Combinational Sum Find the K-th Permutation Sequence of first N natural numbers Count ways to reach the nth stair using step 1, 2 or 3 Count Derangements (Permutation such that no element appears in its original position) Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Print all subsequences of a string
[ { "code": null, "e": 54, "s": 26, "text": "\n06 May, 2021" }, { "code": null, "e": 182, "s": 54, "text": "Given an input string of numbers, find all combinations of numbers that can be formed using digits in the same order.Examples: " }, { "code": null, "e": 386, "s": 182, "text": "Input : 123 \nOutput :1 2 3\n 1 23\n 12 3\n 123\n\nInput : 1234\nOutput : 1 2 3 4 \n 1 2 34 \n 1 23 4 \n 1 234 \n 12 3 4 \n 12 34 \n 123 4 \n 1234 " }, { "code": null, "e": 1074, "s": 386, "text": "The problem can be solved using recursion. We keep track of the current index in the given input string and the length of the output string so far. In each call to the function, if there are no digits remaining in the input string print the current output string and return. Otherwise, copy the current digit to output. From here make two calls, one considering the next digit as part of the next number(including a space in output string) and one considering the next digit as part of the current number( no space included). If there are no digits remaining after the current digit the second call to the function is omitted because a trailing space doesn’t count as a new combination. " }, { "code": null, "e": 1078, "s": 1074, "text": "C++" }, { "code": null, "e": 1083, "s": 1078, "text": "Java" }, { "code": null, "e": 1091, "s": 1083, "text": "Python3" }, { "code": null, "e": 1094, "s": 1091, "text": "C#" }, { "code": null, "e": 1105, "s": 1094, "text": "Javascript" }, { "code": "// CPP program to find all combination of numbers// from a given string of digits#include <iostream>#include <cstring>using namespace std; // function to print combinations of numbers// in given input stringvoid printCombinations(char* input, int index, char* output, int outLength){ // no more digits left in input string if (input[index] == '\\0') { // print output string & return output[outLength] = '\\0'; cout << output << endl; return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input[index + 1] != '\\0') printCombinations(input, index + 1, output, outLength + 1); } // driver function to test above functionint main(){ char input[] = \"1214\"; char *output = new char[100]; // initialize output with empty string output[0] = '\\0'; printCombinations(input, 0, output, 0); return 0;}", "e": 2318, "s": 1105, "text": null }, { "code": "// Java program to find all combinations// of numbers from a given string of digitsclass GFG{ // function to print combinations of numbers// in given input stringstatic void printCombinations(char[] input, int index, char[] output, int outLength){ // no more digits left in input string if (input.length == index) { // print output string & return System.out.println(String.valueOf(output)); return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input.length!=index + 1) printCombinations(input, index + 1, output, outLength + 1);} // Driver Codepublic static void main(String[] args){ char input[] = \"1214\".toCharArray(); char []output = new char[100]; printCombinations(input, 0, output, 0);}} // This code is contributed by Rajput-Ji", "e": 3522, "s": 2318, "text": null }, { "code": "# Python3 program to find all combination of numbers# from a given string of digits # function to print combinations of numbers# in given input stringdef printCombinations(input, index, output, outLength): # no more digits left in input string if (len(input) == index): # print output string & return output[outLength] = '\\0' print(*output[:outLength], sep = \"\") return # place current digit in input string output[outLength] = input[index] # separate next digit with a space output[outLength + 1] = ' ' printCombinations(input, index + 1, output, outLength + 2) # if next digit exists make a # call without including space if(len(input) != (index + 1)): printCombinations(input, index + 1, output, outLength + 1) # Driver codeinput = \"1214\"output = [0]*100 # initialize output with empty stringoutput[0] = '\\0' printCombinations(input, 0, output, 0) # This code is contributed by SHUBHAMSINGH10", "e": 4559, "s": 3522, "text": null }, { "code": "// C# program to find all combinations// of numbers from a given string of digitsusing System; class GFG{ // function to print combinations of numbers// in given input stringstatic void printCombinations(char[] input, int index, char[] output, int outLength){ // no more digits left in input string if (input.Length == index) { // print output string & return Console.WriteLine(String.Join(\"\", output)); return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input.Length!=index + 1) printCombinations(input, index + 1, output, outLength + 1);} // Driver Codepublic static void Main(String[] args){ char []input = \"1214\".ToCharArray(); char []output = new char[100]; printCombinations(input, 0, output, 0);}} // This code is contributed by 29AjayKumar", "e": 5812, "s": 4559, "text": null }, { "code": "<script>// Javascript program to find all combinations// of numbers from a given string of digits // function to print combinations of numbers// in given input string function printCombinations(input,index,output,outLength) { // no more digits left in input string if (input.length == index) { // print output string & return document.write(output.join(\"\")+\"<br>\"); return; } // place current digit in input string output[outLength] = input[index]; // separate next digit with a space output[outLength + 1] = ' '; printCombinations(input, index + 1, output, outLength + 2); // if next digit exists make a // call without including space if(input.length != index + 1) printCombinations(input, index + 1, output, outLength + 1); } // Driver Code let input = \"1214\".split(\"\"); let output = new Array(100); printCombinations(input, 0, output, 0); // This code is contributed by avanitrachhadiya2155</script>", "e": 6914, "s": 5812, "text": null }, { "code": null, "e": 6924, "s": 6914, "text": "Output: " }, { "code": null, "e": 6976, "s": 6924, "text": "1 2 1 4\n1 2 14\n1 21 4\n1 214\n12 1 4\n12 14\n121 4\n1214" }, { "code": null, "e": 7000, "s": 6976, "text": "Alternative Solution: " }, { "code": null, "e": 7004, "s": 7000, "text": "C++" }, { "code": null, "e": 7009, "s": 7004, "text": "Java" }, { "code": null, "e": 7017, "s": 7009, "text": "Python3" }, { "code": null, "e": 7020, "s": 7017, "text": "C#" }, { "code": null, "e": 7031, "s": 7020, "text": "Javascript" }, { "code": "// CPP program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of string#include <bits/stdc++.h>using namespace std; // function to print combinations of// numbers in given input stringvoid printCombinations(char s[]){ // find length of char array int l = strlen(s); // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(int i = 0; i < pow(2, l - 1); i++){ int k = i, x = 0; // first character will be printed // as well cout << s[x]; x++; for(int j = 0; j < strlen(s) - 1; j++){ // if bit is set, means provide // space if(k & 1) cout << \" \"; k = k >> 1; cout << s[x]; // always increment index of // input string x++; } cout << \"\\n\"; }} // driver codeint main() { char input[] = \"1214\"; printCombinations(input); return 0;}// This code is contributed by PRINCE Gupta 2", "e": 8244, "s": 7031, "text": null }, { "code": "// Java program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of stringimport java.util.*; class GFG{ // function to print combinations of// numbers in given input stringstatic void printCombinations(char s[]){ // find length of char array int l = s.length; // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(int i = 0; i < Math.pow(2, l - 1); i++) { int k = i, x = 0; // first character will be printed // as well System.out.print(s[x]); x++; for(int j = 0; j < s.length - 1; j++) { // if bit is set, means provide // space if(k % 2 == 1) System.out.print(\" \"); k = k >> 1; System.out.print(s[x]); // always increment index of // input string x++; } System.out.print(\"\\n\"); }} // Driver Codepublic static void main(String[] args){ char input[] = \"1214\".toCharArray(); printCombinations(input);}} // This code is contributed by PrinciRaj1992", "e": 9560, "s": 8244, "text": null }, { "code": "# Python 3 program to find all# combination of numbers from# a given string of digits using# bit algorithm used same logic# as to print power set of string # Function to print combinations of# numbers in given input stringdef printCombinations(s): # find length of char array l = len(s); # we can give space between # characters ex. ('1' & '2') # or ('2' & '3') or ('3' & '4') # or ('3' & '4') or all that`s # why here we have maximum # space length - 1 for i in range(pow(2, l - 1)): k = i x = 0 # first character will # be printed as well print(s[x], end = \"\") x += 1 for j in range(len(s) - 1): # if bit is set, means # provide space if(k & 1): print(\" \", end = \"\") k = k >> 1 print(s[x], end = \"\") # always increment index of # input string x += 1 print() # Driver codeif __name__ == \"__main__\": inp = \"1214\"; printCombinations(inp); # This code is contributed by Chitranayal", "e": 10692, "s": 9560, "text": null }, { "code": "// C# program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of stringusing System; class GFG{ // function to print combinations of// numbers in given input stringstatic void printCombinations(char []s){ // find length of char array int l = s.Length; // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(int i = 0; i < Math.Pow(2, l - 1); i++) { int k = i, x = 0; // first character will be printed // as well Console.Write(s[x]); x++; for(int j = 0; j < s.Length - 1; j++) { // if bit is set, means provide // space if(k % 2 == 1) Console.Write(\" \"); k = k >> 1; Console.Write(s[x]); // always increment index of // input string x++; } Console.Write(\"\\n\"); }} // Driver Codepublic static void Main(String[] args){ char []input = \"1214\".ToCharArray(); printCombinations(input);}} // This code is contributed by Rajput-Ji", "e": 11988, "s": 10692, "text": null }, { "code": "<script> // Javascript program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of string // function to print combinations of // numbers in given input string function printCombinations(s) { // find length of char array let l = s.length; // we can give space between characters // ex. ('1' & '2') or ('2' & '3') or // ('3' & '4') or ('3' & '4') or all // that`s why here we have maximum // space length - 1 for(let i = 0; i < Math.pow(2, l - 1); i++) { let k = i, x = 0; // first character will be printed // as well document.write(s[x]); x++; for(let j = 0; j < s.length - 1; j++) { // if bit is set, means provide // space if(k % 2 == 1) document.write(\" \"); k = k >> 1; document.write(s[x]); // always increment index of // input string x++; } document.write(\"<br>\"); } } // Driver Code let input= \"1214\".split(\"\"); printCombinations(input); // This code is contributed by rag2127 </script>", "e": 13275, "s": 11988, "text": null }, { "code": null, "e": 13285, "s": 13275, "text": "Output: " }, { "code": null, "e": 13337, "s": 13285, "text": "1214\n1 214\n12 14\n1 2 14\n121 4\n1 21 4\n12 1 4\n1 2 1 4" }, { "code": null, "e": 13759, "s": 13337, "text": "This article is contributed by aditi sharma 2. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 13775, "s": 13759, "text": "Chaitanya Tyagi" }, { "code": null, "e": 13789, "s": 13775, "text": "princiraj1992" }, { "code": null, "e": 13799, "s": 13789, "text": "Rajput-Ji" }, { "code": null, "e": 13811, "s": 13799, "text": "29AjayKumar" }, { "code": null, "e": 13826, "s": 13811, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 13832, "s": 13826, "text": "ukasp" }, { "code": null, "e": 13853, "s": 13832, "text": "avanitrachhadiya2155" }, { "code": null, "e": 13861, "s": 13853, "text": "rag2127" }, { "code": null, "e": 13875, "s": 13861, "text": "Combinatorial" }, { "code": null, "e": 13885, "s": 13875, "text": "Recursion" }, { "code": null, "e": 13895, "s": 13885, "text": "Recursion" }, { "code": null, "e": 13909, "s": 13895, "text": "Combinatorial" }, { "code": null, "e": 14007, "s": 13909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14044, "s": 14007, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 14062, "s": 14044, "text": "Combinational Sum" }, { "code": null, "e": 14124, "s": 14062, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 14179, "s": 14124, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 14266, "s": 14179, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 14351, "s": 14266, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 14361, "s": 14351, "text": "Recursion" }, { "code": null, "e": 14388, "s": 14361, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 14416, "s": 14388, "text": "Backtracking | Introduction" } ]
Python | Locking without Deadlocks
29 May, 2021 This article focuses on dealing with how to get more than one lock at a time if a multithread program is given along with avoiding the deadlocks. Multithread programs – Due to the threads that keep on attempting to get multiple locks at once, these are very much prone to deadlocks. Understanding it with an example – a lock is already been acquired by a thread and then a second lock is attempted by the block then in that case, the program can freeze as the thread can potentially block the progress of other threads. Solution: Enforcement of ordering rule Assigning each lock in a unique manner to the program. Only allowing multiple locks to be acquired in ascending order. Code #1: Implementing the solution using a context manager. Python3 # importing librariesimport threadingfrom contextlib import contextmanager # threading to stored information_local = threading.local() @contextmanagerdef acquire(*lock_state_state): # Object identifier to sort the lock lock_state_state = sorted(lock_state_state, key=lambda a: id(a)) # checking the validity of previous locks acquired = getattr(_local, 'acquired', []) if acquired and max(id(lock_state) for lock_state in acquired) >= id(lock_state_state[0]): raise RuntimeError('lock_state Order Violation') # Collecting all the lock state. acquired.extend(lock_state_state) _local.acquired = acquired try: for lock_state in lock_state_state: lock.acquire() yield finally: # locks are released in reverse order. for lock_state in reversed(lock_state_state): lock_state.release() del acquired[-len(lock_state_state):] Locks are acquired in the normal way using the context manager and for performing this task acquire() function is used as there was more than one lock as shown in the code below : Code #2 : Python3 # threadsimport threading # creating lockslock_state_1 = threading.Lock()lock_state_2 = threading.Lock() # using acquire as there are more than one lock def thread_1(): while True: with acquire(lock_state_1, lock_state_2): print('Thread-1') def thread_2(): while True: with acquire(lock_state_2, lock_state_1): print('Thread-2') t1 = threading.Thread(target=thread_1) # daemon thread runs without blocking# the main program from exitingt1.daemon = Truet1.start() t2 = threading.Thread(target=thread_2)t2.daemon = Truet2.start() Even after the acquisition of the locks specification in a different order in each function – the program will run forever without deadlock. Sorting the locks plays an important role according to the object identifier as locks after being sorted get acquired in a consistent manner regardless of how the user might have provided them to acquire(). If multiple threads are nested as shown in the code below, to solve a subtle problem with detection potential deadlock, thread-local storage is used. Code #3 : Python3 # threadsimport threading # creating lockslock_state_1 = threading.Lock()lock_state_2 = threading.Lock() def thread_1(): while True: with acquire(lock_state_1): with acquire(lock_state_2): print('Thread-1') def thread_2(): while True: with acquire(lock_state_2): with acquire(lock_state_1): print('Thread-2') t1 = threading.Thread(target=thread_1) # daemon thread runs without blocking# the main program from exitingt1.daemon = Truet1.start() t2 = threading.Thread(target=thread_2)t2.daemon = Truet2.start() On running this version of the program, one of the threads will crash with an exception such as : Exception in thread Thread-1: Traceback (most recent call last): File "/usr/HP/lib/python3.3/threading.py", line 639, in _bootstrap_inner self.run() File "/usr/HP/lib/python3.3/threading.py", line 596, in run self._target(*self._args, **self._kwargs) File "deadlock.py", line 49, in thread_1 with acquire(y_lock): File "/usr/HP/lib/python3.3/contextlib.py", line 48, in __enter__ return next(self.gen) File "deadlock.py", line 17, in acquire raise RuntimeError("Lock Order Violation") RuntimeError: Lock Order Violation Each thread remembers the lock been already acquired that’s why it’s been showing this error. The ordering constraints that acquired the locks are also enforced and a list of previously acquired locks is checked by the acquire() method. almbbsr456 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 May, 2021" }, { "code": null, "e": 200, "s": 53, "text": "This article focuses on dealing with how to get more than one lock at a time if a multithread program is given along with avoiding the deadlocks. " }, { "code": null, "e": 576, "s": 200, "text": "Multithread programs – Due to the threads that keep on attempting to get multiple locks at once, these are very much prone to deadlocks. Understanding it with an example – a lock is already been acquired by a thread and then a second lock is attempted by the block then in that case, the program can freeze as the thread can potentially block the progress of other threads. " }, { "code": null, "e": 587, "s": 576, "text": "Solution: " }, { "code": null, "e": 616, "s": 587, "text": "Enforcement of ordering rule" }, { "code": null, "e": 671, "s": 616, "text": "Assigning each lock in a unique manner to the program." }, { "code": null, "e": 735, "s": 671, "text": "Only allowing multiple locks to be acquired in ascending order." }, { "code": null, "e": 796, "s": 735, "text": "Code #1: Implementing the solution using a context manager. " }, { "code": null, "e": 804, "s": 796, "text": "Python3" }, { "code": "# importing librariesimport threadingfrom contextlib import contextmanager # threading to stored information_local = threading.local() @contextmanagerdef acquire(*lock_state_state): # Object identifier to sort the lock lock_state_state = sorted(lock_state_state, key=lambda a: id(a)) # checking the validity of previous locks acquired = getattr(_local, 'acquired', []) if acquired and max(id(lock_state) for lock_state in acquired) >= id(lock_state_state[0]): raise RuntimeError('lock_state Order Violation') # Collecting all the lock state. acquired.extend(lock_state_state) _local.acquired = acquired try: for lock_state in lock_state_state: lock.acquire() yield finally: # locks are released in reverse order. for lock_state in reversed(lock_state_state): lock_state.release() del acquired[-len(lock_state_state):]", "e": 1733, "s": 804, "text": null }, { "code": null, "e": 1915, "s": 1733, "text": "Locks are acquired in the normal way using the context manager and for performing this task acquire() function is used as there was more than one lock as shown in the code below : " }, { "code": null, "e": 1926, "s": 1915, "text": "Code #2 : " }, { "code": null, "e": 1934, "s": 1926, "text": "Python3" }, { "code": "# threadsimport threading # creating lockslock_state_1 = threading.Lock()lock_state_2 = threading.Lock() # using acquire as there are more than one lock def thread_1(): while True: with acquire(lock_state_1, lock_state_2): print('Thread-1') def thread_2(): while True: with acquire(lock_state_2, lock_state_1): print('Thread-2') t1 = threading.Thread(target=thread_1) # daemon thread runs without blocking# the main program from exitingt1.daemon = Truet1.start() t2 = threading.Thread(target=thread_2)t2.daemon = Truet2.start()", "e": 2507, "s": 1934, "text": null }, { "code": null, "e": 2648, "s": 2507, "text": "Even after the acquisition of the locks specification in a different order in each function – the program will run forever without deadlock." }, { "code": null, "e": 2855, "s": 2648, "text": "Sorting the locks plays an important role according to the object identifier as locks after being sorted get acquired in a consistent manner regardless of how the user might have provided them to acquire()." }, { "code": null, "e": 3005, "s": 2855, "text": "If multiple threads are nested as shown in the code below, to solve a subtle problem with detection potential deadlock, thread-local storage is used." }, { "code": null, "e": 3017, "s": 3005, "text": "Code #3 : " }, { "code": null, "e": 3025, "s": 3017, "text": "Python3" }, { "code": "# threadsimport threading # creating lockslock_state_1 = threading.Lock()lock_state_2 = threading.Lock() def thread_1(): while True: with acquire(lock_state_1): with acquire(lock_state_2): print('Thread-1') def thread_2(): while True: with acquire(lock_state_2): with acquire(lock_state_1): print('Thread-2') t1 = threading.Thread(target=thread_1) # daemon thread runs without blocking# the main program from exitingt1.daemon = Truet1.start() t2 = threading.Thread(target=thread_2)t2.daemon = Truet2.start()", "e": 3608, "s": 3025, "text": null }, { "code": null, "e": 3708, "s": 3608, "text": "On running this version of the program, one of the threads will crash with an exception such as : " }, { "code": null, "e": 4288, "s": 3708, "text": "Exception in thread Thread-1:\nTraceback (most recent call last):\n File \"/usr/HP/lib/python3.3/threading.py\", line 639, in _bootstrap_inner\n self.run()\n File \"/usr/HP/lib/python3.3/threading.py\", line 596, in run\n self._target(*self._args, **self._kwargs)\n File \"deadlock.py\", line 49, in thread_1\n with acquire(y_lock):\n File \"/usr/HP/lib/python3.3/contextlib.py\", line 48, in __enter__\n return next(self.gen)\n File \"deadlock.py\", line 17, in acquire\n raise RuntimeError(\"Lock Order Violation\")\nRuntimeError: Lock Order Violation" }, { "code": null, "e": 4526, "s": 4288, "text": "Each thread remembers the lock been already acquired that’s why it’s been showing this error. The ordering constraints that acquired the locks are also enforced and a list of previously acquired locks is checked by the acquire() method. " }, { "code": null, "e": 4537, "s": 4526, "text": "almbbsr456" }, { "code": null, "e": 4552, "s": 4537, "text": "python-utility" }, { "code": null, "e": 4559, "s": 4552, "text": "Python" } ]
How to write a Python regular expression to match multiple words anywhere?
The following code using Python regex matches the given multiple words in the given string import re s = "These are roses and lilies and orchids, but not marigolds or .." r = re.compile(r'\broses\b | \bmarigolds\b | \borchids\b', flags=re.I | re.X) print r.findall(s) This gives the output ['roses', 'orchids', 'marigolds']
[ { "code": null, "e": 1278, "s": 1187, "text": "The following code using Python regex matches the given multiple words in the given string" }, { "code": null, "e": 1455, "s": 1278, "text": "import re\ns = \"These are roses and lilies and orchids, but not marigolds or ..\"\nr = re.compile(r'\\broses\\b | \\bmarigolds\\b | \\borchids\\b', flags=re.I | re.X)\nprint r.findall(s)" }, { "code": null, "e": 1477, "s": 1455, "text": "This gives the output" }, { "code": null, "e": 1511, "s": 1477, "text": "['roses', 'orchids', 'marigolds']" } ]
Java program to find smallest of the three numbers using ternary operators
The conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as − variable x = (expression) ? value if true: value if false Live Demo public class SmallestOf3NumsUsingTernary { public static void main(String args[]) { int a, b, c, temp, result; a = 10; b = 20; c = 30; temp = a > b ? a:b; result = c > temp ? c:temp; System.out.println("Smallest number is ::"+result); } } Smallest number is ::10
[ { "code": null, "e": 1328, "s": 1062, "text": "The conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −" }, { "code": null, "e": 1386, "s": 1328, "text": "variable x = (expression) ? value if true: value if false" }, { "code": null, "e": 1396, "s": 1386, "text": "Live Demo" }, { "code": null, "e": 1683, "s": 1396, "text": "public class SmallestOf3NumsUsingTernary {\n public static void main(String args[]) {\n int a, b, c, temp, result;\n a = 10;\n b = 20;\n c = 30;\n temp = a > b ? a:b;\n result = c > temp ? c:temp;\n System.out.println(\"Smallest number is ::\"+result);\n }\n}" }, { "code": null, "e": 1707, "s": 1683, "text": "Smallest number is ::10" } ]
Linux Admin - Package Management
Package management in CentOS can be performed in two ways: from the terminal and from the Graphical User Interface. More often than not a majority of a CentOS administrator's time will be using the terminal. Updating and installing packages for CentOS is no different. With this in mind, we will first explore package management in the terminal, then touch on using the graphical package management tool provided by CentOS. YUM is the tool provided for package management in CentOS. We have briefly touched this topic in previous chapters. In this chapter, we will be working from a clean CentOS install. We will first completely update our installation and then install an application. YUM has brought software installation and management in Linux a long way. YUM "automagically” checks for out-of-date dependencies, in addition to out-of-date packages. This has really taken a load off the CentOS administrator compared to the old days of compiling every application from source-code. Checks for packages that can update candidates. For this tutorial, we will assume this a production system that will be facing the Internet with no production applications that needs to be tested by DevOps before upgrading the packages. Let us now install the updated candidates onto the system. [root@localhost rdc]# yum check-update Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu NetworkManager.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-adsl.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-glib.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-libnm.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-team.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-tui.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-wifi.x86_64 1:1.4.0-19.el7_3 updates audit.x86_64 2.6.5-3.el7_3.1 updates vim-common.x86_64 2:7.4.160-1.el7_3.1 updates vim-enhanced.x86_64 2:7.4.160-1.el7_3.1 updates vim-filesystem.x86_64 2:7.4.160-1.el7_3.1 updates vim-minimal.x86_64 2:7.4.160-1.el7_3.1 updates wpa_supplicant.x86_64 1:2.0-21.el7_3 updates xfsprogs.x86_64 4.5.0-9.el7_3 updates [root@localhost rdc]# This will install all updated candidates making your CentOS installation current. With a new installation, this can take a little time depending on your installation and your internet connection speed. [root@localhost rdc]# yum update vim-minimal x86_64 2:7.4.160-1.el7_3.1 updates 436 k wpa_supplicant x86_64 1:2.0-21.el7_3 updates 788 k xfsprogs x86_64 4.5.0-9.el7_3 updates 895 k Transaction Summary ====================================================================================== Install 2 Packages Upgrade 156 Packages Total download size: 371 M Is this ok [y/d/N]: Besides updating the CentOS system, the YUM package manager is our go-to tool for installing the software. Everything from network monitoring tools, video players, to text editors can be installed from a central repository with YUM. Before installing some software utilities, let's look at few YUM commands. For daily work, 90% of a CentOS Admin's usage of YUM will be with about 7 commands. We will go over each in the hope of becoming familiar with operating YUM at a proficient level for daily use. However, like most Linux utilities, YUM offers a wealth of advanced features that are always great to explore via the man page. Use man yum will always be the first step to performing unfamiliar operations with any Linux utility. Following are the commonly used YUM commands. We will now install a text-based web browser called Lynx. Before installation, we must first get the package name containing the Lynx web browser. We are not even 100% sure our default CentOS repository provides a package for the Lynx web browser, so let's search and see − [root@localhost rdc]# yum search web browser Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu ================================================================= N/S matched: web, browser ================================================================== icedtea-web.x86_64 : Additional Java components for OpenJDK - Java browser plug-in and Web Start implementation elinks.x86_64 : A text-mode Web browser firefox.i686 : Mozilla Firefox Web browser firefox.x86_64 : Mozilla Firefox Web browser lynx.x86_64 : A text-based Web browser Full name and summary matches only, use "search all" for everything. [root@localhost rdc]# We see, CentOS does offer the Lynx web browser in the repository. Let's see some more information about the package. [root@localhost rdc]# lynx.x86_64 bash: lynx.x86_64: command not found... [root@localhost rdc]# yum info lynx.x86_64 Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Available Packages Name : lynx Arch : x86_64 Version : 2.8.8 Release : 0.3.dev15.el7 Size : 1.4 M Repo : base/7/x86_64 Summary : A text-based Web browser URL : http://lynx.isc.org/ License : GPLv2 Description : Lynx is a text-based Web browser. Lynx does not display any images, : but it does support frames, tables, and most other HTML tags. One : advantage Lynx has over graphical browsers is speed; Lynx starts and : exits quickly and swiftly displays web pages. [root@localhost rdc]# Nice! Version 2.8 is current enough so let's install Lynx. [root@localhost rdc]# yum install lynx Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Resolving Dependencies --> Running transaction check ---> Package lynx.x86_64 0:2.8.8-0.3.dev15.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved =============================================================================== =============================================================================== Package Arch Version Repository Size =============================================================================== =============================================================================== Installing: lynx x86_64 2.8.80.3.dev15.el7 base 1.4 M Transaction Summary =============================================================================== =============================================================================== Install 1 Package Total download size: 1.4 M Installed size: 5.4 M Is this ok [y/d/N]: y Downloading packages: No Presto metadata available for base lynx-2.8.8-0.3.dev15.el7.x86_64.rpm | 1.4 MB 00:00:10 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : lynx-2.8.8-0.3.dev15.el7.x86_64 1/1 Verifying : lynx-2.8.8-0.3.dev15.el7.x86_64 1/1 Installed: lynx.x86_64 0:2.8.8-0.3.dev15.el7 Complete! [root@localhost rdc]# Next, let's make sure Lynx did in fact install correctly. [root@localhost rdc]# yum list installed | grep -i lynx lynx.x86_64 2.8.8-0.3.dev15.el7 @base [root@localhost rdc]# Great! Let's use Lynx to and see what the web looks like without "likes" and pretty pictures. [root@localhost rdc]# lynx www.tutorialpoint.in Great, now we have a web browser for our production server that can be used without much worry into remote exploits launched over the web. This a good thing for production servers. We are almost completed, however first we need to set this server for developers to test applications. Thus, let's make sure they have all the tools needed for their job. We could install everything individually, but CentOS and YUM have made this a lot faster. Let's install the Development Group Package. [root@localhost rdc]# yum groups list Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Available Groups: Compatibility Libraries Console Internet Tools Development Tools Graphical Administration Tools Legacy UNIX Compatibility Scientific Support Security Tools Smart Card Support System Administration Tools System Management Done [root@localhost rdc]# This is a smaller list of Package Groups provided by CentOS. Let's see what is included with the "Development Group". [root@localhost rdc]# yum group info "Development Tools" Loaded plugins: fastestmirror, langpacks There is no installed groups file. Maybe run: yum groups mark convert (see man yum) Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Group: Development Tools Group-Id: development Description: A basic development environment. Mandatory Packages: autoconf automake binutils bison The first screen of output is as seen above. This entire list is rather comprehensive. However, this group will usually be needed to be installed in its entirety as time goes by. Let's install the entire Development Group. [root@localhost rdc]# yum groupinstall "Development Tools" This will be a larger install. When completed, your server will have most development libraries and compilers for Perl, Python, C, and C++. Gnome Desktop provides a graphical package management tool called Software. It is fairly simple to use and straightforward. Software, the Gnome package management tool for CentOS can be found by navigating to: Applications → System Tools → Software. The Software Package Management Tool is divided into groups allowing the administrator to select packages for installation. While this tool is great for ease-of-use and simplicity for end-users, YUM is a lot more powerful and will probably be used more by administrators. Following is a screenshot of the Software Package Management Tool, not really designed for System Administrators. 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2373, "s": 2257, "text": "Package management in CentOS can be performed in two ways: from the terminal and from the Graphical User Interface." }, { "code": null, "e": 2681, "s": 2373, "text": "More often than not a majority of a CentOS administrator's time will be using the terminal. Updating and installing packages for CentOS is no different. With this in mind, we will first explore package management in the terminal, then touch on using the graphical package management tool provided by CentOS." }, { "code": null, "e": 2944, "s": 2681, "text": "YUM is the tool provided for package management in CentOS. We have briefly touched this topic in previous chapters. In this chapter, we will be working from a clean CentOS install. We will first completely update our installation and then install an application." }, { "code": null, "e": 3244, "s": 2944, "text": "YUM has brought software installation and management in Linux a long way. YUM \"automagically” checks for out-of-date dependencies, in addition to out-of-date packages. This has really taken a load off the CentOS administrator compared to the old days of compiling every application from source-code." }, { "code": null, "e": 3540, "s": 3244, "text": "Checks for packages that can update candidates. For this tutorial, we will assume this a production system that will be facing the Internet with no production applications that needs to be tested by DevOps before upgrading the packages. Let us now install the updated candidates onto the system." }, { "code": null, "e": 4920, "s": 3540, "text": "[root@localhost rdc]# yum check-update\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com\n * updates: mirror.clarkson.edu\nNetworkManager.x86_64 1:1.4.0-19.el7_3 updates\nNetworkManager-adsl.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-glib.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-libnm.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-team.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-tui.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-wifi.x86_64 1:1.4.0-19.el7_3 updates \naudit.x86_64 2.6.5-3.el7_3.1 updates \nvim-common.x86_64 2:7.4.160-1.el7_3.1 updates \nvim-enhanced.x86_64 2:7.4.160-1.el7_3.1 updates \nvim-filesystem.x86_64 2:7.4.160-1.el7_3.1 updates \nvim-minimal.x86_64 2:7.4.160-1.el7_3.1 updates \nwpa_supplicant.x86_64 1:2.0-21.el7_3 updates \nxfsprogs.x86_64 4.5.0-9.el7_3 updates\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 5122, "s": 4920, "text": "This will install all updated candidates making your CentOS installation current. With a new installation, this can take a little time depending on your installation and your internet connection speed." }, { "code": null, "e": 5623, "s": 5122, "text": "[root@localhost rdc]# yum update\n\nvim-minimal x86_64 2:7.4.160-1.el7_3.1 updates 436 k \nwpa_supplicant x86_64 1:2.0-21.el7_3 updates 788 k \nxfsprogs x86_64 4.5.0-9.el7_3 updates 895 k \n\nTransaction Summary \n======================================================================================\nInstall 2 Packages \nUpgrade 156 Packages \nTotal download size: 371 M\n\nIs this ok [y/d/N]:\n" }, { "code": null, "e": 5856, "s": 5623, "text": "Besides updating the CentOS system, the YUM package manager is our go-to tool for installing the software. Everything from network monitoring tools, video players, to text editors can be installed from a central repository with YUM." }, { "code": null, "e": 6355, "s": 5856, "text": "Before installing some software utilities, let's look at few YUM commands. For daily work, 90% of a CentOS Admin's usage of YUM will be with about 7 commands. We will go over each in the hope of becoming familiar with operating YUM at a proficient level for daily use. However, like most Linux utilities, YUM offers a wealth of advanced features that are always great to explore via the man page. Use man yum will always be the first step to performing unfamiliar operations with any Linux utility." }, { "code": null, "e": 6401, "s": 6355, "text": "Following are the commonly used YUM commands." }, { "code": null, "e": 6675, "s": 6401, "text": "We will now install a text-based web browser called Lynx. Before installation, we must first get the package name containing the Lynx web browser. We are not even 100% sure our default CentOS repository provides a package for the Lynx web browser, so let's search and see −" }, { "code": null, "e": 7438, "s": 6675, "text": "[root@localhost rdc]# yum search web browser\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com \n * updates: mirror.clarkson.edu \n=================================================================\nN/S matched: web, browser\n================================================================== \nicedtea-web.x86_64 : Additional Java components for OpenJDK - Java browser\nplug-in and Web Start implementation\nelinks.x86_64 : A text-mode Web browser\nfirefox.i686 : Mozilla Firefox Web browser\nfirefox.x86_64 : Mozilla Firefox Web browser\nlynx.x86_64 : A text-based Web browser\n\nFull name and summary matches only, use \"search all\" for everything.\n \n[root@localhost rdc]#\n" }, { "code": null, "e": 7555, "s": 7438, "text": "We see, CentOS does offer the Lynx web browser in the repository. Let's see some more information about the package." }, { "code": null, "e": 8446, "s": 7555, "text": "[root@localhost rdc]# lynx.x86_64\nbash: lynx.x86_64: command not found...\n[root@localhost rdc]# yum info lynx.x86_64\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com\n * updates: mirror.clarkson.edu\nAvailable Packages\nName : lynx\nArch : x86_64\nVersion : 2.8.8\nRelease : 0.3.dev15.el7\nSize : 1.4 M\nRepo : base/7/x86_64\nSummary : A text-based Web browser\nURL : http://lynx.isc.org/\nLicense : GPLv2\nDescription : Lynx is a text-based Web browser. Lynx does not display any images, \n : but it does support frames, tables, and most other HTML tags. One \n : advantage Lynx has over graphical browsers is speed; Lynx starts and\n : exits quickly and swiftly displays web pages.\n \n[root@localhost rdc]#\n" }, { "code": null, "e": 8505, "s": 8446, "text": "Nice! Version 2.8 is current enough so let's install Lynx." }, { "code": null, "e": 10139, "s": 8505, "text": "[root@localhost rdc]# yum install lynx\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com\n * updates: mirror.clarkson.edu \nResolving Dependencies\n--> Running transaction check \n---> Package lynx.x86_64 0:2.8.8-0.3.dev15.el7 will be installed \n--> Finished Dependency Resolution \nDependencies Resolved \n===============================================================================\n===============================================================================\nPackage Arch\nVersion Repository Size \n===============================================================================\n===============================================================================\nInstalling: \n lynx x86_64\n2.8.80.3.dev15.el7 base 1.4 M\n\nTransaction Summary\n===============================================================================\n===============================================================================\nInstall 1 Package\n\nTotal download size: 1.4 M \nInstalled size: 5.4 M \nIs this ok [y/d/N]: y \nDownloading packages: \nNo Presto metadata available for base\nlynx-2.8.8-0.3.dev15.el7.x86_64.rpm\n| 1.4 MB 00:00:10 \nRunning transaction check \nRunning transaction test \nTransaction test succeeded \nRunning transaction \n Installing : lynx-2.8.8-0.3.dev15.el7.x86_64\n1/1\n Verifying : lynx-2.8.8-0.3.dev15.el7.x86_64\n1/1\n\nInstalled: \n lynx.x86_64 0:2.8.8-0.3.dev15.el7\nComplete!\n\n[root@localhost rdc]# \n" }, { "code": null, "e": 10197, "s": 10139, "text": "Next, let's make sure Lynx did in fact install correctly." }, { "code": null, "e": 10351, "s": 10197, "text": "[root@localhost rdc]# yum list installed | grep -i lynx\n\nlynx.x86_64 2.8.8-0.3.dev15.el7 @base \n[root@localhost rdc]#\n" }, { "code": null, "e": 10445, "s": 10351, "text": "Great! Let's use Lynx to and see what the web looks like without \"likes\" and pretty pictures." }, { "code": null, "e": 10494, "s": 10445, "text": "[root@localhost rdc]# lynx www.tutorialpoint.in\n" }, { "code": null, "e": 10675, "s": 10494, "text": "Great, now we have a web browser for our production server that can be used without much worry into remote exploits launched over the web. This a good thing for production servers." }, { "code": null, "e": 10981, "s": 10675, "text": "We are almost completed, however first we need to set this server for developers to test applications. Thus, let's make sure they have all the tools needed for their job. We could install everything individually, but CentOS and YUM have made this a lot faster. Let's install the Development Group Package." }, { "code": null, "e": 11516, "s": 10981, "text": "[root@localhost rdc]# yum groups list \nLoaded plugins: fastestmirror, langpacks \nLoading mirror speeds from cached hostfile \n * base: mirror.scalabledns.com \n * extras: mirror.scalabledns.com \n * updates: mirror.clarkson.edu\n \nAvailable Groups: \n Compatibility Libraries \n Console Internet Tools \n Development Tools \n Graphical Administration Tools\n Legacy UNIX Compatibility \n Scientific Support \n Security Tools \n Smart Card Support \n System Administration Tools \n System Management \nDone\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 11634, "s": 11516, "text": "This is a smaller list of Package Groups provided by CentOS. Let's see what is included with the \"Development Group\"." }, { "code": null, "e": 12121, "s": 11634, "text": "[root@localhost rdc]# yum group info \"Development Tools\" \nLoaded plugins: fastestmirror, langpacks \nThere is no installed groups file. \nMaybe run: yum groups mark convert (see man yum) \nLoading mirror speeds from cached hostfile \n * base: mirror.scalabledns.com \n * extras: mirror.scalabledns.com \n * updates: mirror.clarkson.edu\n \nGroup: Development Tools \nGroup-Id: development \nDescription: A basic development environment. \nMandatory Packages: \nautoconf \nautomake \nbinutils \nbison \n" }, { "code": null, "e": 12345, "s": 12121, "text": "The first screen of output is as seen above. This entire list is rather comprehensive. However, this group will usually be needed to be installed in its entirety as time goes by. Let's install the entire Development Group." }, { "code": null, "e": 12405, "s": 12345, "text": "[root@localhost rdc]# yum groupinstall \"Development Tools\"\n" }, { "code": null, "e": 12545, "s": 12405, "text": "This will be a larger install. When completed, your server will have most development libraries and compilers for Perl, Python, C, and C++." }, { "code": null, "e": 12795, "s": 12545, "text": "Gnome Desktop provides a graphical package management tool called Software. It is fairly simple to use and straightforward. Software, the Gnome package management tool for CentOS can be found by navigating to: Applications → System Tools → Software." }, { "code": null, "e": 13067, "s": 12795, "text": "The Software Package Management Tool is divided into groups allowing the administrator to select packages for installation. While this tool is great for ease-of-use and simplicity for end-users, YUM is a lot more powerful and will probably be used more by administrators." }, { "code": null, "e": 13181, "s": 13067, "text": "Following is a screenshot of the Software Package Management Tool, not really designed for System Administrators." }, { "code": null, "e": 13216, "s": 13181, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 13232, "s": 13216, "text": " Mamta Tripathi" }, { "code": null, "e": 13265, "s": 13232, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 13279, "s": 13265, "text": " Lets Kode It" }, { "code": null, "e": 13314, "s": 13279, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13331, "s": 13314, "text": " Abhilash Nelson" }, { "code": null, "e": 13366, "s": 13331, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13383, "s": 13366, "text": " Frahaan Hussain" }, { "code": null, "e": 13418, "s": 13383, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 13446, "s": 13418, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13479, "s": 13446, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 13519, "s": 13479, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 13526, "s": 13519, "text": " Print" }, { "code": null, "e": 13537, "s": 13526, "text": " Add Notes" } ]
Convert string to character array in Arduino
There are several libraries built for Arduino whose functions take in character arrays as inputs instead of strings. Thankfully, Arduino has an inbuilt method (toCharArray()) to covert a String to a Character Array. A sample implementation is given below − void setup() { // put your setup code here, to run once: Serial.begin(9600); String s1 = "Hello World!"; char buf[30]; s1.toCharArray(buf,6); Serial.println(buf); s1.toCharArray(buf,s1.length()); Serial.println(buf); } void loop() { // put your main code here, to run repeatedly: } As you can see, the toCharArray function takes in two arguments, the array in which the characters of the strings are to be stored, and the number of characters to convert. We are initially converting only the first 5 characters of the string to a char array. Please note that we have specified 6 as the length instead of 5, because the last character is reserved for the string termination character ('0'). Thus, if you want the string to contain N characters, enter N+1 in the length argument. This means that the first print statement will print only "Hello". In the next attempt, the entire string will get printed, as we have specified the length argument to be equal to the length of the string. But, as you can notice from the output below, the exclamation mark (!) at the end is missing. Again, this is because ideally, we should have specified the length argument to be length of the string + 1. Make sure that you don't convert more characters than what your char array can store. The Serial Monitor output is shown below −
[ { "code": null, "e": 1319, "s": 1062, "text": "There are several libraries built for Arduino whose functions take in character arrays as inputs instead of strings. Thankfully, Arduino has an inbuilt method (toCharArray()) to covert a String to a Character Array. A sample implementation is given below −" }, { "code": null, "e": 1630, "s": 1319, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n String s1 = \"Hello World!\";\n char buf[30];\n\n s1.toCharArray(buf,6);\n Serial.println(buf);\n\n s1.toCharArray(buf,s1.length());\n Serial.println(buf);\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 2126, "s": 1630, "text": "As you can see, the toCharArray function takes in two arguments, the array in which the characters of the strings are to be stored, and the number of characters to convert. We are initially converting only the first 5 characters of the string to a char array. Please note that we have specified 6 as the length instead of 5, because the last character is reserved for the string termination character ('0'). Thus, if you want the string to contain N characters, enter N+1 in the length argument." }, { "code": null, "e": 2621, "s": 2126, "text": "This means that the first print statement will print only \"Hello\". In the next attempt, the entire string will get printed, as we have specified the length argument to be equal to the length of the string. But, as you can notice from the output below, the exclamation mark (!) at the end is missing. Again, this is because ideally, we should have specified the length argument to be length of the string + 1. Make sure that you don't convert more characters than what your char array can store." }, { "code": null, "e": 2664, "s": 2621, "text": "The Serial Monitor output is shown below −" } ]
How to get id from tr tag and display it in a new td with JavaScript?
Let’s say the following is our table − <table> <tr id='StudentDetails'> <th>StudentName</th> <th>StudentCountryName</th> </tr> <tr id='FirstRow'> <td>JohnDoe</td> <td>UK</td> </tr> <tr id='SecondRow'> <td>DavidMiller</td> <td>US</td> </tr> </table> To get id from tr tag and display it in a new td, use document.querySelectorAll(table tr). Following is the code − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <style> td, th, table { border: 1px solid black; margin-left: 10px; margin-top: 10px; } </style> <body> <table> <tr id='StudentDetails'> <th>StudentName</th> <th>StudentCountryName</th> </tr> <tr id='FirstRow'> <td>JohnDoe</td> <td>UK</td> </tr> <tr id='SecondRow'> <td>DavidMiller</td> <td>US</td> </tr> </table> </body> <script> document.querySelectorAll('table tr').forEach(trObj => { var tableValue = trObj.insertCell(0); tableValue.textContent = trObj.id; }); </script> </html> To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor. This will produce the following output on console −
[ { "code": null, "e": 1101, "s": 1062, "text": "Let’s say the following is our table −" }, { "code": null, "e": 1365, "s": 1101, "text": "<table>\n <tr id='StudentDetails'>\n <th>StudentName</th>\n <th>StudentCountryName</th>\n </tr>\n <tr id='FirstRow'>\n <td>JohnDoe</td>\n <td>UK</td>\n </tr>\n <tr id='SecondRow'>\n <td>DavidMiller</td>\n <td>US</td>\n </tr>\n</table>" }, { "code": null, "e": 1456, "s": 1365, "text": "To get id from tr tag and display it in a new td, use document.querySelectorAll(table tr)." }, { "code": null, "e": 1480, "s": 1456, "text": "Following is the code −" }, { "code": null, "e": 1491, "s": 1480, "text": " Live Demo" }, { "code": null, "e": 2515, "s": 1491, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<style>\n td,\n th,\n table {\n border: 1px solid black;\n margin-left: 10px;\n margin-top: 10px;\n }\n</style>\n<body>\n <table>\n <tr id='StudentDetails'>\n <th>StudentName</th>\n <th>StudentCountryName</th>\n </tr>\n <tr id='FirstRow'>\n <td>JohnDoe</td>\n <td>UK</td>\n </tr>\n <tr id='SecondRow'>\n <td>DavidMiller</td>\n <td>US</td>\n </tr>\n </table>\n</body>\n<script>\n document.querySelectorAll('table tr').forEach(trObj => {\n var tableValue = trObj.insertCell(0);\n tableValue.textContent = trObj.id;\n });\n</script> \n</html>" }, { "code": null, "e": 2677, "s": 2515, "text": "To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2729, "s": 2677, "text": "This will produce the following output on console −" } ]
Perl Formats - Writing Reports
As stated earlier that Perl stands for Practical Extraction and Reporting Language, and we'll now discuss using Perl to write reports. Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you must − Define a Format Pass the data that will be displayed on the format Invoke the Format Following is the syntax to define a Perl format format FormatName = fieldline value_one, value_two, value_three fieldline value_one, value_two . FormatName represents the name of the format. The fieldline is the specific way the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period. fieldline can contain any text or fieldholders. Fieldholders hold space for data that will be placed there at a later date. A fieldholder has the format − @<<<< This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of spaces in the field. Other field holders include @>>>> right-justified @|||| centered @####.## numeric field holder @* multiline field holder An example format would be − format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== . In this example $name would be written as left justify within 22 character spaces and after that age will be written in two spaces. In order to invoke this format declaration we would use the write keyword − write EMPLOYEE; #send to the output The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function select(STDOUT); We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~ $~ = "EMPLOYEE"; When we now do a write(), the data would be sent to STDOUT. Remember: if you didn't have STDOUT set as your default file handle, you could revert back to the original file handle by assigning the return value of select to a scalar value, and using select along with this scalar variable after the special variable is assigned the format name, to be associated with STDOUT. The above example will generate a report in the following format Kirsten 12 Mohammad 35 Suhi 15 Namrat 10 Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Apart from defining a template you would have to define a header which will have same name but appended with _TOP keyword as follows format EMPLOYEE_TOP = ------------------------ Name Age ------------------------ . Now your report will look like ------------------------ Name Age ------------------------ Kirsten 12 Mohammad 35 Suhi 15 Namrat 10 What about if your report is taking more than one page ? You have a solution for that. Use $% vairable along with header as follows format EMPLOYEE_TOP = ------------------------ Name Age Page @< ------------------------ $% . Now your output will look like ------------------------ Name Age Page 1 ------------------------ Kirsten 12 Mohammad 35 Suhi 15 Namrat 10 You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ) By default $= will be 60 One final thing is left which is footer. Very similar to header, you can define a footer and it will be written after each page. Here you will use _BOTTOM keyword instead of _TOP. format EMPLOYEE_BOTTOM = End of Page @< $% . This will give you following result ------------------------ Name Age Page 1 ------------------------ Kirsten 12 Mohammad 35 Suhi 15 Namrat 10 End of Page 1 For a complete set of variables related to formating, please refer to Perl Special Variables section. 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2355, "s": 2220, "text": "As stated earlier that Perl stands for Practical Extraction and Reporting Language, and we'll now discuss using Perl to write reports." }, { "code": null, "e": 2468, "s": 2355, "text": "Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you must − " }, { "code": null, "e": 2484, "s": 2468, "text": "Define a Format" }, { "code": null, "e": 2535, "s": 2484, "text": "Pass the data that will be displayed on the format" }, { "code": null, "e": 2553, "s": 2535, "text": "Invoke the Format" }, { "code": null, "e": 2601, "s": 2553, "text": "Following is the syntax to define a Perl format" }, { "code": null, "e": 2713, "s": 2601, "text": "format FormatName =\n fieldline\n value_one, value_two, value_three\n fieldline\n value_one, value_two\n ." }, { "code": null, "e": 2944, "s": 2713, "text": "FormatName represents the name of the format. The fieldline is the specific way the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period." }, { "code": null, "e": 3099, "s": 2944, "text": "fieldline can contain any text or fieldholders. Fieldholders hold space for data that will be placed there at a later date. A fieldholder has the format −" }, { "code": null, "e": 3105, "s": 3099, "text": "@<<<<" }, { "code": null, "e": 3279, "s": 3105, "text": "This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of spaces in the field. Other field holders include" }, { "code": null, "e": 3381, "s": 3279, "text": "@>>>> right-justified\n @|||| centered\n @####.## numeric field holder\n @* multiline field holder" }, { "code": null, "e": 3410, "s": 3381, "text": "An example format would be −" }, { "code": null, "e": 3581, "s": 3410, "text": "format EMPLOYEE =\n ===================================\n @<<<<<<<<<<<<<<<<<<<<<< @<< \n $name $age\n @#####.##\n $salary\n ===================================\n ." }, { "code": null, "e": 3713, "s": 3581, "text": "In this example $name would be written as left justify within 22 character spaces and after that age will be written in two spaces." }, { "code": null, "e": 3790, "s": 3713, "text": "In order to invoke this format declaration we would use the write keyword −\n" }, { "code": null, "e": 3826, "s": 3790, "text": "write EMPLOYEE; #send to the output" }, { "code": null, "e": 4175, "s": 3826, "text": "The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function" }, { "code": null, "e": 4191, "s": 4175, "text": "select(STDOUT);" }, { "code": null, "e": 4310, "s": 4191, "text": "We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~" }, { "code": null, "e": 4327, "s": 4310, "text": "$~ = \"EMPLOYEE\";" }, { "code": null, "e": 4700, "s": 4327, "text": "When we now do a write(), the data would be sent to STDOUT. Remember: if you didn't have STDOUT set as your default file handle, you could revert back to the original file handle by assigning the return value of select to a scalar value, and using select along with this scalar variable after the special variable is assigned the format name, to be associated with STDOUT." }, { "code": null, "e": 4765, "s": 4700, "text": "The above example will generate a report in the following format" }, { "code": null, "e": 4873, "s": 4765, "text": " Kirsten 12\n Mohammad 35\n Suhi 15\n Namrat 10" }, { "code": null, "e": 5171, "s": 4873, "text": "Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Apart from defining a template you would have to define a header which will have same name but appended with _TOP keyword as follows" }, { "code": null, "e": 5285, "s": 5171, "text": " format EMPLOYEE_TOP =\n ------------------------\n Name Age\n ------------------------\n ." }, { "code": null, "e": 5316, "s": 5285, "text": "Now your report will look like" }, { "code": null, "e": 5508, "s": 5316, "text": " ------------------------\n Name Age\n ------------------------\n Kirsten 12\n Mohammad 35\n Suhi 15\n Namrat 10" }, { "code": null, "e": 5640, "s": 5508, "text": "What about if your report is taking more than one page ? You have a solution for that. Use $% vairable along with header as follows" }, { "code": null, "e": 5774, "s": 5640, "text": " format EMPLOYEE_TOP =\n ------------------------\n Name Age Page @<\n ------------------------ $%\n ." }, { "code": null, "e": 5805, "s": 5774, "text": "Now your output will look like" }, { "code": null, "e": 6011, "s": 5805, "text": " ------------------------\n Name Age Page 1\n ------------------------ \n Kirsten 12\n Mohammad 35\n Suhi 15\n Namrat 10\n" }, { "code": null, "e": 6133, "s": 6011, "text": "You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ) By default $= will be 60" }, { "code": null, "e": 6313, "s": 6133, "text": "One final thing is left which is footer. Very similar to header, you can define a footer and it will be written after each page. Here you will use _BOTTOM keyword instead of _TOP." }, { "code": null, "e": 6382, "s": 6313, "text": " format EMPLOYEE_BOTTOM =\n End of Page @<\n $%\n ." }, { "code": null, "e": 6418, "s": 6382, "text": "This will give you following result" }, { "code": null, "e": 6641, "s": 6418, "text": " ------------------------\n Name Age Page 1\n ------------------------ \n Kirsten 12\n Mohammad 35\n Suhi 15\n Namrat 10\n End of Page 1\n" }, { "code": null, "e": 6743, "s": 6641, "text": "For a complete set of variables related to formating, please refer to Perl Special Variables section." }, { "code": null, "e": 6778, "s": 6743, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6792, "s": 6778, "text": " Devi Killada" }, { "code": null, "e": 6827, "s": 6792, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6847, "s": 6827, "text": " Harshit Srivastava" }, { "code": null, "e": 6880, "s": 6847, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 6896, "s": 6880, "text": " TELCOMA Global" }, { "code": null, "e": 6929, "s": 6896, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 6946, "s": 6929, "text": " Mohammad Nauman" }, { "code": null, "e": 6979, "s": 6946, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 7002, "s": 6979, "text": " Stone River ELearning" }, { "code": null, "e": 7037, "s": 7002, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7060, "s": 7037, "text": " Stone River ELearning" }, { "code": null, "e": 7067, "s": 7060, "text": " Print" }, { "code": null, "e": 7078, "s": 7067, "text": " Add Notes" } ]
Write and train your own custom machine learning models using PyCaret | by Moez Ali | Towards Data Science
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to quickly and efficiently build and deploy end-to-end ML prototypes. PyCaret is an alternate low-code library that can replace hundreds of code lines with few lines only. This makes the experiment cycle exponentially fast and efficient. PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it. This tutorial assumes that you have some prior knowledge and experience with PyCaret. If you haven’t used it before, no problem — you can get a quick headstart through these tutorials: PyCaret 2.2 is here — what’s new Announcing PyCaret 2.0 Five things you don’t know about PyCaret Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries. PyCaret’s default installation is a slim version of pycaret that only installs hard dependencies listed here. # install slim version (default)pip install pycaret# install the full versionpip install pycaret[full] When you install the full version of pycaret, all the optional dependencies as listed here are also installed. Before we start talking about custom model training, let’s see a quick demo of how PyCaret works with out-of-the-box models. I will be using the ‘insurance’ dataset available on PyCaret’s Repository. The goal of this dataset is to predict patient charges based on some attributes. # read data from pycaret repofrom pycaret.datasets import get_datadata = get_data('insurance') Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required before training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link. # initialize setupfrom pycaret.regression import *s = setup(data, target = 'charges') Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. If all data types are correctly inferred, you can press enter to continue. To check the list of all models available for training, you can use the function called models . It displays a table with model ID, name, and the reference of the actual estimator. # check all the available modelsmodels() The most used function for training any model in PyCaret is create_model . It takes an ID for the estimator you want to train. # train decision treedt = create_model('dt') The output shows the 10-fold cross-validated metrics with mean and standard deviation. The output from this function is a trained model object, which is essentially a scikit-learn object. print(dt) To train multiple models in a loop, you can write a simple list comprehension: # train multiple modelsmultiple_models = [create_model(i) for i in ['dt', 'lr', 'xgboost']]# check multiple_modelstype(multiple_models), len(multiple_models)>>> (list, 3)print(multiple_models) If you want to train all the models available in the library instead of the few selected you can use PyCaret’s compare_models function instead of writing your own loop (the results will be the same though). # compare all modelsbest_model = compare_models() compare_models returns the output which shows the cross-validated metrics for all models. According to this output, Gradient Boosting Regressor is the best model with $2,702 in Mean Absolute Error (MAE) using 10-fold cross-validation on the train set. # check the best modelprint(best_model) The metrics shown in the above grid is cross-validation scores, to check the score of the best_modelon hold-out set: # predict on hold-outpred_holdout = predict_model(best_model) To generate predictions on the unseen dataset you can use the same predict_model function but just pass an extra parameter data : # create copy of data drop target columndata2 = data.copy()data2.drop('charges', axis=1, inplace=True)# generate predictionspredictions = predict_model(best_model, data = data2) So far what we have seen is training and model selection for all the available models in PyCaret. However, the way PyCaret works for custom models is exactly the same. As long as, your estimator is compatible with sklearn API style, it will work the same way. Let’s see few examples. Before I show you how to write your own custom class, I will first demonstrate how you can work with custom non-sklearn models (models that are not available in sklearn or pycaret’s base library). While Genetic Programming (GP) can be used to perform a very wide variety of tasks, gplearn is purposefully constrained to solving symbolic regression problems. Symbolic regression is a machine learning technique that aims to identify an underlying mathematical expression that best describes a relationship. It begins by building a population of naive random formulas to represent a relationship between known independent variables and their dependent variable targets to predict new data. Each successive generation of programs is then evolved from the one that came before it by selecting the fittest individuals from the population to undergo genetic operations. To use models from gplearn you will have to first install it: # install gplearnpip install gplearn Now you can simply import the untrained model and pass it in the create_model function: # import untrained estimatorfrom gplearn.genetic import SymbolicRegressorsc = SymbolicRegressor()# train using create_modelsc_trained = create_model(sc) print(sc_trained) You can also check the hold-out score for this: # check hold-out scorepred_holdout_sc = predict_model(sc_trained) ngboost is a Python library that implements Natural Gradient Boosting, as described in “NGBoost: Natural Gradient Boosting for Probabilistic Prediction”. It is built on top of Scikit-Learn and is designed to be scalable and modular with respect to the choice of proper scoring rule, distribution, and base learner. A didactic introduction to the methodology underlying NGBoost is available in this slide deck. To use models from ngboost, you will have to first install ngboost: # install ngboostpip install ngboost Once installed, you can import the untrained estimator from the ngboost library and use create_model to train and evaluate the model: # import untrained estimatorfrom ngboost import NGBRegressorng = NGBRegressor()# train using create_modelng_trained = create_model(ng) print(ng_trained) The above two examples gplearn and ngboost are custom models for pycaret as they are not available in the default library but you can use them just like you can use any other out-of-the-box models. However, there may be a use-case that involves writing your own algorithm (i.e. maths behind the algorithm), in which case you can inherit the base class from sklearn and write your own maths. Let’s create a naive estimator which learns the mean value of target variable during fit stage and predicts the same mean value for all new data points, irrespective of X input (probably not useful in real life, but just to make demonstrate the functionality). # create custom estimatorimport numpy as npfrom sklearn.base import BaseEstimatorclass MyOwnModel(BaseEstimator): def __init__(self): self.mean = 0 def fit(self, X, y): self.mean = y.mean() return self def predict(self, X): return np.array(X.shape[0]*[self.mean]) Now let’s use this estimator for training: # import MyOwnModel classmom = MyOwnModel()# train using create_modelmom_trained = create_model(mom) # generate predictions on datapredictions = predict_model(mom_trained, data=data) Notice that Label column which is essentially the prediction is the same number $13,225 for all the rows, that’s because we created this algorithm in such a way, that learns from the mean of train set and predict the same value (just to keep things simple). I hope that you will appreciate the ease of use and simplicity in PyCaret. In just a few lines, you can perform end-to-end machine learning experiments and write your own algorithms without adjusting any native code. Next week I will be writing a tutorial to advance this tutorial. We will write a more complex algorithm instead of just a mean prediction. I will introduce some complex concepts in the next tutorial. Please follow me on Medium, LinkedIn, and Twitter to get more updates. There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository. To hear more about PyCaret follow us on LinkedIn and Youtube. Join us on our slack channel. Invite link here. Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret Click on the links below to see the documentation and working examples. ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
[ { "code": null, "e": 344, "s": 47, "text": "PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to quickly and efficiently build and deploy end-to-end ML prototypes." }, { "code": null, "e": 512, "s": 344, "text": "PyCaret is an alternate low-code library that can replace hundreds of code lines with few lines only. This makes the experiment cycle exponentially fast and efficient." }, { "code": null, "e": 833, "s": 512, "text": "PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it." }, { "code": null, "e": 1018, "s": 833, "text": "This tutorial assumes that you have some prior knowledge and experience with PyCaret. If you haven’t used it before, no problem — you can get a quick headstart through these tutorials:" }, { "code": null, "e": 1051, "s": 1018, "text": "PyCaret 2.2 is here — what’s new" }, { "code": null, "e": 1074, "s": 1051, "text": "Announcing PyCaret 2.0" }, { "code": null, "e": 1115, "s": 1074, "text": "Five things you don’t know about PyCaret" }, { "code": null, "e": 1278, "s": 1115, "text": "Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries." }, { "code": null, "e": 1388, "s": 1278, "text": "PyCaret’s default installation is a slim version of pycaret that only installs hard dependencies listed here." }, { "code": null, "e": 1491, "s": 1388, "text": "# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]" }, { "code": null, "e": 1602, "s": 1491, "text": "When you install the full version of pycaret, all the optional dependencies as listed here are also installed." }, { "code": null, "e": 1883, "s": 1602, "text": "Before we start talking about custom model training, let’s see a quick demo of how PyCaret works with out-of-the-box models. I will be using the ‘insurance’ dataset available on PyCaret’s Repository. The goal of this dataset is to predict patient charges based on some attributes." }, { "code": null, "e": 1978, "s": 1883, "text": "# read data from pycaret repofrom pycaret.datasets import get_datadata = get_data('insurance')" }, { "code": null, "e": 2416, "s": 1978, "text": "Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required before training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link." }, { "code": null, "e": 2502, "s": 2416, "text": "# initialize setupfrom pycaret.regression import *s = setup(data, target = 'charges')" }, { "code": null, "e": 2706, "s": 2502, "text": "Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. If all data types are correctly inferred, you can press enter to continue." }, { "code": null, "e": 2887, "s": 2706, "text": "To check the list of all models available for training, you can use the function called models . It displays a table with model ID, name, and the reference of the actual estimator." }, { "code": null, "e": 2928, "s": 2887, "text": "# check all the available modelsmodels()" }, { "code": null, "e": 3055, "s": 2928, "text": "The most used function for training any model in PyCaret is create_model . It takes an ID for the estimator you want to train." }, { "code": null, "e": 3100, "s": 3055, "text": "# train decision treedt = create_model('dt')" }, { "code": null, "e": 3288, "s": 3100, "text": "The output shows the 10-fold cross-validated metrics with mean and standard deviation. The output from this function is a trained model object, which is essentially a scikit-learn object." }, { "code": null, "e": 3298, "s": 3288, "text": "print(dt)" }, { "code": null, "e": 3377, "s": 3298, "text": "To train multiple models in a loop, you can write a simple list comprehension:" }, { "code": null, "e": 3570, "s": 3377, "text": "# train multiple modelsmultiple_models = [create_model(i) for i in ['dt', 'lr', 'xgboost']]# check multiple_modelstype(multiple_models), len(multiple_models)>>> (list, 3)print(multiple_models)" }, { "code": null, "e": 3777, "s": 3570, "text": "If you want to train all the models available in the library instead of the few selected you can use PyCaret’s compare_models function instead of writing your own loop (the results will be the same though)." }, { "code": null, "e": 3827, "s": 3777, "text": "# compare all modelsbest_model = compare_models()" }, { "code": null, "e": 4079, "s": 3827, "text": "compare_models returns the output which shows the cross-validated metrics for all models. According to this output, Gradient Boosting Regressor is the best model with $2,702 in Mean Absolute Error (MAE) using 10-fold cross-validation on the train set." }, { "code": null, "e": 4119, "s": 4079, "text": "# check the best modelprint(best_model)" }, { "code": null, "e": 4236, "s": 4119, "text": "The metrics shown in the above grid is cross-validation scores, to check the score of the best_modelon hold-out set:" }, { "code": null, "e": 4298, "s": 4236, "text": "# predict on hold-outpred_holdout = predict_model(best_model)" }, { "code": null, "e": 4428, "s": 4298, "text": "To generate predictions on the unseen dataset you can use the same predict_model function but just pass an extra parameter data :" }, { "code": null, "e": 4606, "s": 4428, "text": "# create copy of data drop target columndata2 = data.copy()data2.drop('charges', axis=1, inplace=True)# generate predictionspredictions = predict_model(best_model, data = data2)" }, { "code": null, "e": 4890, "s": 4606, "text": "So far what we have seen is training and model selection for all the available models in PyCaret. However, the way PyCaret works for custom models is exactly the same. As long as, your estimator is compatible with sklearn API style, it will work the same way. Let’s see few examples." }, { "code": null, "e": 5087, "s": 4890, "text": "Before I show you how to write your own custom class, I will first demonstrate how you can work with custom non-sklearn models (models that are not available in sklearn or pycaret’s base library)." }, { "code": null, "e": 5248, "s": 5087, "text": "While Genetic Programming (GP) can be used to perform a very wide variety of tasks, gplearn is purposefully constrained to solving symbolic regression problems." }, { "code": null, "e": 5754, "s": 5248, "text": "Symbolic regression is a machine learning technique that aims to identify an underlying mathematical expression that best describes a relationship. It begins by building a population of naive random formulas to represent a relationship between known independent variables and their dependent variable targets to predict new data. Each successive generation of programs is then evolved from the one that came before it by selecting the fittest individuals from the population to undergo genetic operations." }, { "code": null, "e": 5816, "s": 5754, "text": "To use models from gplearn you will have to first install it:" }, { "code": null, "e": 5853, "s": 5816, "text": "# install gplearnpip install gplearn" }, { "code": null, "e": 5941, "s": 5853, "text": "Now you can simply import the untrained model and pass it in the create_model function:" }, { "code": null, "e": 6094, "s": 5941, "text": "# import untrained estimatorfrom gplearn.genetic import SymbolicRegressorsc = SymbolicRegressor()# train using create_modelsc_trained = create_model(sc)" }, { "code": null, "e": 6112, "s": 6094, "text": "print(sc_trained)" }, { "code": null, "e": 6160, "s": 6112, "text": "You can also check the hold-out score for this:" }, { "code": null, "e": 6226, "s": 6160, "text": "# check hold-out scorepred_holdout_sc = predict_model(sc_trained)" }, { "code": null, "e": 6636, "s": 6226, "text": "ngboost is a Python library that implements Natural Gradient Boosting, as described in “NGBoost: Natural Gradient Boosting for Probabilistic Prediction”. It is built on top of Scikit-Learn and is designed to be scalable and modular with respect to the choice of proper scoring rule, distribution, and base learner. A didactic introduction to the methodology underlying NGBoost is available in this slide deck." }, { "code": null, "e": 6704, "s": 6636, "text": "To use models from ngboost, you will have to first install ngboost:" }, { "code": null, "e": 6741, "s": 6704, "text": "# install ngboostpip install ngboost" }, { "code": null, "e": 6875, "s": 6741, "text": "Once installed, you can import the untrained estimator from the ngboost library and use create_model to train and evaluate the model:" }, { "code": null, "e": 7010, "s": 6875, "text": "# import untrained estimatorfrom ngboost import NGBRegressorng = NGBRegressor()# train using create_modelng_trained = create_model(ng)" }, { "code": null, "e": 7028, "s": 7010, "text": "print(ng_trained)" }, { "code": null, "e": 7419, "s": 7028, "text": "The above two examples gplearn and ngboost are custom models for pycaret as they are not available in the default library but you can use them just like you can use any other out-of-the-box models. However, there may be a use-case that involves writing your own algorithm (i.e. maths behind the algorithm), in which case you can inherit the base class from sklearn and write your own maths." }, { "code": null, "e": 7680, "s": 7419, "text": "Let’s create a naive estimator which learns the mean value of target variable during fit stage and predicts the same mean value for all new data points, irrespective of X input (probably not useful in real life, but just to make demonstrate the functionality)." }, { "code": null, "e": 7997, "s": 7680, "text": "# create custom estimatorimport numpy as npfrom sklearn.base import BaseEstimatorclass MyOwnModel(BaseEstimator): def __init__(self): self.mean = 0 def fit(self, X, y): self.mean = y.mean() return self def predict(self, X): return np.array(X.shape[0]*[self.mean])" }, { "code": null, "e": 8040, "s": 7997, "text": "Now let’s use this estimator for training:" }, { "code": null, "e": 8141, "s": 8040, "text": "# import MyOwnModel classmom = MyOwnModel()# train using create_modelmom_trained = create_model(mom)" }, { "code": null, "e": 8223, "s": 8141, "text": "# generate predictions on datapredictions = predict_model(mom_trained, data=data)" }, { "code": null, "e": 8481, "s": 8223, "text": "Notice that Label column which is essentially the prediction is the same number $13,225 for all the rows, that’s because we created this algorithm in such a way, that learns from the mean of train set and predict the same value (just to keep things simple)." }, { "code": null, "e": 8698, "s": 8481, "text": "I hope that you will appreciate the ease of use and simplicity in PyCaret. In just a few lines, you can perform end-to-end machine learning experiments and write your own algorithms without adjusting any native code." }, { "code": null, "e": 8969, "s": 8698, "text": "Next week I will be writing a tutorial to advance this tutorial. We will write a more complex algorithm instead of just a mean prediction. I will introduce some complex concepts in the next tutorial. Please follow me on Medium, LinkedIn, and Twitter to get more updates." }, { "code": null, "e": 9159, "s": 8969, "text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository." }, { "code": null, "e": 9221, "s": 9159, "text": "To hear more about PyCaret follow us on LinkedIn and Youtube." }, { "code": null, "e": 9269, "s": 9221, "text": "Join us on our slack channel. Invite link here." }, { "code": null, "e": 9732, "s": 9269, "text": "Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE" }, { "code": null, "e": 9823, "s": 9732, "text": "DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret" }, { "code": null, "e": 9895, "s": 9823, "text": "Click on the links below to see the documentation and working examples." } ]
JavaScript location.host vs location.hostname - GeeksforGeeks
25 Jul, 2021 In this article, we will learn about how to get information related to the webpage like hostname, port number, etc. We will also see the difference between the location.hostname and location.host. location object is used to get information about the current web page. host and hostname are properties of location objects. location.hostname: This property will return the domain name of the web page. Syntax: location.hostname Return value: It returns a string representing the domain name or IP address. Example: If this is our URL,https://www.geeksforgeeks.org:8080/ds/heap If this is our URL, https://www.geeksforgeeks.org:8080/ds/heap When we call location.hostname, This will return.www.geeksforgeeks.org When we call location.hostname, This will return. www.geeksforgeeks.org HTML <!DOCTYPE html><html lang="en"> <head> <!-- using jquery library --> <script src="https://code.jquery.com/jquery-git.js"> </script> </head> <body> <script> document.write("hostname : " + location.hostname); </script> </body></html> Output: In order to verify this thing for any webpage, open the webpage you want, then click on inspect and then write console.log(location.hostname) in the console tab. You will get the domain name of the webpage. location.host: This property also returns the same hostname but it also includes the port number. In case, if the port number is not available, then it will just return the hostname. Syntax: location.host Return value: It returns a string representing the domain name and port number. Example: If this is our URL,https://www.geeksforgeeks.org:8080/ds/heap If this is our URL, https://www.geeksforgeeks.org:8080/ds/heap When we call location.host, This will return.www.geeksforgeeks.org:8080 When we call location.host, This will return. www.geeksforgeeks.org:8080 HTML <!DOCTYPE html><html lang="en"> <head> <!-- using jquery library --> <script src="https://code.jquery.com/jquery-git.js"> </script> </head> <body> <script> document.write("host : " + location.host); </script> </body></html> Output: JavaScript-Properties JavaScript-Questions Picked Difference Between JavaScript Web Technologies 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 26215, "s": 26187, "text": "\n25 Jul, 2021" }, { "code": null, "e": 26412, "s": 26215, "text": "In this article, we will learn about how to get information related to the webpage like hostname, port number, etc. We will also see the difference between the location.hostname and location.host." }, { "code": null, "e": 26537, "s": 26412, "text": "location object is used to get information about the current web page. host and hostname are properties of location objects." }, { "code": null, "e": 26615, "s": 26537, "text": "location.hostname: This property will return the domain name of the web page." }, { "code": null, "e": 26623, "s": 26615, "text": "Syntax:" }, { "code": null, "e": 26641, "s": 26623, "text": "location.hostname" }, { "code": null, "e": 26719, "s": 26641, "text": "Return value: It returns a string representing the domain name or IP address." }, { "code": null, "e": 26728, "s": 26719, "text": "Example:" }, { "code": null, "e": 26790, "s": 26728, "text": "If this is our URL,https://www.geeksforgeeks.org:8080/ds/heap" }, { "code": null, "e": 26810, "s": 26790, "text": "If this is our URL," }, { "code": null, "e": 26853, "s": 26810, "text": "https://www.geeksforgeeks.org:8080/ds/heap" }, { "code": null, "e": 26924, "s": 26853, "text": "When we call location.hostname, This will return.www.geeksforgeeks.org" }, { "code": null, "e": 26974, "s": 26924, "text": "When we call location.hostname, This will return." }, { "code": null, "e": 26996, "s": 26974, "text": "www.geeksforgeeks.org" }, { "code": null, "e": 27001, "s": 26996, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> </head> <body> <script> document.write(\"hostname : \" + location.hostname); </script> </body></html>", "e": 27265, "s": 27001, "text": null }, { "code": null, "e": 27273, "s": 27265, "text": "Output:" }, { "code": null, "e": 27480, "s": 27273, "text": "In order to verify this thing for any webpage, open the webpage you want, then click on inspect and then write console.log(location.hostname) in the console tab. You will get the domain name of the webpage." }, { "code": null, "e": 27663, "s": 27480, "text": "location.host: This property also returns the same hostname but it also includes the port number. In case, if the port number is not available, then it will just return the hostname." }, { "code": null, "e": 27672, "s": 27663, "text": "Syntax: " }, { "code": null, "e": 27686, "s": 27672, "text": "location.host" }, { "code": null, "e": 27766, "s": 27686, "text": "Return value: It returns a string representing the domain name and port number." }, { "code": null, "e": 27776, "s": 27766, "text": "Example: " }, { "code": null, "e": 27838, "s": 27776, "text": "If this is our URL,https://www.geeksforgeeks.org:8080/ds/heap" }, { "code": null, "e": 27858, "s": 27838, "text": "If this is our URL," }, { "code": null, "e": 27901, "s": 27858, "text": "https://www.geeksforgeeks.org:8080/ds/heap" }, { "code": null, "e": 27973, "s": 27901, "text": "When we call location.host, This will return.www.geeksforgeeks.org:8080" }, { "code": null, "e": 28019, "s": 27973, "text": "When we call location.host, This will return." }, { "code": null, "e": 28046, "s": 28019, "text": "www.geeksforgeeks.org:8080" }, { "code": null, "e": 28051, "s": 28046, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script> </head> <body> <script> document.write(\"host : \" + location.host); </script> </body></html>", "e": 28301, "s": 28051, "text": null }, { "code": null, "e": 28309, "s": 28301, "text": "Output:" }, { "code": null, "e": 28331, "s": 28309, "text": "JavaScript-Properties" }, { "code": null, "e": 28352, "s": 28331, "text": "JavaScript-Questions" }, { "code": null, "e": 28359, "s": 28352, "text": "Picked" }, { "code": null, "e": 28378, "s": 28359, "text": "Difference Between" }, { "code": null, "e": 28389, "s": 28378, "text": "JavaScript" }, { "code": null, "e": 28406, "s": 28389, "text": "Web Technologies" }, { "code": null, "e": 28504, "s": 28406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28565, "s": 28504, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28633, "s": 28565, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28691, "s": 28633, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 28746, "s": 28691, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 28812, "s": 28746, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 28852, "s": 28812, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28897, "s": 28852, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28958, "s": 28897, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29027, "s": 28958, "text": "How to calculate the number of days between two dates in javascript?" } ]
SQL Query for Matching Multiple Values in the Same Column
29 Oct, 2021 In SQL, for matching multiple values in the same column, we need to use some special words in our query. Below, 3 methods are demonstrated to achieve this using the IN, LIKE and comparison operator(>=). 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 CARS inside the database GeeksForGeeks. This table has 3 columns namely CAR_NAME, COMPANY and COST containing the name, company and cost of various cars. Query: CREATE TABLE CARS( CAR_NAME VARCHAR(10), COMPANY VARCHAR(10), COST INT); Output: Step 4: Describe the structure of the table CARS. Query: EXEC SP_COLUMNS CARS; Output: Step 5: Insert 5 rows into the CARS table. Query: INSERT INTO CARS VALUES('INNOVA','TOYOTA',10000); INSERT INTO CARS VALUES('CAMRY','TOYOTA',20000); INSERT INTO CARS VALUES('CIAZ','HONDA',30000); INSERT INTO CARS VALUES('POLO','VOLKSWAGEN',50000); INSERT INTO CARS VALUES('BENZ','MERCEDES',100000); Output: Step 6: Display all the rows of the CARS table. Query: SELECT * FROM CARS; Output: Step 7: Retrieve the details of all the cars belonging to the companies TOYOTA and HONDA. Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2); Query: SELECT * FROM CARS WHERE COMPANY IN ('TOYOTA','HONDA'); Output: Step 8: Retrieve the details of all the cars whose name starts with the letter C. Note – Use of LIKE for matching multiple values i.e. CAMRY and CIAZ in the same column i.e. CAR_NAME. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE 'STARTING_LETTER%'; Query: SELECT * FROM CARS WHERE CAR_NAME LIKE 'C%'; Output: Step 9: Retrieve the details of all the cars having cost greater than or equal to 30000. Note – Use of comparison operator >= for matching multiple values i.e. 30000, 50000 and 100000 in the same column i.e. COST. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME >=VALUE; Query: SELECT * FROM CARS WHERE COST>=30000; Output: DBMS-SQL Picked 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? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Window functions in SQL SQL | GROUP BY Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE SQL Correlated Subqueries
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Oct, 2021" }, { "code": null, "e": 335, "s": 54, "text": "In SQL, for matching multiple values in the same column, we need to use some special words in our query. Below, 3 methods are demonstrated to achieve this using the IN, LIKE and comparison operator(>=). For this article, we will be using the Microsoft SQL Server as our database." }, { "code": null, "e": 435, "s": 335, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 442, "s": 435, "text": "Query:" }, { "code": null, "e": 472, "s": 442, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 480, "s": 472, "text": "Output:" }, { "code": null, "e": 552, "s": 480, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 559, "s": 552, "text": "Query:" }, { "code": null, "e": 577, "s": 559, "text": "USE GeeksForGeeks" }, { "code": null, "e": 585, "s": 577, "text": "Output:" }, { "code": null, "e": 762, "s": 585, "text": "Step 3: Create a table CARS inside the database GeeksForGeeks. This table has 3 columns namely CAR_NAME, COMPANY and COST containing the name, company and cost of various cars." }, { "code": null, "e": 769, "s": 762, "text": "Query:" }, { "code": null, "e": 842, "s": 769, "text": "CREATE TABLE CARS(\nCAR_NAME VARCHAR(10),\nCOMPANY VARCHAR(10),\nCOST INT);" }, { "code": null, "e": 850, "s": 842, "text": "Output:" }, { "code": null, "e": 900, "s": 850, "text": "Step 4: Describe the structure of the table CARS." }, { "code": null, "e": 907, "s": 900, "text": "Query:" }, { "code": null, "e": 929, "s": 907, "text": "EXEC SP_COLUMNS CARS;" }, { "code": null, "e": 937, "s": 929, "text": "Output:" }, { "code": null, "e": 980, "s": 937, "text": "Step 5: Insert 5 rows into the CARS table." }, { "code": null, "e": 987, "s": 980, "text": "Query:" }, { "code": null, "e": 1236, "s": 987, "text": "INSERT INTO CARS VALUES('INNOVA','TOYOTA',10000);\nINSERT INTO CARS VALUES('CAMRY','TOYOTA',20000);\nINSERT INTO CARS VALUES('CIAZ','HONDA',30000);\nINSERT INTO CARS VALUES('POLO','VOLKSWAGEN',50000);\nINSERT INTO CARS VALUES('BENZ','MERCEDES',100000);" }, { "code": null, "e": 1244, "s": 1236, "text": "Output:" }, { "code": null, "e": 1292, "s": 1244, "text": "Step 6: Display all the rows of the CARS table." }, { "code": null, "e": 1299, "s": 1292, "text": "Query:" }, { "code": null, "e": 1319, "s": 1299, "text": "SELECT * FROM CARS;" }, { "code": null, "e": 1327, "s": 1319, "text": "Output:" }, { "code": null, "e": 1417, "s": 1327, "text": "Step 7: Retrieve the details of all the cars belonging to the companies TOYOTA and HONDA." }, { "code": null, "e": 1518, "s": 1417, "text": "Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY." }, { "code": null, "e": 1526, "s": 1518, "text": "Syntax:" }, { "code": null, "e": 1607, "s": 1526, "text": "SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);" }, { "code": null, "e": 1614, "s": 1607, "text": "Query:" }, { "code": null, "e": 1670, "s": 1614, "text": "SELECT * FROM CARS WHERE COMPANY IN ('TOYOTA','HONDA');" }, { "code": null, "e": 1678, "s": 1670, "text": "Output:" }, { "code": null, "e": 1760, "s": 1678, "text": "Step 8: Retrieve the details of all the cars whose name starts with the letter C." }, { "code": null, "e": 1862, "s": 1760, "text": "Note – Use of LIKE for matching multiple values i.e. CAMRY and CIAZ in the same column i.e. CAR_NAME." }, { "code": null, "e": 1870, "s": 1862, "text": "Syntax:" }, { "code": null, "e": 1938, "s": 1870, "text": "SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE 'STARTING_LETTER%';" }, { "code": null, "e": 1945, "s": 1938, "text": "Query:" }, { "code": null, "e": 1990, "s": 1945, "text": "SELECT * FROM CARS WHERE CAR_NAME LIKE 'C%';" }, { "code": null, "e": 1998, "s": 1990, "text": "Output:" }, { "code": null, "e": 2087, "s": 1998, "text": "Step 9: Retrieve the details of all the cars having cost greater than or equal to 30000." }, { "code": null, "e": 2212, "s": 2087, "text": "Note – Use of comparison operator >= for matching multiple values i.e. 30000, 50000 and 100000 in the same column i.e. COST." }, { "code": null, "e": 2220, "s": 2212, "text": "Syntax:" }, { "code": null, "e": 2272, "s": 2220, "text": "SELECT * FROM TABLE_NAME WHERE COLUMN_NAME >=VALUE;" }, { "code": null, "e": 2279, "s": 2272, "text": "Query:" }, { "code": null, "e": 2317, "s": 2279, "text": "SELECT * FROM CARS WHERE COST>=30000;" }, { "code": null, "e": 2325, "s": 2317, "text": "Output:" }, { "code": null, "e": 2334, "s": 2325, "text": "DBMS-SQL" }, { "code": null, "e": 2341, "s": 2334, "text": "Picked" }, { "code": null, "e": 2345, "s": 2341, "text": "SQL" }, { "code": null, "e": 2349, "s": 2345, "text": "SQL" }, { "code": null, "e": 2447, "s": 2349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2513, "s": 2447, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2537, "s": 2513, "text": "SQL Interview Questions" }, { "code": null, "e": 2549, "s": 2537, "text": "SQL | Views" }, { "code": null, "e": 2594, "s": 2549, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 2626, "s": 2594, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 2650, "s": 2626, "text": "Window functions in SQL" }, { "code": null, "e": 2665, "s": 2650, "text": "SQL | GROUP BY" }, { "code": null, "e": 2704, "s": 2665, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 2743, "s": 2704, "text": "Difference between DELETE and TRUNCATE" } ]
Set contains() method in Java with Examples
31 Dec, 2018 The Java.util.Set.contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element. Syntax: boolean contains(Object element) Parameters: The parameter element is of the type of Set. This is the element that needs to be tested if it is present in the set or not. Return Value: The method returns true if the element is present in the set else return False. Below program illustrate the Java.util.Set.contains() method: // Java code to illustrate Set.contains() methodimport java.io.*;import java.util.*; public class HashSetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Using add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the Set System.out.println("Set: " + set); // Check for "Geeks" in the set System.out.println("Does the Set contains 'Geeks'? " + set.contains("Geeks")); // Check for "4" in the set System.out.println("Does the Set contains '4'? " + set.contains("4")); // Check if the Set contains "No" System.out.println("Does the Set contains 'No'? " + set.contains("No")); }} Set: [4, Geeks, Welcome, To] Does the Set contains 'Geeks'? true Does the Set contains '4'? true Does the Set contains 'No'? false Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#contains(java.lang.Object) Java-Collections Java-Functions java-set Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Queue Interface In Java How to add an element to an Array in Java? Multidimensional Arrays in Java Math pow() method in Java with Example PriorityQueue in Java Stack Class in Java List Interface in Java with Examples ArrayList in Java Different ways of Reading a text file in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Dec, 2018" }, { "code": null, "e": 213, "s": 28, "text": "The Java.util.Set.contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element." }, { "code": null, "e": 221, "s": 213, "text": "Syntax:" }, { "code": null, "e": 254, "s": 221, "text": "boolean contains(Object element)" }, { "code": null, "e": 391, "s": 254, "text": "Parameters: The parameter element is of the type of Set. This is the element that needs to be tested if it is present in the set or not." }, { "code": null, "e": 485, "s": 391, "text": "Return Value: The method returns true if the element is present in the set else return False." }, { "code": null, "e": 547, "s": 485, "text": "Below program illustrate the Java.util.Set.contains() method:" }, { "code": "// Java code to illustrate Set.contains() methodimport java.io.*;import java.util.*; public class HashSetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Using add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the Set System.out.println(\"Set: \" + set); // Check for \"Geeks\" in the set System.out.println(\"Does the Set contains 'Geeks'? \" + set.contains(\"Geeks\")); // Check for \"4\" in the set System.out.println(\"Does the Set contains '4'? \" + set.contains(\"4\")); // Check if the Set contains \"No\" System.out.println(\"Does the Set contains 'No'? \" + set.contains(\"No\")); }}", "e": 1489, "s": 547, "text": null }, { "code": null, "e": 1621, "s": 1489, "text": "Set: [4, Geeks, Welcome, To]\nDoes the Set contains 'Geeks'? true\nDoes the Set contains '4'? true\nDoes the Set contains 'No'? false\n" }, { "code": null, "e": 1720, "s": 1621, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#contains(java.lang.Object)" }, { "code": null, "e": 1737, "s": 1720, "text": "Java-Collections" }, { "code": null, "e": 1752, "s": 1737, "text": "Java-Functions" }, { "code": null, "e": 1761, "s": 1752, "text": "java-set" }, { "code": null, "e": 1766, "s": 1761, "text": "Java" }, { "code": null, "e": 1771, "s": 1766, "text": "Java" }, { "code": null, "e": 1788, "s": 1771, "text": "Java-Collections" }, { "code": null, "e": 1886, "s": 1788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1905, "s": 1886, "text": "Interfaces in Java" }, { "code": null, "e": 1929, "s": 1905, "text": "Queue Interface In Java" }, { "code": null, "e": 1972, "s": 1929, "text": "How to add an element to an Array in Java?" }, { "code": null, "e": 2004, "s": 1972, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2043, "s": 2004, "text": "Math pow() method in Java with Example" }, { "code": null, "e": 2065, "s": 2043, "text": "PriorityQueue in Java" }, { "code": null, "e": 2085, "s": 2065, "text": "Stack Class in Java" }, { "code": null, "e": 2122, "s": 2085, "text": "List Interface in Java with Examples" }, { "code": null, "e": 2140, "s": 2122, "text": "ArrayList in Java" } ]
WML - Overview
The topmost layer in the WAP (Wireless Application Protocol) architecture is made up of WAE (Wireless Application Environment), which consists of WML and WML scripting language. WML stands for Wireless Markup Language WML stands for Wireless Markup Language WML is an application of XML, which is defined in a document-type definition. WML is an application of XML, which is defined in a document-type definition. WML is based on HDML and is modified so that it can be compared with HTML. WML is based on HDML and is modified so that it can be compared with HTML. WML takes care of the small screen and the low bandwidth of transmission. WML takes care of the small screen and the low bandwidth of transmission. WML is the markup language defined in the WAP specification. WML is the markup language defined in the WAP specification. WAP sites are written in WML, while web sites are written in HTML. WAP sites are written in WML, while web sites are written in HTML. WML is very similar to HTML. Both of them use tags and are written in plain text format. WML is very similar to HTML. Both of them use tags and are written in plain text format. WML files have the extension ".wml". The MIME type of WML is "text/vnd.wap.wml". WML files have the extension ".wml". The MIME type of WML is "text/vnd.wap.wml". WML supports client-side scripting. The scripting language supported is called WMLScript. WML supports client-side scripting. The scripting language supported is called WMLScript. WAP Forum has released a latest version WAP 2.0. The markup language defined in WAP 2.0 is XHTML Mobile Profile (MP). The WML MP is a subset of the XHTML. A style sheet called WCSS (WAP CSS) has been introduced alongwith XHTML MP. The WCSS is a subset of the CSS2. Most of the new mobile phone models released are WAP 2.0-enabled. Because WAP 2.0 is backward compatible to WAP 1.x, WAP 2.0-enabled mobile devices can display both XHTML MP and WML documents. WML 1.x is an earlier technology. However, that does not mean it is of no use, since a lot of wireless devices that only supports WML 1.x are still being used. Latest version of WML is 2.0 and it is created for backward compatibility purposes. So WAP site developers need not to worry about WML 2.0. A main difference between HTML and WML is that the basic unit of navigation in HTML is a page, while that in WML is a card. A WML file can contain multiple cards and they form a deck. When a WML page is accessed from a mobile phone, all the cards in the page are downloaded from the WAP server. So if the user goes to another card of the same deck, the mobile browser does not have to send any requests to the server since the file that contains the deck is already stored in the wireless device. You can put links, text, images, input fields, option boxes and many other elements in a card. Following is the basic structure of a WML program: <?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN" "http://www.wapforum.org/DTD/wml12.dtd"> <wml> <card id="one" title="First Card"> <p> This is the first card in the deck </p> </card> <card id="two" title="Second Card"> <p> Ths is the second card in the deck </p> </card> </wml> The first line of this text says that this is an XML document and the version is 1.0. The second line selects the document type and gives the URL of the document type definition (DTD). One WML deck (i.e. page ) can have one or more cards as shown above. We will see complete details on WML document structure in subsequent chapter. Unlike HTML 4.01 Transitional, text cannot be enclosed directly in the <card>...</card> tag pair. So you need to put a content inside <p>...</p> as shown above. Wireless devices are limited by the size of their displays and keypads. It's therefore very important to take this into account when designing a WAP Site. While designing a WAP site you must ensure that you keep things simple and easy to use. You should always keep in mind that there are no standard microbrowser behaviors and that the data link may be relatively slow, at around 10Kbps. However, with GPRS, EDGE, and UMTS, this may not be the case for long, depending on where you are located. The following are general design tips that you should keep in mind when designing a service: Keep the WML decks and images to less than 1.5KB. Keep the WML decks and images to less than 1.5KB. Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry. Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry. Keep URLs brief and easy to recall. Keep URLs brief and easy to recall. Minimize menu levels to prevent users from getting lost and the system from slowing down. Minimize menu levels to prevent users from getting lost and the system from slowing down. Use standard layout tags such as <big> and <b>, and logically structure your information. Use standard layout tags such as <big> and <b>, and logically structure your information. Don't go overboard with the use of graphics, as many target devices may not support them. Don't go overboard with the use of graphics, as many target devices may not support them.
[ { "code": null, "e": 2251, "s": 2073, "text": "The topmost layer in the WAP (Wireless Application Protocol) architecture is made up of WAE (Wireless Application Environment), which consists of WML and WML scripting language." }, { "code": null, "e": 2291, "s": 2251, "text": "WML stands for Wireless Markup Language" }, { "code": null, "e": 2331, "s": 2291, "text": "WML stands for Wireless Markup Language" }, { "code": null, "e": 2409, "s": 2331, "text": "WML is an application of XML, which is defined in a document-type definition." }, { "code": null, "e": 2487, "s": 2409, "text": "WML is an application of XML, which is defined in a document-type definition." }, { "code": null, "e": 2562, "s": 2487, "text": "WML is based on HDML and is modified so that it can be compared with HTML." }, { "code": null, "e": 2637, "s": 2562, "text": "WML is based on HDML and is modified so that it can be compared with HTML." }, { "code": null, "e": 2711, "s": 2637, "text": "WML takes care of the small screen and the low bandwidth of transmission." }, { "code": null, "e": 2785, "s": 2711, "text": "WML takes care of the small screen and the low bandwidth of transmission." }, { "code": null, "e": 2846, "s": 2785, "text": "WML is the markup language defined in the WAP specification." }, { "code": null, "e": 2907, "s": 2846, "text": "WML is the markup language defined in the WAP specification." }, { "code": null, "e": 2974, "s": 2907, "text": "WAP sites are written in WML, while web sites are written in HTML." }, { "code": null, "e": 3041, "s": 2974, "text": "WAP sites are written in WML, while web sites are written in HTML." }, { "code": null, "e": 3130, "s": 3041, "text": "WML is very similar to HTML. Both of them use tags and are written in plain text format." }, { "code": null, "e": 3219, "s": 3130, "text": "WML is very similar to HTML. Both of them use tags and are written in plain text format." }, { "code": null, "e": 3300, "s": 3219, "text": "WML files have the extension \".wml\". The MIME type of WML is \"text/vnd.wap.wml\"." }, { "code": null, "e": 3381, "s": 3300, "text": "WML files have the extension \".wml\". The MIME type of WML is \"text/vnd.wap.wml\"." }, { "code": null, "e": 3471, "s": 3381, "text": "WML supports client-side scripting. The scripting language supported is called WMLScript." }, { "code": null, "e": 3561, "s": 3471, "text": "WML supports client-side scripting. The scripting language supported is called WMLScript." }, { "code": null, "e": 3827, "s": 3561, "text": "WAP Forum has released a latest version WAP 2.0. The markup language defined in WAP 2.0 is XHTML Mobile Profile (MP). The WML MP is a subset of the XHTML. A style sheet called WCSS (WAP CSS) has been introduced alongwith XHTML MP. The WCSS is a subset of the CSS2." }, { "code": null, "e": 4020, "s": 3827, "text": "Most of the new mobile phone models released are WAP 2.0-enabled. Because WAP 2.0 is backward compatible to WAP 1.x, WAP 2.0-enabled mobile devices can display both XHTML MP and WML documents." }, { "code": null, "e": 4320, "s": 4020, "text": "WML 1.x is an earlier technology. However, that does not mean it is of no use, since a lot of wireless devices that only supports WML 1.x are still being used. Latest version of WML is 2.0 and it is created for backward compatibility purposes. So WAP site developers need not to worry about WML 2.0." }, { "code": null, "e": 4504, "s": 4320, "text": "A main difference between HTML and WML is that the basic unit of navigation in HTML is a page, while that in WML is a card. A WML file can contain multiple cards and they form a deck." }, { "code": null, "e": 4817, "s": 4504, "text": "When a WML page is accessed from a mobile phone, all the cards in the page are downloaded from the WAP server. So if the user goes to another card of the same deck, the mobile browser does not have to send any requests to the server since the file that contains the deck is already stored in the wireless device." }, { "code": null, "e": 4912, "s": 4817, "text": "You can put links, text, images, input fields, option boxes and many other elements in a card." }, { "code": null, "e": 4963, "s": 4912, "text": "Following is the basic structure of a WML program:" }, { "code": null, "e": 5270, "s": 4963, "text": "<?xml version=\"1.0\"?>\n<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\"\n\"http://www.wapforum.org/DTD/wml12.dtd\">\n\n<wml>\n\n<card id=\"one\" title=\"First Card\">\n<p>\nThis is the first card in the deck\n</p>\n</card>\n\n<card id=\"two\" title=\"Second Card\">\n<p>\nThs is the second card in the deck\n</p>\n</card>\n\n</wml>" }, { "code": null, "e": 5455, "s": 5270, "text": "The first line of this text says that this is an XML document and the version is 1.0. The second line selects\nthe document type and gives the URL of the document type definition (DTD)." }, { "code": null, "e": 5602, "s": 5455, "text": "One WML deck (i.e. page ) can have one or more cards as shown above. We will see complete details on WML document structure in subsequent chapter." }, { "code": null, "e": 5763, "s": 5602, "text": "Unlike HTML 4.01 Transitional, text cannot be enclosed directly in the <card>...</card> tag pair. So you need to put a content inside <p>...</p> as shown above." }, { "code": null, "e": 5918, "s": 5763, "text": "Wireless devices are limited by the size of their displays and keypads. It's therefore very important to take this into account when designing a WAP Site." }, { "code": null, "e": 6260, "s": 5918, "text": "While designing a WAP site you must ensure that you keep things simple and easy to use. You should always keep in mind that there are no standard microbrowser behaviors and that the data link may be relatively slow, at around 10Kbps. However, with GPRS, EDGE, and UMTS, this may not be the case for long, depending on where you are located." }, { "code": null, "e": 6353, "s": 6260, "text": "The following are general design tips that you should keep in mind when designing a service:" }, { "code": null, "e": 6403, "s": 6353, "text": "Keep the WML decks and images to less than 1.5KB." }, { "code": null, "e": 6453, "s": 6403, "text": "Keep the WML decks and images to less than 1.5KB." }, { "code": null, "e": 6593, "s": 6453, "text": "Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry." }, { "code": null, "e": 6733, "s": 6593, "text": "Keep text brief and meaningful, and as far as possible try to precode options to minimize the rather painful experience of user data entry." }, { "code": null, "e": 6769, "s": 6733, "text": "Keep URLs brief and easy to recall." }, { "code": null, "e": 6805, "s": 6769, "text": "Keep URLs brief and easy to recall." }, { "code": null, "e": 6895, "s": 6805, "text": "Minimize menu levels to prevent users from getting lost and the system from slowing down." }, { "code": null, "e": 6985, "s": 6895, "text": "Minimize menu levels to prevent users from getting lost and the system from slowing down." }, { "code": null, "e": 7075, "s": 6985, "text": "Use standard layout tags such as <big> and <b>, and logically structure your information." }, { "code": null, "e": 7165, "s": 7075, "text": "Use standard layout tags such as <big> and <b>, and logically structure your information." }, { "code": null, "e": 7255, "s": 7165, "text": "Don't go overboard with the use of graphics, as many target devices may not support them." } ]
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
07 Jul, 2022 Some of the string methods are covered in the set 3 belowString Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count(“string”, beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning position( by default 0) and end position(by default string length). # Python code to demonstrate working of # len() and count()str = "geeksforgeeks is for geeks" # Printing length of string using len()print (" The length of string is : ", len(str)); # Printing occurrence of "geeks" in string# Prints 2 as it only checks till 15th elementprint (" Number of appearance of ""geeks"" is : ",end="")print (str.count("geeks",0,15)) Output: 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. The length of string is : 26 Number of appearance of geeks is : 2 3. center() :- This function is used to surround the string with a character repeated both sides of string multiple times. By default the character is a space. Takes 2 arguments, length of string and the character. 4. ljust() :- This function returns the original string shifted to left that has a character at its right. It left adjusts the string. By default the character is space. It also takes two arguments, length of string and the character.5. rjust() :- This function returns the original string shifted to right that has a character at its left. It right adjusts the string. By default the character is space. It also takes two arguments, length of string and the character. # Python code to demonstrate working of # center(), ljust() and rjust()str = "geeksforgeeks" # Printing the string after centering with '-'print ("The string after centering with '-' is : ",end="")print ( str.center(20,'-')) # Printing the string after ljust()print ("The string after ljust is : ",end="")print ( str.ljust(20,'-')) # Printing the string after rjust()print ("The string after rjust is : ",end="")print ( str.rjust(20,'-')) Output: The string after centering with '-' is : ---geeksforgeeks---- The string after ljust is : geeksforgeeks------- The string after rjust is : -------geeksforgeeks 6. isalpha() :- This function returns true when all the characters in the string are alphabets else returns false. 7. isalnum() :- This function returns true when all the characters in the string are combination of numbers and/or alphabets else returns false. 8. isspace() :- This function returns true when all the characters in the string are spaces else returns false. # Python code to demonstrate working of # isalpha(), isalnum(), isspace()str = "geeksforgeeks"str1 = "123" # Checking if str has all alphabets if (str.isalpha()): print ("All characters are alphabets in str")else : print ("All characters are not alphabets in str") # Checking if str1 has all numbersif (str1.isalnum()): print ("All characters are numbers in str1")else : print ("All characters are not numbers in str1") # Checking if str1 has all spacesif (str1.isspace()): print ("All characters are spaces in str1")else : print ("All characters are not spaces in str1") Output: All characters are alphabets in str All characters are numbers in str1 All characters are not spaces in str1 9. join() :- This function is used to join a sequence of strings mentioned in its arguments with the string. # Python code to demonstrate working of # join()str = "_"str1 = ( "geeks", "for", "geeks" ) # using join() to join sequence str1 with strprint ("The string after joining is : ", end="")print ( str.join(str1)) Output: The string after joining is : geeks_for_geeks Python School Programming 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 How to Install PIP on Windows ? *args and **kwargs in Python Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 132, "s": 52, "text": "Some of the string methods are covered in the set 3 belowString Methods Part- 1" }, { "code": null, "e": 175, "s": 132, "text": "More methods are discussed in this article" }, { "code": null, "e": 235, "s": 175, "text": "1. len() :- This function returns the length of the string." }, { "code": null, "e": 465, "s": 235, "text": "2. count(“string”, beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning position( by default 0) and end position(by default string length)." }, { "code": "# Python code to demonstrate working of # len() and count()str = \"geeksforgeeks is for geeks\" # Printing length of string using len()print (\" The length of string is : \", len(str)); # Printing occurrence of \"geeks\" in string# Prints 2 as it only checks till 15th elementprint (\" Number of appearance of \"\"geeks\"\" is : \",end=\"\")print (str.count(\"geeks\",0,15))", "e": 827, "s": 465, "text": null }, { "code": null, "e": 835, "s": 827, "text": "Output:" }, { "code": null, "e": 844, "s": 835, "text": "Chapters" }, { "code": null, "e": 871, "s": 844, "text": "descriptions off, selected" }, { "code": null, "e": 921, "s": 871, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 944, "s": 921, "text": "captions off, selected" }, { "code": null, "e": 952, "s": 944, "text": "English" }, { "code": null, "e": 976, "s": 952, "text": "This is a modal window." }, { "code": null, "e": 1045, "s": 976, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1067, "s": 1045, "text": "End of dialog window." }, { "code": null, "e": 1137, "s": 1067, "text": " The length of string is : 26\n Number of appearance of geeks is : 2\n" }, { "code": null, "e": 1352, "s": 1137, "text": "3. center() :- This function is used to surround the string with a character repeated both sides of string multiple times. By default the character is a space. Takes 2 arguments, length of string and the character." }, { "code": null, "e": 1822, "s": 1352, "text": "4. ljust() :- This function returns the original string shifted to left that has a character at its right. It left adjusts the string. By default the character is space. It also takes two arguments, length of string and the character.5. rjust() :- This function returns the original string shifted to right that has a character at its left. It right adjusts the string. By default the character is space. It also takes two arguments, length of string and the character." }, { "code": "# Python code to demonstrate working of # center(), ljust() and rjust()str = \"geeksforgeeks\" # Printing the string after centering with '-'print (\"The string after centering with '-' is : \",end=\"\")print ( str.center(20,'-')) # Printing the string after ljust()print (\"The string after ljust is : \",end=\"\")print ( str.ljust(20,'-')) # Printing the string after rjust()print (\"The string after rjust is : \",end=\"\")print ( str.rjust(20,'-'))", "e": 2265, "s": 1822, "text": null }, { "code": null, "e": 2273, "s": 2265, "text": "Output:" }, { "code": null, "e": 2434, "s": 2273, "text": "The string after centering with '-' is : ---geeksforgeeks----\nThe string after ljust is : geeksforgeeks-------\nThe string after rjust is : -------geeksforgeeks\n" }, { "code": null, "e": 2549, "s": 2434, "text": "6. isalpha() :- This function returns true when all the characters in the string are alphabets else returns false." }, { "code": null, "e": 2694, "s": 2549, "text": "7. isalnum() :- This function returns true when all the characters in the string are combination of numbers and/or alphabets else returns false." }, { "code": null, "e": 2806, "s": 2694, "text": "8. isspace() :- This function returns true when all the characters in the string are spaces else returns false." }, { "code": "# Python code to demonstrate working of # isalpha(), isalnum(), isspace()str = \"geeksforgeeks\"str1 = \"123\" # Checking if str has all alphabets if (str.isalpha()): print (\"All characters are alphabets in str\")else : print (\"All characters are not alphabets in str\") # Checking if str1 has all numbersif (str1.isalnum()): print (\"All characters are numbers in str1\")else : print (\"All characters are not numbers in str1\") # Checking if str1 has all spacesif (str1.isspace()): print (\"All characters are spaces in str1\")else : print (\"All characters are not spaces in str1\")", "e": 3400, "s": 2806, "text": null }, { "code": null, "e": 3408, "s": 3400, "text": "Output:" }, { "code": null, "e": 3518, "s": 3408, "text": "All characters are alphabets in str\nAll characters are numbers in str1\nAll characters are not spaces in str1\n" }, { "code": null, "e": 3627, "s": 3518, "text": "9. join() :- This function is used to join a sequence of strings mentioned in its arguments with the string." }, { "code": "# Python code to demonstrate working of # join()str = \"_\"str1 = ( \"geeks\", \"for\", \"geeks\" ) # using join() to join sequence str1 with strprint (\"The string after joining is : \", end=\"\")print ( str.join(str1))", "e": 3837, "s": 3627, "text": null }, { "code": null, "e": 3845, "s": 3837, "text": "Output:" }, { "code": null, "e": 3892, "s": 3845, "text": "The string after joining is : geeks_for_geeks\n" }, { "code": null, "e": 3899, "s": 3892, "text": "Python" }, { "code": null, "e": 3918, "s": 3899, "text": "School Programming" }, { "code": null, "e": 4016, "s": 3918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4034, "s": 4016, "text": "Python Dictionary" }, { "code": null, "e": 4076, "s": 4034, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4098, "s": 4076, "text": "Enumerate() in Python" }, { "code": null, "e": 4130, "s": 4098, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4159, "s": 4130, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4177, "s": 4159, "text": "Python Dictionary" }, { "code": null, "e": 4202, "s": 4177, "text": "Reverse a string in Java" }, { "code": null, "e": 4218, "s": 4202, "text": "Arrays in C/C++" }, { "code": null, "e": 4241, "s": 4218, "text": "Introduction To PYTHON" } ]
Sort a nearly sorted (or K sorted) array
12 Jul, 2022 Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. Examples: Input : arr[] = {6, 5, 3, 2, 8, 10, 9} k = 3 Output : arr[] = {2, 3, 5, 6, 8, 9, 10} Input : arr[] = {10, 9, 8, 7, 4, 70, 60, 50} k = 4Output : arr[] = {4, 7, 8, 9, 10, 50, 60, 70} We can use Insertion Sort to sort the elements efficiently. Following is the C code for standard Insertion Sort. C++ C Java Python3 C# Javascript /* Function to sort an array using insertion sort*/void insertionSort(int A[], int size){ int i, key, j; for(i = 1; i < size; i++) { key = A[i]; j = i - 1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j + 1] = A[j]; j = j - 1; } A[j + 1] = key; }} // This code is contributed by Shivani /* Function to sort an array using insertion sort*/void insertionSort(int A[], int size){ int i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i-1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j+1] = A[j]; j = j-1; } A[j+1] = key; }} /* Function to sort an array using insertion sort*/static void insertionSort(int A[], int size){ int i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i-1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j+1] = A[j]; j = j-1; } A[j+1] = key; }} # Function to sort an array using# insertion sort def insertionSort(A, size): i, key, j = 0, 0, 0 for i in range(size): key = A[i] j = i-1 # Move elements of A[0..i-1], that are # greater than key, to one position # ahead of their current position. # This loop will run at most k times while j >= 0 and A[j] > key: A[j + 1] = A[j] j = j - 1 A[j + 1] = key /* C# Function to sort an array using insertion sort*/static void insertionSort(int A[], int size){ int i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i - 1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j + 1] = A[j]; j = j - 1; } A[j + 1] = key; }} /* Function to sort an array using insertion sort*/function insertionSort(A, size){ var i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i-1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j+1] = A[j]; j = j-1; } A[j+1] = key; }} // This code is contributed by itsok. Time Complexity: O(nk), The inner loop will run at most k times. To move every element to its correct place, at most k elements need to be moved. Auxiliary Space: O(1) We can sort such arrays more efficiently with the help of Heap data structure. Following is the detailed process that uses Heap. 1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time (See this GFact). We are creating heap of size k as the element can be at most k distance from its index in a sorted array. 2) One by one remove min element from heap, put it in result array, and add a new element to heap from remaining elements.Removing an element and adding a new element to min heap will take log k time. So overall complexity will be O(k) + O((n-k) * log(k)). C++ Java Python3 C# Javascript // A STL based C++ program to sort a nearly sorted array.#include <bits/stdc++.h>using namespace std; // Given an array of size n, where every element// is k away from its target position, sorts the// array in O(n logk) time.void sortK(int arr[], int n, int k){ // Insert first k+1 items in a priority queue (or min // heap) //(A O(k) operation). We assume, k < n. //if size of array = k i.e k away from its target position //then int size; size=(n==k)?k:k+1; priority_queue<int, vector<int>, greater<int> > pq(arr, arr +size); // i is index for remaining elements in arr[] and index // is target index of for current minimum element in // Min Heap 'pq'. int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = pq.top(); pq.pop(); pq.push(arr[i]); } while (pq.empty() == false) { arr[index++] = pq.top(); pq.pop(); }} // A utility function to print array elementsvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl;} // Driver program to test above functionsint main(){ int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << "Following is sorted array" << endl; printArray(arr, n); return 0;} // A java program to sort a nearly sorted arrayimport java.util.Iterator;import java.util.PriorityQueue; class GFG { private static void kSort(int[] arr, int n, int k) { if (arr == null || arr.length == 0) { return; } // min heap PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); // if there are less than k + 1 elements present in the array int minCount = Math.min(arr.length, k + 1); // add first k + 1 items to the min heap for (int i = 0; i < minCount; i++) { priorityQueue.add(arr[i]); } int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = priorityQueue.peek(); priorityQueue.poll(); priorityQueue.add(arr[i]); } Iterator<Integer> itr = priorityQueue.iterator(); while (itr.hasNext()) { arr[index++] = priorityQueue.peek(); priorityQueue.poll(); } } // A utility function to print the array private static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Driver Code public static void main(String[] args) { int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = arr.length; kSort(arr, n, k); System.out.println("Following is sorted array"); printArray(arr, n); }} // This code is contributed by// Manpreet Singh(manpreetsngh294) # A Python3 program to sort a# nearly sorted array. from heapq import heappop, heappush, heapify # A utility function to print# array elementsdef print_array(arr: list): for elem in arr: print(elem, end=' ') # Given an array of size n, where every# element is k away from its target# position, sorts the array in O(nLogk) time. def sort_k(arr: list, n: int, k: int): """ :param arr: input array :param n: length of the array :param k: max distance, which every element is away from its target position. :return: None """ # List of first k+1 items heap = arr[:k + 1] # using heapify to convert list # into heap(or min heap) heapify(heap) # "rem_elmnts_index" is index for remaining # elements in arr and "target_index" is # target index of for current minimum element # in Min Heap "heap". target_index = 0 for rem_elmnts_index in range(k + 1, n): arr[target_index] = heappop(heap) heappush(heap, arr[rem_elmnts_index]) target_index += 1 while heap: arr[target_index] = heappop(heap) target_index += 1 # Driver Codek = 3arr = [2, 6, 3, 12, 56, 8]n = len(arr)sort_k(arr, n, k) print('Following is sorted array')print_array(arr) # This code is contributed by# Veerat Beri(viratberi) // A C# program to sort a nearly sorted arrayusing System;using System.Collections.Generic;class GFG { static void kSort(int[] arr, int n, int k) { // min heap List<int> priorityQueue = new List<int>(); // add first k + 1 items to the min heap for (int i = 0; i < k + 1; i++) { priorityQueue.Add(arr[i]); } priorityQueue.Sort(); int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = priorityQueue[0]; priorityQueue.RemoveAt(0); priorityQueue.Add(arr[i]); priorityQueue.Sort(); } int queue_size = priorityQueue.Count; for (int i = 0; i < queue_size; i++) { arr[index++] = priorityQueue[0]; priorityQueue.RemoveAt(0); } } // A utility function to print the array static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Driver code static void Main() { int k = 3; int[] arr = { 2, 6, 3, 12, 56, 8 }; int n = arr.Length; kSort(arr, n, k); Console.WriteLine("Following is sorted array"); printArray(arr, n); }} // This code is contributed by divyeshrabadiya07. <script>// A javascript program to sort a nearly sorted array function kSort(arr,n,k){ let priorityQueue=[]; // add first k + 1 items to the min heap for (let i = 0; i < k + 1; i++) { priorityQueue.push(arr[i]); } priorityQueue.sort(function(a,b){return a-b;}); let index = 0; for (let i = k + 1; i < n; i++) { arr[index++] = priorityQueue[0]; priorityQueue.shift(); priorityQueue.push(arr[i]); priorityQueue.sort(function(a,b){return a-b;}); } while (priorityQueue.length != 0) { arr[index++] = priorityQueue[0]; priorityQueue.shift(); }} // A utility function to print the arrayfunction printArray(arr,n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Driver Codelet k = 3;let arr = [ 2, 6, 3, 12, 56, 8 ];let n = arr.length;kSort(arr, n, k);document.write("Following is sorted array<br>");printArray(arr, n); // This code is contributed by unknown2108</script> Following is sorted array 2 3 6 8 12 56 Time Complexity: O(k) + O((m) * log(k)) , where m = n – kAuxiliary Space: O(k) We can also use a Balanced Binary Search Tree instead of Heap to store k+1 elements. The insert and delete operations on Balanced BST also take O(log k) time. So Balanced BST based method will also take O(n log k) time, but the Heap based method seems to be more efficient as the minimum element will always be at root. Also, Heap doesn’t need extra space for left and right pointers. The previous algorithm is good the time and space complexity can be improved with a variation of Quick Sort algorithm. If you aren’t familiar with quicksort take a look at it before reading through this solution. The algorithm uses quick sort but changes the partition function in 2 ways. Selects pivot element as the middle element instead of the first or last element.Scans the array from max(low, mid – k) to min(mid + k, high) instead of low to high. Selects pivot element as the middle element instead of the first or last element. Scans the array from max(low, mid – k) to min(mid + k, high) instead of low to high. The middle element is chosen as pivot for diving the array into almost 2 halves for a logarithmic time complexity. C++ Java #include <bits/stdc++.h>#include <iostream>using namespace std; int sort(vector<int>& array, int l, int h, int k){ int mid = l + (h - l) / 2; //Chose middle element as pivot int i = max(l, mid - k), j = i, end = min(mid + k, h); // Set appropriate range swap(array[mid], array[end]); //Swap middle and last element to avoid extra complications while (j < end) { if (array[j] < array[end]) { swap(array[i++], array[j]); } j = j + 1; } swap(array[end], array[i]); return i;} void ksorter(vector<int>& array, int l, int h, int k){ if (l < h) { int q = sort(array, l, h, k); ksorter(array, l, q - 1, k); ksorter(array, q + 1, h, k); }} int main(){ vector<int> array( { 3, 3, 2, 1, 6, 4, 4, 5, 9, 7, 8, 11, 12 }); int k = 3; cout << "Array before k sort\n"; for (int& num : array) cout << num << ' '; cout << endl; ksorter(array, 0, array.size() - 1, k); cout << "Array after k sort\n"; for (int& num : array) cout << num << ' '; return 0;} // Java program for above approachimport java.io.*;import java.util.*; class GFG{ public static int sort(ArrayList<Integer> arr,int l,int h,int k) { int mid = l + (h-l)/2; //choose middle element as pivot int i = Math.max(l,mid-k), j=i, end = Math.min(mid+k,h); //set appropriate ranges Collections.swap(arr,end,mid); //swap middle and last element to avoid extra complications while(j<end) { if(arr.get(j)<arr.get(end)) { Collections.swap(arr,j,i++); } j=j+1; } Collections.swap(arr,end,i); return i; } public static void ksorter(ArrayList<Integer> arr, int l,int h,int k) { if(l<h) { int q = sort(arr,l,h,k); ksorter(arr,l,q-1,k); ksorter(arr,q+1,h,k); } } // Driver Code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<>(List.of(3, 3, 2, 1, 6, 4, 4, 5, 9, 7, 8, 11, 12 )); int k = 3; int N = arr.size(); System.out.println("Array before k sort\n"); System.out.println(arr); System.out.println("\n"); ksorter(arr, 0, N - 1, k); System.out.println("Array after k sort\n"); System.out.println(arr); }}//this code is contributed by aditya942003patil Array before k sort 3 3 2 1 6 4 4 5 9 7 8 11 12 Array after k sort 1 2 3 3 4 4 5 6 7 8 9 11 12 Time Complexity: O(KLogN) Auxiliary Space: O(LogN) Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. prerna saini viratberi PranchalKatiyar aman neekhara jit_t manpreetsngh294 SakshayMahna divyeshrabadiya07 rahulas1505 itsok shivanisinghss2110 nishant3690 unknown2108 ninjackiee97 ekantchandrakar07 HatimLokhandwala ayushhhkhare adeebhs1 aditya942003patil cpp-priority-queue Insertion Sort Arrays Heap Sorting Arrays Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jul, 2022" }, { "code": null, "e": 330, "s": 54, "text": "Given an array of n elements, where each element is at most k away from its target position, devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array." }, { "code": null, "e": 341, "s": 330, "text": "Examples: " }, { "code": null, "e": 437, "s": 341, "text": "Input : arr[] = {6, 5, 3, 2, 8, 10, 9} k = 3 Output : arr[] = {2, 3, 5, 6, 8, 9, 10}" }, { "code": null, "e": 541, "s": 437, "text": "Input : arr[] = {10, 9, 8, 7, 4, 70, 60, 50} k = 4Output : arr[] = {4, 7, 8, 9, 10, 50, 60, 70}" }, { "code": null, "e": 656, "s": 541, "text": "We can use Insertion Sort to sort the elements efficiently. Following is the C code for standard Insertion Sort. " }, { "code": null, "e": 660, "s": 656, "text": "C++" }, { "code": null, "e": 662, "s": 660, "text": "C" }, { "code": null, "e": 667, "s": 662, "text": "Java" }, { "code": null, "e": 675, "s": 667, "text": "Python3" }, { "code": null, "e": 678, "s": 675, "text": "C#" }, { "code": null, "e": 689, "s": 678, "text": "Javascript" }, { "code": "/* Function to sort an array using insertion sort*/void insertionSort(int A[], int size){ int i, key, j; for(i = 1; i < size; i++) { key = A[i]; j = i - 1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j + 1] = A[j]; j = j - 1; } A[j + 1] = key; }} // This code is contributed by Shivani", "e": 1207, "s": 689, "text": null }, { "code": "/* Function to sort an array using insertion sort*/void insertionSort(int A[], int size){ int i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i-1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j+1] = A[j]; j = j-1; } A[j+1] = key; }}", "e": 1679, "s": 1207, "text": null }, { "code": "/* Function to sort an array using insertion sort*/static void insertionSort(int A[], int size){ int i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i-1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j+1] = A[j]; j = j-1; } A[j+1] = key; }}", "e": 2177, "s": 1679, "text": null }, { "code": "# Function to sort an array using# insertion sort def insertionSort(A, size): i, key, j = 0, 0, 0 for i in range(size): key = A[i] j = i-1 # Move elements of A[0..i-1], that are # greater than key, to one position # ahead of their current position. # This loop will run at most k times while j >= 0 and A[j] > key: A[j + 1] = A[j] j = j - 1 A[j + 1] = key", "e": 2618, "s": 2177, "text": null }, { "code": "/* C# Function to sort an array using insertion sort*/static void insertionSort(int A[], int size){ int i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i - 1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j + 1] = A[j]; j = j - 1; } A[j + 1] = key; }}", "e": 3107, "s": 2618, "text": null }, { "code": "/* Function to sort an array using insertion sort*/function insertionSort(A, size){ var i, key, j; for (i = 1; i < size; i++) { key = A[i]; j = i-1; /* Move elements of A[0..i-1], that are greater than key, to one position ahead of their current position. This loop will run at most k times */ while (j >= 0 && A[j] > key) { A[j+1] = A[j]; j = j-1; } A[j+1] = key; }} // This code is contributed by itsok.", "e": 3611, "s": 3107, "text": null }, { "code": null, "e": 3779, "s": 3611, "text": "Time Complexity: O(nk), The inner loop will run at most k times. To move every element to its correct place, at most k elements need to be moved. Auxiliary Space: O(1)" }, { "code": null, "e": 4372, "s": 3779, "text": "We can sort such arrays more efficiently with the help of Heap data structure. Following is the detailed process that uses Heap. 1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time (See this GFact). We are creating heap of size k as the element can be at most k distance from its index in a sorted array. 2) One by one remove min element from heap, put it in result array, and add a new element to heap from remaining elements.Removing an element and adding a new element to min heap will take log k time. So overall complexity will be O(k) + O((n-k) * log(k))." }, { "code": null, "e": 4376, "s": 4372, "text": "C++" }, { "code": null, "e": 4381, "s": 4376, "text": "Java" }, { "code": null, "e": 4389, "s": 4381, "text": "Python3" }, { "code": null, "e": 4392, "s": 4389, "text": "C#" }, { "code": null, "e": 4403, "s": 4392, "text": "Javascript" }, { "code": "// A STL based C++ program to sort a nearly sorted array.#include <bits/stdc++.h>using namespace std; // Given an array of size n, where every element// is k away from its target position, sorts the// array in O(n logk) time.void sortK(int arr[], int n, int k){ // Insert first k+1 items in a priority queue (or min // heap) //(A O(k) operation). We assume, k < n. //if size of array = k i.e k away from its target position //then int size; size=(n==k)?k:k+1; priority_queue<int, vector<int>, greater<int> > pq(arr, arr +size); // i is index for remaining elements in arr[] and index // is target index of for current minimum element in // Min Heap 'pq'. int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = pq.top(); pq.pop(); pq.push(arr[i]); } while (pq.empty() == false) { arr[index++] = pq.top(); pq.pop(); }} // A utility function to print array elementsvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} // Driver program to test above functionsint main(){ int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << \"Following is sorted array\" << endl; printArray(arr, n); return 0;}", "e": 5735, "s": 4403, "text": null }, { "code": "// A java program to sort a nearly sorted arrayimport java.util.Iterator;import java.util.PriorityQueue; class GFG { private static void kSort(int[] arr, int n, int k) { if (arr == null || arr.length == 0) { return; } // min heap PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); // if there are less than k + 1 elements present in the array int minCount = Math.min(arr.length, k + 1); // add first k + 1 items to the min heap for (int i = 0; i < minCount; i++) { priorityQueue.add(arr[i]); } int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = priorityQueue.peek(); priorityQueue.poll(); priorityQueue.add(arr[i]); } Iterator<Integer> itr = priorityQueue.iterator(); while (itr.hasNext()) { arr[index++] = priorityQueue.peek(); priorityQueue.poll(); } } // A utility function to print the array private static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); } // Driver Code public static void main(String[] args) { int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = arr.length; kSort(arr, n, k); System.out.println(\"Following is sorted array\"); printArray(arr, n); }} // This code is contributed by// Manpreet Singh(manpreetsngh294)", "e": 7234, "s": 5735, "text": null }, { "code": "# A Python3 program to sort a# nearly sorted array. from heapq import heappop, heappush, heapify # A utility function to print# array elementsdef print_array(arr: list): for elem in arr: print(elem, end=' ') # Given an array of size n, where every# element is k away from its target# position, sorts the array in O(nLogk) time. def sort_k(arr: list, n: int, k: int): \"\"\" :param arr: input array :param n: length of the array :param k: max distance, which every element is away from its target position. :return: None \"\"\" # List of first k+1 items heap = arr[:k + 1] # using heapify to convert list # into heap(or min heap) heapify(heap) # \"rem_elmnts_index\" is index for remaining # elements in arr and \"target_index\" is # target index of for current minimum element # in Min Heap \"heap\". target_index = 0 for rem_elmnts_index in range(k + 1, n): arr[target_index] = heappop(heap) heappush(heap, arr[rem_elmnts_index]) target_index += 1 while heap: arr[target_index] = heappop(heap) target_index += 1 # Driver Codek = 3arr = [2, 6, 3, 12, 56, 8]n = len(arr)sort_k(arr, n, k) print('Following is sorted array')print_array(arr) # This code is contributed by# Veerat Beri(viratberi)", "e": 8523, "s": 7234, "text": null }, { "code": "// A C# program to sort a nearly sorted arrayusing System;using System.Collections.Generic;class GFG { static void kSort(int[] arr, int n, int k) { // min heap List<int> priorityQueue = new List<int>(); // add first k + 1 items to the min heap for (int i = 0; i < k + 1; i++) { priorityQueue.Add(arr[i]); } priorityQueue.Sort(); int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = priorityQueue[0]; priorityQueue.RemoveAt(0); priorityQueue.Add(arr[i]); priorityQueue.Sort(); } int queue_size = priorityQueue.Count; for (int i = 0; i < queue_size; i++) { arr[index++] = priorityQueue[0]; priorityQueue.RemoveAt(0); } } // A utility function to print the array static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Driver code static void Main() { int k = 3; int[] arr = { 2, 6, 3, 12, 56, 8 }; int n = arr.Length; kSort(arr, n, k); Console.WriteLine(\"Following is sorted array\"); printArray(arr, n); }} // This code is contributed by divyeshrabadiya07.", "e": 9801, "s": 8523, "text": null }, { "code": "<script>// A javascript program to sort a nearly sorted array function kSort(arr,n,k){ let priorityQueue=[]; // add first k + 1 items to the min heap for (let i = 0; i < k + 1; i++) { priorityQueue.push(arr[i]); } priorityQueue.sort(function(a,b){return a-b;}); let index = 0; for (let i = k + 1; i < n; i++) { arr[index++] = priorityQueue[0]; priorityQueue.shift(); priorityQueue.push(arr[i]); priorityQueue.sort(function(a,b){return a-b;}); } while (priorityQueue.length != 0) { arr[index++] = priorityQueue[0]; priorityQueue.shift(); }} // A utility function to print the arrayfunction printArray(arr,n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Driver Codelet k = 3;let arr = [ 2, 6, 3, 12, 56, 8 ];let n = arr.length;kSort(arr, n, k);document.write(\"Following is sorted array<br>\");printArray(arr, n); // This code is contributed by unknown2108</script>", "e": 10849, "s": 9801, "text": null }, { "code": null, "e": 10890, "s": 10849, "text": "Following is sorted array\n2 3 6 8 12 56 " }, { "code": null, "e": 10970, "s": 10890, "text": "Time Complexity: O(k) + O((m) * log(k)) , where m = n – kAuxiliary Space: O(k)" }, { "code": null, "e": 11355, "s": 10970, "text": "We can also use a Balanced Binary Search Tree instead of Heap to store k+1 elements. The insert and delete operations on Balanced BST also take O(log k) time. So Balanced BST based method will also take O(n log k) time, but the Heap based method seems to be more efficient as the minimum element will always be at root. Also, Heap doesn’t need extra space for left and right pointers." }, { "code": null, "e": 11568, "s": 11355, "text": "The previous algorithm is good the time and space complexity can be improved with a variation of Quick Sort algorithm. If you aren’t familiar with quicksort take a look at it before reading through this solution." }, { "code": null, "e": 11644, "s": 11568, "text": "The algorithm uses quick sort but changes the partition function in 2 ways." }, { "code": null, "e": 11810, "s": 11644, "text": "Selects pivot element as the middle element instead of the first or last element.Scans the array from max(low, mid – k) to min(mid + k, high) instead of low to high." }, { "code": null, "e": 11892, "s": 11810, "text": "Selects pivot element as the middle element instead of the first or last element." }, { "code": null, "e": 11977, "s": 11892, "text": "Scans the array from max(low, mid – k) to min(mid + k, high) instead of low to high." }, { "code": null, "e": 12092, "s": 11977, "text": "The middle element is chosen as pivot for diving the array into almost 2 halves for a logarithmic time complexity." }, { "code": null, "e": 12096, "s": 12092, "text": "C++" }, { "code": null, "e": 12101, "s": 12096, "text": "Java" }, { "code": "#include <bits/stdc++.h>#include <iostream>using namespace std; int sort(vector<int>& array, int l, int h, int k){ int mid = l + (h - l) / 2; //Chose middle element as pivot int i = max(l, mid - k), j = i, end = min(mid + k, h); // Set appropriate range swap(array[mid], array[end]); //Swap middle and last element to avoid extra complications while (j < end) { if (array[j] < array[end]) { swap(array[i++], array[j]); } j = j + 1; } swap(array[end], array[i]); return i;} void ksorter(vector<int>& array, int l, int h, int k){ if (l < h) { int q = sort(array, l, h, k); ksorter(array, l, q - 1, k); ksorter(array, q + 1, h, k); }} int main(){ vector<int> array( { 3, 3, 2, 1, 6, 4, 4, 5, 9, 7, 8, 11, 12 }); int k = 3; cout << \"Array before k sort\\n\"; for (int& num : array) cout << num << ' '; cout << endl; ksorter(array, 0, array.size() - 1, k); cout << \"Array after k sort\\n\"; for (int& num : array) cout << num << ' '; return 0;}", "e": 13165, "s": 12101, "text": null }, { "code": "// Java program for above approachimport java.io.*;import java.util.*; class GFG{ public static int sort(ArrayList<Integer> arr,int l,int h,int k) { int mid = l + (h-l)/2; //choose middle element as pivot int i = Math.max(l,mid-k), j=i, end = Math.min(mid+k,h); //set appropriate ranges Collections.swap(arr,end,mid); //swap middle and last element to avoid extra complications while(j<end) { if(arr.get(j)<arr.get(end)) { Collections.swap(arr,j,i++); } j=j+1; } Collections.swap(arr,end,i); return i; } public static void ksorter(ArrayList<Integer> arr, int l,int h,int k) { if(l<h) { int q = sort(arr,l,h,k); ksorter(arr,l,q-1,k); ksorter(arr,q+1,h,k); } } // Driver Code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<>(List.of(3, 3, 2, 1, 6, 4, 4, 5, 9, 7, 8, 11, 12 )); int k = 3; int N = arr.size(); System.out.println(\"Array before k sort\\n\"); System.out.println(arr); System.out.println(\"\\n\"); ksorter(arr, 0, N - 1, k); System.out.println(\"Array after k sort\\n\"); System.out.println(arr); }}//this code is contributed by aditya942003patil", "e": 14403, "s": 13165, "text": null }, { "code": null, "e": 14500, "s": 14403, "text": "Array before k sort\n3 3 2 1 6 4 4 5 9 7 8 11 12 \nArray after k sort\n1 2 3 3 4 4 5 6 7 8 9 11 12 " }, { "code": null, "e": 14551, "s": 14500, "text": "Time Complexity: O(KLogN) Auxiliary Space: O(LogN)" }, { "code": null, "e": 14677, "s": 14551, "text": "Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 14690, "s": 14677, "text": "prerna saini" }, { "code": null, "e": 14700, "s": 14690, "text": "viratberi" }, { "code": null, "e": 14716, "s": 14700, "text": "PranchalKatiyar" }, { "code": null, "e": 14730, "s": 14716, "text": "aman neekhara" }, { "code": null, "e": 14736, "s": 14730, "text": "jit_t" }, { "code": null, "e": 14752, "s": 14736, "text": "manpreetsngh294" }, { "code": null, "e": 14765, "s": 14752, "text": "SakshayMahna" }, { "code": null, "e": 14783, "s": 14765, "text": "divyeshrabadiya07" }, { "code": null, "e": 14795, "s": 14783, "text": "rahulas1505" }, { "code": null, "e": 14801, "s": 14795, "text": "itsok" }, { "code": null, "e": 14820, "s": 14801, "text": "shivanisinghss2110" }, { "code": null, "e": 14832, "s": 14820, "text": "nishant3690" }, { "code": null, "e": 14844, "s": 14832, "text": "unknown2108" }, { "code": null, "e": 14857, "s": 14844, "text": "ninjackiee97" }, { "code": null, "e": 14875, "s": 14857, "text": "ekantchandrakar07" }, { "code": null, "e": 14892, "s": 14875, "text": "HatimLokhandwala" }, { "code": null, "e": 14905, "s": 14892, "text": "ayushhhkhare" }, { "code": null, "e": 14914, "s": 14905, "text": "adeebhs1" }, { "code": null, "e": 14932, "s": 14914, "text": "aditya942003patil" }, { "code": null, "e": 14951, "s": 14932, "text": "cpp-priority-queue" }, { "code": null, "e": 14966, "s": 14951, "text": "Insertion Sort" }, { "code": null, "e": 14973, "s": 14966, "text": "Arrays" }, { "code": null, "e": 14978, "s": 14973, "text": "Heap" }, { "code": null, "e": 14986, "s": 14978, "text": "Sorting" }, { "code": null, "e": 14993, "s": 14986, "text": "Arrays" }, { "code": null, "e": 15001, "s": 14993, "text": "Sorting" }, { "code": null, "e": 15006, "s": 15001, "text": "Heap" } ]
Scala Set exists() method with example
18 Oct, 2019 The exists() method is utilized to test whether a predicate holds for some of the elements of the set or not. Method Definition: def exists(p: (A) => Boolean): Boolean Return Type: It returns true if the stated predicate holds true for some elements of the set else it returns false. Example #1: // Scala program of exists() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a list val s1 = Set(1, 2, 3, 4, 5) // Applying exists method val result = s1.exists(y => {y % 3 == 0}) // Displays output println(result) } } true Example #2: // Scala program of exists() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a list val s1 = Set(1, 2, 3, 4, 5) // Applying exists method val result = s1.exists(y => {y % 7 == 0}) // Displays output println(result) } } false Scala scala-collection Scala-Method Scala-Set Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2019" }, { "code": null, "e": 138, "s": 28, "text": "The exists() method is utilized to test whether a predicate holds for some of the elements of the set or not." }, { "code": null, "e": 196, "s": 138, "text": "Method Definition: def exists(p: (A) => Boolean): Boolean" }, { "code": null, "e": 312, "s": 196, "text": "Return Type: It returns true if the stated predicate holds true for some elements of the set else it returns false." }, { "code": null, "e": 324, "s": 312, "text": "Example #1:" }, { "code": "// Scala program of exists() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a list val s1 = Set(1, 2, 3, 4, 5) // Applying exists method val result = s1.exists(y => {y % 3 == 0}) // Displays output println(result) } } ", "e": 694, "s": 324, "text": null }, { "code": null, "e": 700, "s": 694, "text": "true\n" }, { "code": null, "e": 712, "s": 700, "text": "Example #2:" }, { "code": "// Scala program of exists() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a list val s1 = Set(1, 2, 3, 4, 5) // Applying exists method val result = s1.exists(y => {y % 7 == 0}) // Displays output println(result) } } ", "e": 1082, "s": 712, "text": null }, { "code": null, "e": 1089, "s": 1082, "text": "false\n" }, { "code": null, "e": 1095, "s": 1089, "text": "Scala" }, { "code": null, "e": 1112, "s": 1095, "text": "scala-collection" }, { "code": null, "e": 1125, "s": 1112, "text": "Scala-Method" }, { "code": null, "e": 1135, "s": 1125, "text": "Scala-Set" }, { "code": null, "e": 1141, "s": 1135, "text": "Scala" } ]
Slowloris DDOS Attack Tool in Kali Linux
28 Mar, 2021 Slowloris is a free and Open source tool available on Github. We can perform a denial of service attack using this tool. It’s a framework written in python. This tool allows a single machine to take down another machine’s web server it uses perfectly legitimate HTTP traffic. It makes a full TCP connection and then requires only a few hundred requests at long-term and regular intervals. As a result, the tool doesn’t need to spend a lot of traffic to exhaust the available connections on a server. Slowloris sends multiple requests to the target as a result generates heavy traffic botnets. Slowloris can be used to perform ddos attacks on any webserver. It is an open-source tool, so you can download it from github free of cost. It uses perfectly legitimate HTTP traffic. Deniel of service attack can be executed with the help of Slowloris by generating heavy traffic of botnets. Step 1: Open your Kali Linux and then Open your Terminal. Step 2: Create a new Directory on Desktop named Slowloris using the following command. mkdir Slowloris Step 3: Move to the directory that you have to create (Slowloris). cd Slowloris Step 4: Now you have to clone the Slowloris tool from Github so that you can install it on your Kali Linux machine. For that, you only have to type the following URL in your terminal within Slowloris directory that you have created. git clone https://github.com/gkbrk/slowloris.git You have successfully installed Slowloris tool in your Kali Linux. Now it’s time to perform a denial of service using the following steps. Step 5: Now go to the Action bar and click on split terminal vertically then you will see that the two-terminal screen has been open now. Step 6: Now you have to check the IP address of your machine to do that type following command. ifconfig Step 7: As you can see we got our IP address now it’s time to start the apache server, to start the apache server using the following command. sudo service apache 2 start Step 8: Now we have to check the status of your server whether it is active or not so to check the status of your server run the following command. service apache2 status Step 9: We can see that our server is under active status it means is running properly, now come back to the first terminal, and to check permissions run the following command. ls -l Step 10: Now it’s time to run the tool using the following command. python3 slowloris .py (your ip address) -s 500 Step 11: You can see the tool has started attacking on that particular IP address which we have given now to check whether its working or not go to your browser and on your URL bar type that IP address, and you will see the site is only loading and loading but not opening this is how Slowloris tool works. As you can see here the browser is waiting for an IP address because the browser is not able to load the page, this is because the denial of service attack is happening behind the browser using slowloris tool if you want to attack the live website you can attack using the domain name of that website instead of giving the IP address of the system to the slowloris tool. Slowloris tool will start attacking that particular domain however it’s a crime, and we do not promote such type of activity the tutorial was only for education purposes. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples 'crontab' in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples TCP Server-Client implementation in C Docker - COPY Instruction UDP Server-Client implementation in C
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Mar, 2021" }, { "code": null, "e": 553, "s": 52, "text": "Slowloris is a free and Open source tool available on Github. We can perform a denial of service attack using this tool. It’s a framework written in python. This tool allows a single machine to take down another machine’s web server it uses perfectly legitimate HTTP traffic. It makes a full TCP connection and then requires only a few hundred requests at long-term and regular intervals. As a result, the tool doesn’t need to spend a lot of traffic to exhaust the available connections on a server. " }, { "code": null, "e": 646, "s": 553, "text": "Slowloris sends multiple requests to the target as a result generates heavy traffic botnets." }, { "code": null, "e": 710, "s": 646, "text": "Slowloris can be used to perform ddos attacks on any webserver." }, { "code": null, "e": 786, "s": 710, "text": "It is an open-source tool, so you can download it from github free of cost." }, { "code": null, "e": 829, "s": 786, "text": "It uses perfectly legitimate HTTP traffic." }, { "code": null, "e": 937, "s": 829, "text": "Deniel of service attack can be executed with the help of Slowloris by generating heavy traffic of botnets." }, { "code": null, "e": 995, "s": 937, "text": "Step 1: Open your Kali Linux and then Open your Terminal." }, { "code": null, "e": 1082, "s": 995, "text": "Step 2: Create a new Directory on Desktop named Slowloris using the following command." }, { "code": null, "e": 1098, "s": 1082, "text": "mkdir Slowloris" }, { "code": null, "e": 1165, "s": 1098, "text": "Step 3: Move to the directory that you have to create (Slowloris)." }, { "code": null, "e": 1178, "s": 1165, "text": "cd Slowloris" }, { "code": null, "e": 1411, "s": 1178, "text": "Step 4: Now you have to clone the Slowloris tool from Github so that you can install it on your Kali Linux machine. For that, you only have to type the following URL in your terminal within Slowloris directory that you have created." }, { "code": null, "e": 1460, "s": 1411, "text": "git clone https://github.com/gkbrk/slowloris.git" }, { "code": null, "e": 1599, "s": 1460, "text": "You have successfully installed Slowloris tool in your Kali Linux. Now it’s time to perform a denial of service using the following steps." }, { "code": null, "e": 1737, "s": 1599, "text": "Step 5: Now go to the Action bar and click on split terminal vertically then you will see that the two-terminal screen has been open now." }, { "code": null, "e": 1833, "s": 1737, "text": "Step 6: Now you have to check the IP address of your machine to do that type following command." }, { "code": null, "e": 1842, "s": 1833, "text": "ifconfig" }, { "code": null, "e": 1985, "s": 1842, "text": "Step 7: As you can see we got our IP address now it’s time to start the apache server, to start the apache server using the following command." }, { "code": null, "e": 2013, "s": 1985, "text": "sudo service apache 2 start" }, { "code": null, "e": 2161, "s": 2013, "text": "Step 8: Now we have to check the status of your server whether it is active or not so to check the status of your server run the following command." }, { "code": null, "e": 2184, "s": 2161, "text": "service apache2 status" }, { "code": null, "e": 2361, "s": 2184, "text": "Step 9: We can see that our server is under active status it means is running properly, now come back to the first terminal, and to check permissions run the following command." }, { "code": null, "e": 2367, "s": 2361, "text": "ls -l" }, { "code": null, "e": 2435, "s": 2367, "text": "Step 10: Now it’s time to run the tool using the following command." }, { "code": null, "e": 2482, "s": 2435, "text": "python3 slowloris .py (your ip address) -s 500" }, { "code": null, "e": 2789, "s": 2482, "text": "Step 11: You can see the tool has started attacking on that particular IP address which we have given now to check whether its working or not go to your browser and on your URL bar type that IP address, and you will see the site is only loading and loading but not opening this is how Slowloris tool works." }, { "code": null, "e": 3331, "s": 2789, "text": "As you can see here the browser is waiting for an IP address because the browser is not able to load the page, this is because the denial of service attack is happening behind the browser using slowloris tool if you want to attack the live website you can attack using the domain name of that website instead of giving the IP address of the system to the slowloris tool. Slowloris tool will start attacking that particular domain however it’s a crime, and we do not promote such type of activity the tutorial was only for education purposes." }, { "code": null, "e": 3342, "s": 3331, "text": "Kali-Linux" }, { "code": null, "e": 3354, "s": 3342, "text": "Linux-Tools" }, { "code": null, "e": 3365, "s": 3354, "text": "Linux-Unix" }, { "code": null, "e": 3463, "s": 3365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3498, "s": 3463, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 3533, "s": 3498, "text": "tar command in Linux with examples" }, { "code": null, "e": 3569, "s": 3533, "text": "curl command in Linux with Examples" }, { "code": null, "e": 3610, "s": 3569, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 3643, "s": 3610, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 3681, "s": 3643, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 3717, "s": 3681, "text": "Tail command in Linux with examples" }, { "code": null, "e": 3755, "s": 3717, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3781, "s": 3755, "text": "Docker - COPY Instruction" } ]
How to replace missing values with median in an R data frame column?
To replace missing values with median, we can use the same trick that is used to replace missing values with mean. For example, if we have a data frame df that contain columns x and y where both of the columns contains some missing values then the missing values can be replaced with median as dfx[is.na(dfx)]<-median(dfx,na.rm=TRUE)forxandforywecandothesameasdfy[is.na(dfy)]<−median(dfy,na.rm=TRUE). Live Demo Consider the below data frame − set.seed(1112) x1<-LETTERS[1:20] x2<-sample(c(NA,rpois(19,8)),20,replace=TRUE) df1<-data.frame(x1,x2) df1 x1 x2 1 A 10 2 B 11 3 C 8 4 D 6 5 E 6 6 F NA 7 G 10 8 H 8 9 I 8 10 J 7 11 K NA 12 L 12 13 M 7 14 N 6 15 O 10 16 P 7 17 Q 7 18 R 8 19 S 11 20 T 4 median(df1$x2) [1] 8 Replacing missing values in x2 with median of the remaining values − df1$x2[is.na(df1$x2)]<-median(df1$x2,na.rm=TRUE) df1 x1 x2 1 A 10 2 B 11 3 C 8 4 D 6 5 E 6 6 F 8 7 G 10 8 H 8 9 I 8 10 J 7 11 K 8 12 L 12 13 M 7 14 N 6 15 O 10 16 P 7 17 Q 7 18 R 8 19 S 11 20 T 4 Let’s have a look at another example − ID<-1:20 Ratings<-sample(c(NA,1,2,3,4,5),20,replace=TRUE) df2<-data.frame(ID,Ratings) df2 ID Ratings 1 1 3 2 2 1 3 3 1 4 4 4 5 5 1 6 6 4 7 7 2 8 8 3 9 9 2 10 10 2 11 11 3 12 12 5 13 13 5 14 14 1 15 15 4 16 16 1 17 17 4 18 18 NA 19 19 1 20 20 NA median(df2$Ratings,na.rm=TRUE) [1] 2.5 Replacing missing values in Ratings with median of the remaining values − df2$Ratings[is.na(df2$Ratings)]<-median(df2$Ratings,na.rm=TRUE) df2 ID Ratings 1 1 3.0 2 2 1.0 3 3 1.0 4 4 4.0 5 5 1.0 6 6 4.0 7 7 2.0 8 8 3.0 9 9 2.0 10 10 2.0 11 11 3.0 12 12 5.0 13 13 5.0 14 14 1.0 15 15 4.0 16 16 1.0 17 17 4.0 18 18 2.5 19 19 1.0 20 20 2.5
[ { "code": null, "e": 1588, "s": 1187, "text": "To replace missing values with median, we can use the same trick that is used to replace missing values with mean. For example, if we have a data frame df that contain columns x and y where both of the columns contains some missing values then the missing values can be replaced with median as dfx[is.na(dfx)]<-median(dfx,na.rm=TRUE)forxandforywecandothesameasdfy[is.na(dfy)]<−median(dfy,na.rm=TRUE)." }, { "code": null, "e": 1599, "s": 1588, "text": " Live Demo" }, { "code": null, "e": 1631, "s": 1599, "text": "Consider the below data frame −" }, { "code": null, "e": 1737, "s": 1631, "text": "set.seed(1112)\nx1<-LETTERS[1:20]\nx2<-sample(c(NA,rpois(19,8)),20,replace=TRUE)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 1904, "s": 1737, "text": " x1 x2\n1 A 10\n2 B 11\n3 C 8\n4 D 6\n5 E 6\n6 F NA\n7 G 10\n8 H 8\n9 I 8\n10 J 7\n11 K NA\n12 L 12\n13 M 7\n14 N 6\n15 O 10\n16 P 7\n17 Q 7\n18 R 8\n19 S 11\n20 T 4\nmedian(df1$x2)\n[1] 8" }, { "code": null, "e": 1973, "s": 1904, "text": "Replacing missing values in x2 with median of the remaining values −" }, { "code": null, "e": 2026, "s": 1973, "text": "df1$x2[is.na(df1$x2)]<-median(df1$x2,na.rm=TRUE)\ndf1" }, { "code": null, "e": 2169, "s": 2026, "text": "x1 x2\n1 A 10\n2 B 11\n3 C 8\n4 D 6\n5 E 6\n6 F 8\n7 G 10\n8 H 8\n9 I 8\n10 J 7\n11 K 8\n12 L 12\n13 M 7\n14 N 6\n15 O 10\n16 P 7\n17 Q 7\n18 R 8\n19 S 11\n20 T 4" }, { "code": null, "e": 2208, "s": 2169, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2298, "s": 2208, "text": "ID<-1:20 Ratings<-sample(c(NA,1,2,3,4,5),20,replace=TRUE) df2<-data.frame(ID,Ratings) df2" }, { "code": null, "e": 2492, "s": 2298, "text": "ID Ratings\n1 1 3\n2 2 1\n3 3 1\n4 4 4\n5 5 1\n6 6 4\n7 7 2\n8 8 3\n9 9 2\n10 10 2\n11 11 3\n12 12 5\n13 13 5\n14 14 1\n15 15 4\n16 16 1\n17 17 4\n18 18 NA\n19 19 1\n20 20 NA\nmedian(df2$Ratings,na.rm=TRUE)\n[1] 2.5" }, { "code": null, "e": 2566, "s": 2492, "text": "Replacing missing values in Ratings with median of the remaining values −" }, { "code": null, "e": 2634, "s": 2566, "text": "df2$Ratings[is.na(df2$Ratings)]<-median(df2$Ratings,na.rm=TRUE)\ndf2" }, { "code": null, "e": 2827, "s": 2634, "text": "ID Ratings\n1 1 3.0\n2 2 1.0\n3 3 1.0\n4 4 4.0\n5 5 1.0\n6 6 4.0\n7 7 2.0\n8 8 3.0\n9 9 2.0\n10 10 2.0\n11 11 3.0\n12 12 5.0\n13 13 5.0\n14 14 1.0\n15 15 4.0\n16 16 1.0\n17 17 4.0\n18 18 2.5\n19 19 1.0\n20 20 2.5" } ]
Construct a graph from given degrees of all vertices
09 Jul, 2021 This is a C++ program to generate a graph for a given fixed degree sequence. This algorithm generates a undirected graph for the given degree sequence.It does not include self-edge and multiple edges.Examples: Input : degrees[] = {2, 2, 1, 1} Output : (0) (1) (2) (3) (0) 0 1 1 0 (1) 1 0 0 1 (2) 1 0 0 0 (3) 0 1 0 0 Explanation : We are given that there are four vertices with degree of vertex 0 as 2, degree of vertex 1 as 2, degree of vertex 2 as 1 and degree of vertex 3 as 1. Following is graph that follows given conditions. (0)----------(1) | | | | | | (2) (3) Approach : 1- Take the input of the number of vertexes and their corresponding degree. 2- Declare adjacency matrix, mat[ ][ ] to store the graph. 3- To create the graph, create the first loop to connect each vertex ‘i’. 4- Second nested loop to connect the vertex ‘i’ to the every valid vertex ‘j’, next to it. 5- If the degree of vertex ‘i’ and ‘j’ are more than zero then connect them. 6- Print the adjacency matrix.Based on the above explanation, below are implementations: C++ Java Python3 C# Javascript // C++ program to generate a graph for a// given fixed degrees#include <bits/stdc++.h>using namespace std; // A function to print the adjacency matrix.void printMat(int degseq[], int n){ // n is number of vertices int mat[n][n]; memset(mat, 0, sizeof(mat)); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i][j] = 1; mat[j][i] = 1; } } } // Print the result in specified format cout << "\n" << setw(3) << " "; for (int i = 0; i < n; i++) cout << setw(3) << "(" << i << ")"; cout << "\n\n"; for (int i = 0; i < n; i++) { cout << setw(4) << "(" << i << ")"; for (int j = 0; j < n; j++) cout << setw(5) << mat[i][j]; cout << "\n"; }} // driver program to test above functionint main(){ int degseq[] = { 2, 2, 1, 1, 1 }; int n = sizeof(degseq) / sizeof(degseq[0]); printMat(degseq, n); return 0;} // Java program to generate a graph for a// given fixed degreesimport java.util.*; class GFG{ // A function to print the adjacency matrix.static void printMat(int degseq[], int n){ // n is number of vertices int [][]mat = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i][j] = 1; mat[j][i] = 1; } } } // Print the result in specified format System.out.print("\n" + setw(3) + " "); for (int i = 0; i < n; i++) System.out.print(setw(3) + "(" + i + ")"); System.out.print("\n\n"); for (int i = 0; i < n; i++) { System.out.print(setw(4) + "(" + i + ")"); for (int j = 0; j < n; j++) System.out.print(setw(5) + mat[i][j]); System.out.print("\n"); }} static String setw(int n){ String space = ""; while(n-- > 0) space += " "; return space;} // Driver Codepublic static void main(String[] args){ int degseq[] = { 2, 2, 1, 1, 1 }; int n = degseq.length; printMat(degseq, n);}} // This code is contributed by 29AjayKumar # Python3 program to generate a graph# for a given fixed degrees # A function to print the adjacency matrix.def printMat(degseq, n): # n is number of vertices mat = [[0] * n for i in range(n)] for i in range(n): for j in range(i + 1, n): # For each pair of vertex decrement # the degree of both vertex. if (degseq[i] > 0 and degseq[j] > 0): degseq[i] -= 1 degseq[j] -= 1 mat[i][j] = 1 mat[j][i] = 1 # Print the result in specified form print(" ", end = " ") for i in range(n): print(" ", "(", i, ")", end = "") print() print() for i in range(n): print(" ", "(", i, ")", end = "") for j in range(n): print(" ", mat[i][j], end = "") print() # Driver Codeif __name__ == '__main__': degseq = [2, 2, 1, 1, 1] n = len(degseq) printMat(degseq, n) # This code is contributed by PranchalK // C# program to generate a graph for a// given fixed degreesusing System; class GFG{ // A function to print the adjacency matrix.static void printMat(int []degseq, int n){ // n is number of vertices int [,]mat = new int[n, n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i, j] = 1; mat[j, i] = 1; } } } // Print the result in specified format Console.Write("\n" + setw(3) + " "); for (int i = 0; i < n; i++) Console.Write(setw(3) + "(" + i + ")"); Console.Write("\n\n"); for (int i = 0; i < n; i++) { Console.Write(setw(4) + "(" + i + ")"); for (int j = 0; j < n; j++) Console.Write(setw(5) + mat[i, j]); Console.Write("\n"); }} static String setw(int n){ String space = ""; while(n-- > 0) space += " "; return space;} // Driver Codepublic static void Main(String[] args){ int []degseq = { 2, 2, 1, 1, 1 }; int n = degseq.Length; printMat(degseq, n);}} // This code is contributed by Princi Singh <script> // JavaScript program to generate a graph for a// given fixed degrees // A function to print the adjacency matrix.function printMat(degseq,n){ // n is number of vertices let mat = new Array(n); for(let i=0;i<n;i++) { mat[i]=new Array(n); for(let j=0;j<n;j++) mat[i][j]=0; } for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i][j] = 1; mat[j][i] = 1; } } } // Print the result in specified format document.write("<br>" + setw(3) + " "); for (let i = 0; i < n; i++) document.write(setw(3) + "(" + i + ")"); document.write("<br><br>"); for (let i = 0; i < n; i++) { document.write(setw(4) + "(" + i + ")"); for (let j = 0; j < n; j++) document.write(setw(5) + mat[i][j]); document.write("<br>"); }} function setw(n){ let space = ""; while(n-- > 0) space += " "; return space;} // Driver Codelet degseq=[2, 2, 1, 1, 1];let n = degseq.length;printMat(degseq, n); // This code is contributed by rag2127 </script> Output: (0) (1) (2) (3) (4) (0) 0 1 1 0 0 (1) 1 0 0 1 0 (2) 1 0 0 0 0 (3) 0 1 0 0 0 (4) 0 0 0 0 0 Time Complexity: O(v*v). PranchalKatiyar 29AjayKumar princi singh nidhi_biet rag2127 Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Minimum number of swaps required to sort an array m Coloring Problem | Backtracking-5
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jul, 2021" }, { "code": null, "e": 266, "s": 54, "text": "This is a C++ program to generate a graph for a given fixed degree sequence. This algorithm generates a undirected graph for the given degree sequence.It does not include self-edge and multiple edges.Examples: " }, { "code": null, "e": 855, "s": 266, "text": "Input : degrees[] = {2, 2, 1, 1}\nOutput : (0) (1) (2) (3)\n (0) 0 1 1 0 \n (1) 1 0 0 1 \n (2) 1 0 0 0 \n (3) 0 1 0 0 \nExplanation : We are given that there\nare four vertices with degree of vertex\n0 as 2, degree of vertex 1 as 2, degree\nof vertex 2 as 1 and degree of vertex 3\nas 1. Following is graph that follows\ngiven conditions. \n (0)----------(1)\n | | \n | | \n | |\n (2) (3) " }, { "code": null, "e": 1335, "s": 857, "text": "Approach : 1- Take the input of the number of vertexes and their corresponding degree. 2- Declare adjacency matrix, mat[ ][ ] to store the graph. 3- To create the graph, create the first loop to connect each vertex ‘i’. 4- Second nested loop to connect the vertex ‘i’ to the every valid vertex ‘j’, next to it. 5- If the degree of vertex ‘i’ and ‘j’ are more than zero then connect them. 6- Print the adjacency matrix.Based on the above explanation, below are implementations: " }, { "code": null, "e": 1339, "s": 1335, "text": "C++" }, { "code": null, "e": 1344, "s": 1339, "text": "Java" }, { "code": null, "e": 1352, "s": 1344, "text": "Python3" }, { "code": null, "e": 1355, "s": 1352, "text": "C#" }, { "code": null, "e": 1366, "s": 1355, "text": "Javascript" }, { "code": "// C++ program to generate a graph for a// given fixed degrees#include <bits/stdc++.h>using namespace std; // A function to print the adjacency matrix.void printMat(int degseq[], int n){ // n is number of vertices int mat[n][n]; memset(mat, 0, sizeof(mat)); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i][j] = 1; mat[j][i] = 1; } } } // Print the result in specified format cout << \"\\n\" << setw(3) << \" \"; for (int i = 0; i < n; i++) cout << setw(3) << \"(\" << i << \")\"; cout << \"\\n\\n\"; for (int i = 0; i < n; i++) { cout << setw(4) << \"(\" << i << \")\"; for (int j = 0; j < n; j++) cout << setw(5) << mat[i][j]; cout << \"\\n\"; }} // driver program to test above functionint main(){ int degseq[] = { 2, 2, 1, 1, 1 }; int n = sizeof(degseq) / sizeof(degseq[0]); printMat(degseq, n); return 0;}", "e": 2527, "s": 1366, "text": null }, { "code": "// Java program to generate a graph for a// given fixed degreesimport java.util.*; class GFG{ // A function to print the adjacency matrix.static void printMat(int degseq[], int n){ // n is number of vertices int [][]mat = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i][j] = 1; mat[j][i] = 1; } } } // Print the result in specified format System.out.print(\"\\n\" + setw(3) + \" \"); for (int i = 0; i < n; i++) System.out.print(setw(3) + \"(\" + i + \")\"); System.out.print(\"\\n\\n\"); for (int i = 0; i < n; i++) { System.out.print(setw(4) + \"(\" + i + \")\"); for (int j = 0; j < n; j++) System.out.print(setw(5) + mat[i][j]); System.out.print(\"\\n\"); }} static String setw(int n){ String space = \"\"; while(n-- > 0) space += \" \"; return space;} // Driver Codepublic static void main(String[] args){ int degseq[] = { 2, 2, 1, 1, 1 }; int n = degseq.length; printMat(degseq, n);}} // This code is contributed by 29AjayKumar", "e": 3863, "s": 2527, "text": null }, { "code": "# Python3 program to generate a graph# for a given fixed degrees # A function to print the adjacency matrix.def printMat(degseq, n): # n is number of vertices mat = [[0] * n for i in range(n)] for i in range(n): for j in range(i + 1, n): # For each pair of vertex decrement # the degree of both vertex. if (degseq[i] > 0 and degseq[j] > 0): degseq[i] -= 1 degseq[j] -= 1 mat[i][j] = 1 mat[j][i] = 1 # Print the result in specified form print(\" \", end = \" \") for i in range(n): print(\" \", \"(\", i, \")\", end = \"\") print() print() for i in range(n): print(\" \", \"(\", i, \")\", end = \"\") for j in range(n): print(\" \", mat[i][j], end = \"\") print() # Driver Codeif __name__ == '__main__': degseq = [2, 2, 1, 1, 1] n = len(degseq) printMat(degseq, n) # This code is contributed by PranchalK", "e": 4835, "s": 3863, "text": null }, { "code": "// C# program to generate a graph for a// given fixed degreesusing System; class GFG{ // A function to print the adjacency matrix.static void printMat(int []degseq, int n){ // n is number of vertices int [,]mat = new int[n, n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i, j] = 1; mat[j, i] = 1; } } } // Print the result in specified format Console.Write(\"\\n\" + setw(3) + \" \"); for (int i = 0; i < n; i++) Console.Write(setw(3) + \"(\" + i + \")\"); Console.Write(\"\\n\\n\"); for (int i = 0; i < n; i++) { Console.Write(setw(4) + \"(\" + i + \")\"); for (int j = 0; j < n; j++) Console.Write(setw(5) + mat[i, j]); Console.Write(\"\\n\"); }} static String setw(int n){ String space = \"\"; while(n-- > 0) space += \" \"; return space;} // Driver Codepublic static void Main(String[] args){ int []degseq = { 2, 2, 1, 1, 1 }; int n = degseq.Length; printMat(degseq, n);}} // This code is contributed by Princi Singh", "e": 6149, "s": 4835, "text": null }, { "code": "<script> // JavaScript program to generate a graph for a// given fixed degrees // A function to print the adjacency matrix.function printMat(degseq,n){ // n is number of vertices let mat = new Array(n); for(let i=0;i<n;i++) { mat[i]=new Array(n); for(let j=0;j<n;j++) mat[i][j]=0; } for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { // For each pair of vertex decrement // the degree of both vertex. if (degseq[i] > 0 && degseq[j] > 0) { degseq[i]--; degseq[j]--; mat[i][j] = 1; mat[j][i] = 1; } } } // Print the result in specified format document.write(\"<br>\" + setw(3) + \" \"); for (let i = 0; i < n; i++) document.write(setw(3) + \"(\" + i + \")\"); document.write(\"<br><br>\"); for (let i = 0; i < n; i++) { document.write(setw(4) + \"(\" + i + \")\"); for (let j = 0; j < n; j++) document.write(setw(5) + mat[i][j]); document.write(\"<br>\"); }} function setw(n){ let space = \"\"; while(n-- > 0) space += \" \"; return space;} // Driver Codelet degseq=[2, 2, 1, 1, 1];let n = degseq.length;printMat(degseq, n); // This code is contributed by rag2127 </script>", "e": 7506, "s": 6149, "text": null }, { "code": null, "e": 7516, "s": 7506, "text": "Output: " }, { "code": null, "e": 7709, "s": 7516, "text": " (0) (1) (2) (3) (4)\n\n (0) 0 1 1 0 0\n (1) 1 0 0 1 0\n (2) 1 0 0 0 0\n (3) 0 1 0 0 0\n (4) 0 0 0 0 0" }, { "code": null, "e": 7735, "s": 7709, "text": "Time Complexity: O(v*v). " }, { "code": null, "e": 7751, "s": 7735, "text": "PranchalKatiyar" }, { "code": null, "e": 7763, "s": 7751, "text": "29AjayKumar" }, { "code": null, "e": 7776, "s": 7763, "text": "princi singh" }, { "code": null, "e": 7787, "s": 7776, "text": "nidhi_biet" }, { "code": null, "e": 7795, "s": 7787, "text": "rag2127" }, { "code": null, "e": 7801, "s": 7795, "text": "Graph" }, { "code": null, "e": 7807, "s": 7801, "text": "Graph" }, { "code": null, "e": 7905, "s": 7807, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7956, "s": 7905, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 8021, "s": 7956, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 8079, "s": 8021, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 8112, "s": 8079, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 8144, "s": 8112, "text": "Introduction to Data Structures" }, { "code": null, "e": 8212, "s": 8144, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 8276, "s": 8212, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8307, "s": 8276, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 8357, "s": 8307, "text": "Minimum number of swaps required to sort an array" } ]
Python Program for QuickSort
13 Jun, 2022 Just unlikely merge Sort, QuickSort is a divide and conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. Always pick the first element as a pivotAlways pick the last element as a pivotPick a random element as a pivotPick median as a pivot Always pick the first element as a pivot Always pick the last element as a pivot Pick a random element as a pivot Pick median as a pivot Here we will be picking the last element as a pivot. The key process in quickSort is partition(). Target of partitions is, given an array and an element ‘x’ of array as a pivot, put x at its correct position in a sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time. Pseudo Code: Recursive QuickSort function // low --> Starting index, // high --> Ending index quickSort(arr[], low, high) { // Till starting index is lesser than ending index if (low < high) { // pi is partitioning index, // arr[p] is now at right place pi = partition(arr, low, high); // Before pi quickSort(arr, low, pi - 1); // After pi quickSort(arr, pi + 1, high); } } Python3 # Python program for implementation of Quicksort Sort # This implementation utilizes pivot as the last element in the nums list# It has a pointer to keep track of the elements smaller than the pivot# At the very end of partition() function, the pointer is swapped with the pivot# to come up with a "sorted" nums relative to the pivot def partition(l, r, nums): # Last element will be the pivot and the first element the pointer pivot, ptr = nums[r], l for i in range(l, r): if nums[i] <= pivot: # Swapping values smaller than the pivot to the front nums[i], nums[ptr] = nums[ptr], nums[i] ptr += 1 # Finally swapping the last element with the pointer indexed number nums[ptr], nums[r] = nums[r], nums[ptr] return ptr # With quicksort() function, we will be utilizing the above code to obtain the pointer# at which the left values are all smaller than the number at pointer index and vice versa# for the right values. def quicksort(l, r, nums): if len(nums) == 1: # Terminating Condition for recursion. VERY IMPORTANT! return nums if l < r: pi = partition(l, r, nums) quicksort(l, pi-1, nums) # Recursively sorting the left values quicksort(pi+1, r, nums) # Recursively sorting the right values return nums example = [4, 5, 1, 2, 3]result = [1, 2, 3, 4, 5]print(quicksort(0, len(example)-1, example)) example = [2, 5, 6, 1, 4, 6, 2, 4, 7, 8]result = [1, 2, 2, 4, 4, 5, 6, 6, 7, 8]# As you can see, it works for duplicates tooprint(quicksort(0, len(example)-1, example)) [1, 2, 3, 4, 5] [1, 2, 2, 4, 4, 5, 6, 6, 7, 8] Time Complexity: Worst case time complexity is O(N2) and average case time complexity is O(N logN) Auxiliary Space: O(1) anush_krishna_v divyapvmahesh amartyaghoshgfg kimhyunbin106 sweetyty chandramauliguptach python sorting-exercises Quick Sort Python Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 295, "s": 54, "text": "Just unlikely merge Sort, QuickSort is a divide and conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. " }, { "code": null, "e": 429, "s": 295, "text": "Always pick the first element as a pivotAlways pick the last element as a pivotPick a random element as a pivotPick median as a pivot" }, { "code": null, "e": 470, "s": 429, "text": "Always pick the first element as a pivot" }, { "code": null, "e": 510, "s": 470, "text": "Always pick the last element as a pivot" }, { "code": null, "e": 543, "s": 510, "text": "Pick a random element as a pivot" }, { "code": null, "e": 566, "s": 543, "text": "Pick median as a pivot" }, { "code": null, "e": 944, "s": 566, "text": "Here we will be picking the last element as a pivot. The key process in quickSort is partition(). Target of partitions is, given an array and an element ‘x’ of array as a pivot, put x at its correct position in a sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time. " }, { "code": null, "e": 987, "s": 944, "text": "Pseudo Code: Recursive QuickSort function " }, { "code": null, "e": 1358, "s": 987, "text": "// low --> Starting index,\n// high --> Ending index\nquickSort(arr[], low, high) {\n\n // Till starting index is lesser than ending index\n if (low < high) {\n\n // pi is partitioning index,\n // arr[p] is now at right place\n pi = partition(arr, low, high);\n\n // Before pi\n quickSort(arr, low, pi - 1);\n // After pi\n quickSort(arr, pi + 1, high);\n }\n}" }, { "code": null, "e": 1366, "s": 1358, "text": "Python3" }, { "code": "# Python program for implementation of Quicksort Sort # This implementation utilizes pivot as the last element in the nums list# It has a pointer to keep track of the elements smaller than the pivot# At the very end of partition() function, the pointer is swapped with the pivot# to come up with a \"sorted\" nums relative to the pivot def partition(l, r, nums): # Last element will be the pivot and the first element the pointer pivot, ptr = nums[r], l for i in range(l, r): if nums[i] <= pivot: # Swapping values smaller than the pivot to the front nums[i], nums[ptr] = nums[ptr], nums[i] ptr += 1 # Finally swapping the last element with the pointer indexed number nums[ptr], nums[r] = nums[r], nums[ptr] return ptr # With quicksort() function, we will be utilizing the above code to obtain the pointer# at which the left values are all smaller than the number at pointer index and vice versa# for the right values. def quicksort(l, r, nums): if len(nums) == 1: # Terminating Condition for recursion. VERY IMPORTANT! return nums if l < r: pi = partition(l, r, nums) quicksort(l, pi-1, nums) # Recursively sorting the left values quicksort(pi+1, r, nums) # Recursively sorting the right values return nums example = [4, 5, 1, 2, 3]result = [1, 2, 3, 4, 5]print(quicksort(0, len(example)-1, example)) example = [2, 5, 6, 1, 4, 6, 2, 4, 7, 8]result = [1, 2, 2, 4, 4, 5, 6, 6, 7, 8]# As you can see, it works for duplicates tooprint(quicksort(0, len(example)-1, example))", "e": 2936, "s": 1366, "text": null }, { "code": null, "e": 2983, "s": 2936, "text": "[1, 2, 3, 4, 5]\n[1, 2, 2, 4, 4, 5, 6, 6, 7, 8]" }, { "code": null, "e": 3082, "s": 2983, "text": "Time Complexity: Worst case time complexity is O(N2) and average case time complexity is O(N logN)" }, { "code": null, "e": 3104, "s": 3082, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3120, "s": 3104, "text": "anush_krishna_v" }, { "code": null, "e": 3134, "s": 3120, "text": "divyapvmahesh" }, { "code": null, "e": 3150, "s": 3134, "text": "amartyaghoshgfg" }, { "code": null, "e": 3164, "s": 3150, "text": "kimhyunbin106" }, { "code": null, "e": 3173, "s": 3164, "text": "sweetyty" }, { "code": null, "e": 3193, "s": 3173, "text": "chandramauliguptach" }, { "code": null, "e": 3218, "s": 3193, "text": "python sorting-exercises" }, { "code": null, "e": 3229, "s": 3218, "text": "Quick Sort" }, { "code": null, "e": 3245, "s": 3229, "text": "Python Programs" }, { "code": null, "e": 3253, "s": 3245, "text": "Sorting" }, { "code": null, "e": 3261, "s": 3253, "text": "Sorting" } ]