title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to measure time taken by a function to execute using JavaScript? - GeeksforGeeks
20 May, 2019 Method 1: Using the performance.now() method: The now() method of the performance interface returns a high-resolution timestamp whenever it is called during the program. The time can be measured by getting the starting time before the function and ending time after the function and then subtracting both of them. This gives the time elapsed for the function. Syntax: start = performance.now(); function_to_call(); end = performance.now(); Example: <!DOCTYPE html><html> <head> <title> How to measure time taken by a function to execute using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to measure time taken by a function to execute using JavaScript? </b> <p> Click on the button to measure the time taken by the function. The output would be displayed on the console. </p> <button onclick="measurePerformance()"> Click to check </button> <script type="text/javascript"> function measurePerformance() { start = performance.now(); exampleFunction(); end = performance.now(); timeTaken = end - start; console.log("Function took " + timeTaken + " milliseconds"); } function exampleFunction() { for (i = 0; i < 1000; i++) { console.log('Hello Geeks'); } } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Using console.time() method: The time() and timeEnd() methods of Console object could be used as a timer to measure the time taken between these two methods. It takes a label parameter that could be used to distinguish between multiple timers. Whenever the timeEnd() method is called, the timer is stopped and the time output is given to the console. Syntax: console.time('label'); function_to_call(); console.timeEnd('label'); Example: <!DOCTYPE html><html> <head> <title> How to measure time taken by a function to execute using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to measure time taken by a function to execute using JavaScript? </b> <p> Click on the button to measure the time taken by the function. The output would be displayed on the console. </p> <button onclick="measurePerformance()"> Click to check </button> <script type="text/javascript"> function measurePerformance() { console.time('function1'); exampleFunction(); console.timeEnd('function1'); } function exampleFunction() { for(i= 0;i <1000; i++) { console.log('Hello Geeks'); } } </script></body> </html> Output: Before clicking the button: After clicking the button: javascript-functions Picked JavaScript Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 26543, "s": 26515, "text": "\n20 May, 2019" }, { "code": null, "e": 26903, "s": 26543, "text": "Method 1: Using the performance.now() method: The now() method of the performance interface returns a high-resolution timestamp whenever it is called during the program. The time can be measured by getting the starting time before the function and ending time after the function and then subtracting both of them. This gives the time elapsed for the function." }, { "code": null, "e": 26911, "s": 26903, "text": "Syntax:" }, { "code": null, "e": 26985, "s": 26911, "text": "start = performance.now();\nfunction_to_call();\n end = performance.now();\n" }, { "code": null, "e": 26994, "s": 26985, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to measure time taken by a function to execute using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to measure time taken by a function to execute using JavaScript? </b> <p> Click on the button to measure the time taken by the function. The output would be displayed on the console. </p> <button onclick=\"measurePerformance()\"> Click to check </button> <script type=\"text/javascript\"> function measurePerformance() { start = performance.now(); exampleFunction(); end = performance.now(); timeTaken = end - start; console.log(\"Function took \" + timeTaken + \" milliseconds\"); } function exampleFunction() { for (i = 0; i < 1000; i++) { console.log('Hello Geeks'); } } </script></body> </html> ", "e": 28059, "s": 26994, "text": null }, { "code": null, "e": 28067, "s": 28059, "text": "Output:" }, { "code": null, "e": 28095, "s": 28067, "text": "Before clicking the button:" }, { "code": null, "e": 28122, "s": 28095, "text": "After clicking the button:" }, { "code": null, "e": 28483, "s": 28122, "text": "Method 2: Using console.time() method: The time() and timeEnd() methods of Console object could be used as a timer to measure the time taken between these two methods. It takes a label parameter that could be used to distinguish between multiple timers. Whenever the timeEnd() method is called, the timer is stopped and the time output is given to the console." }, { "code": null, "e": 28491, "s": 28483, "text": "Syntax:" }, { "code": null, "e": 28561, "s": 28491, "text": "console.time('label');\nfunction_to_call();\nconsole.timeEnd('label');\n" }, { "code": null, "e": 28570, "s": 28561, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to measure time taken by a function to execute using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to measure time taken by a function to execute using JavaScript? </b> <p> Click on the button to measure the time taken by the function. The output would be displayed on the console. </p> <button onclick=\"measurePerformance()\"> Click to check </button> <script type=\"text/javascript\"> function measurePerformance() { console.time('function1'); exampleFunction(); console.timeEnd('function1'); } function exampleFunction() { for(i= 0;i <1000; i++) { console.log('Hello Geeks'); } } </script></body> </html> ", "e": 29509, "s": 28570, "text": null }, { "code": null, "e": 29517, "s": 29509, "text": "Output:" }, { "code": null, "e": 29545, "s": 29517, "text": "Before clicking the button:" }, { "code": null, "e": 29572, "s": 29545, "text": "After clicking the button:" }, { "code": null, "e": 29593, "s": 29572, "text": "javascript-functions" }, { "code": null, "e": 29600, "s": 29593, "text": "Picked" }, { "code": null, "e": 29611, "s": 29600, "text": "JavaScript" }, { "code": null, "e": 29638, "s": 29611, "text": "Web technologies Questions" }, { "code": null, "e": 29736, "s": 29638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29776, "s": 29736, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29837, "s": 29776, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29878, "s": 29837, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29900, "s": 29878, "text": "JavaScript | Promises" }, { "code": null, "e": 29954, "s": 29900, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29994, "s": 29954, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30027, "s": 29994, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30077, "s": 30027, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30137, "s": 30077, "text": "How to set the default value for an HTML <select> element ?" } ]
Move all zeros to start and ones to end in an Array of random integers - GeeksforGeeks
04 Sep, 2021 Given an array arr[] of random integers, the task is to push all the zero’s in the array to the start and all the one’s to the end of the array. Note that the order of all the other elements should be the same.Example: Input: arr[] = {1, 2, 0, 4, 3, 0, 5, 0} Output: 0 0 0 2 4 3 5 1 Input: arr[] = {1, 2, 0, 0, 0, 3, 6}; Output: 0 0 0 2 3 6 1 Approach: Traverse the array from left to right and move all the elements which are not equal to 1 at the beginning and then put 1’s in the rest of the indices at the end of the array. Now, find the index of the last element which is not equal to 1 say lastInd and then starting from this index to the beginning of the array push all the elements which are not equal to 0 in the end till lastInd and then put 0’s in the beginning.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function that pushes all the zeros// to the start and ones to the end of an arrayvoid pushBinaryToBorder(int arr[], int n){ // To store the count of elements // which are not equal to 1 int count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (int i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero int lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (int i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (!lastNonOne) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codeint main(){ int arr[] = { 1, 2, 0, 0, 0, 3, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pushBinaryToBorder(arr, n); printArr(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i]+" ");} // Function that pushes all the zeros// to the start and ones to the end of an arraystatic void pushBinaryToBorder(int arr[], int n){ // To store the count of elements // which are not equal to 1 int count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (int i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero int lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (int i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (lastNonOne == 0) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 2, 0, 0, 0, 3, 6 }; int n = arr.length; pushBinaryToBorder(arr, n); printArr(arr, n); }} // This code is contributed by SURENDRA_GANGWAR. # Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr, n) : for i in range(n) : print(arr[i],end=" ") # Function that pushes all the zeros# to the start and ones to the end of an arraydef pushBinaryToBorder(arr, n) : # To store the count of elements # which are not equal to 1 count1 = 0 # Traverse the array and calculate # count of elements which are not 1 for i in range(n) : if (arr[i] != 1) : arr[count1] = arr[i] count1 += 1 # Now all non-ones elements have been shifted to # front and 'count1' is set as index of first 1. # Make all elements 1 from count to end. while (count1 < n) : arr[count1] = 1 count1 += 1 # Initialize lastNonBinary position to zero lastNonOne = 0 # Traverse the array and pull non-zero # elements to the required indices for i in range(n - 1, -1, -1) : # Ignore the 1's if (arr[i] == 1) : continue if (not lastNonOne) : # Mark the position Of # last NonBinary integer lastNonOne = i # Place non-zero element to # their required indices if (arr[i] != 0) : arr[lastNonOne] = arr[i] lastNonOne -= 1 # Put zeros to start of array while (lastNonOne >= 0) : arr[lastNonOne] = 0 lastNonOne -= 1 # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 0, 0, 0, 3, 6 ]; n = len(arr); pushBinaryToBorder(arr, n) printArr(arr, n) # This code is contributed by Ryuga // C# implementation of the approachusing System; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.Write(arr[i] + " ");} // Function that pushes all the zeros// to the start and ones to the end of an arraystatic void pushBinaryToBorder(int [] arr, int n){ // To store the count of elements // which are not equal to 1 int count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (int i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero int lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (int i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (lastNonOne == 0) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codepublic static void Main(){ int []arr = { 1, 2, 0, 0, 0, 3, 6 }; int n = arr.Length; pushBinaryToBorder(arr, n); printArr(arr, n);}} // This code is contributed by Mohit kumar 29. <script> // Javascript implementation of the approach // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for (var i = 0; i < n; i++) document.write( arr[i] + " ");} // Function that pushes all the zeros// to the start and ones to the end of an arrayfunction pushBinaryToBorder(arr, n){ // To store the count of elements // which are not equal to 1 var count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (var i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero var lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (var i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (!lastNonOne) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codevar arr = [ 1, 2, 0, 0, 0, 3, 6 ];var n = arr.length;pushBinaryToBorder(arr, n);printArr(arr, n); </script> 0 0 0 2 3 6 1 ankthon SURENDRA_GANGWAR mohit kumar 29 rrrtnx adnanirshad158 array-traversal-question Constructive Algorithms Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26065, "s": 26037, "text": "\n04 Sep, 2021" }, { "code": null, "e": 26286, "s": 26065, "text": "Given an array arr[] of random integers, the task is to push all the zero’s in the array to the start and all the one’s to the end of the array. Note that the order of all the other elements should be the same.Example: " }, { "code": null, "e": 26412, "s": 26286, "text": "Input: arr[] = {1, 2, 0, 4, 3, 0, 5, 0} Output: 0 0 0 2 4 3 5 1 Input: arr[] = {1, 2, 0, 0, 0, 3, 6}; Output: 0 0 0 2 3 6 1 " }, { "code": null, "e": 26897, "s": 26414, "text": "Approach: Traverse the array from left to right and move all the elements which are not equal to 1 at the beginning and then put 1’s in the rest of the indices at the end of the array. Now, find the index of the last element which is not equal to 1 say lastInd and then starting from this index to the beginning of the array push all the elements which are not equal to 0 in the end till lastInd and then put 0’s in the beginning.Below is the implementation of the above approach: " }, { "code": null, "e": 26901, "s": 26897, "text": "C++" }, { "code": null, "e": 26906, "s": 26901, "text": "Java" }, { "code": null, "e": 26914, "s": 26906, "text": "Python3" }, { "code": null, "e": 26917, "s": 26914, "text": "C#" }, { "code": null, "e": 26928, "s": 26917, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function that pushes all the zeros// to the start and ones to the end of an arrayvoid pushBinaryToBorder(int arr[], int n){ // To store the count of elements // which are not equal to 1 int count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (int i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero int lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (int i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (!lastNonOne) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codeint main(){ int arr[] = { 1, 2, 0, 0, 0, 3, 6 }; int n = sizeof(arr) / sizeof(arr[0]); pushBinaryToBorder(arr, n); printArr(arr, n); return 0;}", "e": 28544, "s": 26928, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i]+\" \");} // Function that pushes all the zeros// to the start and ones to the end of an arraystatic void pushBinaryToBorder(int arr[], int n){ // To store the count of elements // which are not equal to 1 int count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (int i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero int lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (int i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (lastNonOne == 0) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 2, 0, 0, 0, 3, 6 }; int n = arr.length; pushBinaryToBorder(arr, n); printArr(arr, n); }} // This code is contributed by SURENDRA_GANGWAR.", "e": 30234, "s": 28544, "text": null }, { "code": "# Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr, n) : for i in range(n) : print(arr[i],end=\" \") # Function that pushes all the zeros# to the start and ones to the end of an arraydef pushBinaryToBorder(arr, n) : # To store the count of elements # which are not equal to 1 count1 = 0 # Traverse the array and calculate # count of elements which are not 1 for i in range(n) : if (arr[i] != 1) : arr[count1] = arr[i] count1 += 1 # Now all non-ones elements have been shifted to # front and 'count1' is set as index of first 1. # Make all elements 1 from count to end. while (count1 < n) : arr[count1] = 1 count1 += 1 # Initialize lastNonBinary position to zero lastNonOne = 0 # Traverse the array and pull non-zero # elements to the required indices for i in range(n - 1, -1, -1) : # Ignore the 1's if (arr[i] == 1) : continue if (not lastNonOne) : # Mark the position Of # last NonBinary integer lastNonOne = i # Place non-zero element to # their required indices if (arr[i] != 0) : arr[lastNonOne] = arr[i] lastNonOne -= 1 # Put zeros to start of array while (lastNonOne >= 0) : arr[lastNonOne] = 0 lastNonOne -= 1 # Driver codeif __name__ == \"__main__\" : arr = [ 1, 2, 0, 0, 0, 3, 6 ]; n = len(arr); pushBinaryToBorder(arr, n) printArr(arr, n) # This code is contributed by Ryuga", "e": 31847, "s": 30234, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \");} // Function that pushes all the zeros// to the start and ones to the end of an arraystatic void pushBinaryToBorder(int [] arr, int n){ // To store the count of elements // which are not equal to 1 int count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (int i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero int lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (int i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (lastNonOne == 0) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codepublic static void Main(){ int []arr = { 1, 2, 0, 0, 0, 3, 6 }; int n = arr.Length; pushBinaryToBorder(arr, n); printArr(arr, n);}} // This code is contributed by Mohit kumar 29.", "e": 33513, "s": 31847, "text": null }, { "code": "<script> // Javascript implementation of the approach // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for (var i = 0; i < n; i++) document.write( arr[i] + \" \");} // Function that pushes all the zeros// to the start and ones to the end of an arrayfunction pushBinaryToBorder(arr, n){ // To store the count of elements // which are not equal to 1 var count1 = 0; // Traverse the array and calculate // count of elements which are not 1 for (var i = 0; i < n; i++) if (arr[i] != 1) arr[count1++] = arr[i]; // Now all non-ones elements have been shifted to // front and 'count1' is set as index of first 1. // Make all elements 1 from count to end. while (count1 < n) arr[count1++] = 1; // Initialize lastNonBinary position to zero var lastNonOne = 0; // Traverse the array and pull non-zero // elements to the required indices for (var i = n - 1; i >= 0; i--) { // Ignore the 1's if (arr[i] == 1) continue; if (!lastNonOne) { // Mark the position Of // last NonBinary integer lastNonOne = i; } // Place non-zero element to // their required indices if (arr[i] != 0) arr[lastNonOne--] = arr[i]; } // Put zeros to start of array while (lastNonOne >= 0) arr[lastNonOne--] = 0;} // Driver codevar arr = [ 1, 2, 0, 0, 0, 3, 6 ];var n = arr.length;pushBinaryToBorder(arr, n);printArr(arr, n); </script>", "e": 35051, "s": 33513, "text": null }, { "code": null, "e": 35065, "s": 35051, "text": "0 0 0 2 3 6 1" }, { "code": null, "e": 35075, "s": 35067, "text": "ankthon" }, { "code": null, "e": 35092, "s": 35075, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 35107, "s": 35092, "text": "mohit kumar 29" }, { "code": null, "e": 35114, "s": 35107, "text": "rrrtnx" }, { "code": null, "e": 35129, "s": 35114, "text": "adnanirshad158" }, { "code": null, "e": 35154, "s": 35129, "text": "array-traversal-question" }, { "code": null, "e": 35178, "s": 35154, "text": "Constructive Algorithms" }, { "code": null, "e": 35185, "s": 35178, "text": "Arrays" }, { "code": null, "e": 35192, "s": 35185, "text": "Greedy" }, { "code": null, "e": 35199, "s": 35192, "text": "Arrays" }, { "code": null, "e": 35206, "s": 35199, "text": "Greedy" }, { "code": null, "e": 35304, "s": 35206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35331, "s": 35304, "text": "Count pairs with given sum" }, { "code": null, "e": 35362, "s": 35331, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35387, "s": 35362, "text": "Window Sliding Technique" }, { "code": null, "e": 35425, "s": 35387, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35446, "s": 35425, "text": "Next Greater Element" }, { "code": null, "e": 35497, "s": 35446, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 35555, "s": 35497, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 35606, "s": 35555, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 35666, "s": 35606, "text": "Write a program to print all permutations of a given string" } ]
Drop rows containing specific value in PySpark dataframe - GeeksforGeeks
30 Jun, 2021 In this article, we are going to drop the rows with a specific value in pyspark dataframe. Creating dataframe for demonstration: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "sravan", "vignan"], ["2", "ojaswi", "vvit"], ["3", "rohith", "vvit"], ["4", "sridevi", "vignan"], ["6", "ravi", "vrs"], ["5", "gnanesh", "iit"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print('Actual data in dataframe')dataframe.show() Output: Method 1: Using where() function This function is used to check the condition and give the results. That means it drops the rows based on the values in the dataframe column Syntax: dataframe.where(condition) Example 1: Python program to drop rows with college = vrs. Python3 # drop rows with college vrsdataframe.where(dataframe.college!='vrs').show() Output: Example 2: Python program to drop rows with ID=1 Python3 # drop rows with id=1 dataframe.where(dataframe.ID !='1').show() Output: Method 2: Using filter() function This function is used to check the condition and give the results, Which means it drops the rows based on the values in the dataframe column. Both are similar. Syntax: dataframe.filter(condition) Example: Python code to drop row with name = ravi. Python3 # drop rows with name = ravi dataframe.filter(dataframe.NAME !='ravi').show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25628, "s": 25537, "text": "In this article, we are going to drop the rows with a specific value in pyspark dataframe." }, { "code": null, "e": 25666, "s": 25628, "text": "Creating dataframe for demonstration:" }, { "code": null, "e": 25674, "s": 25666, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"sravan\", \"vignan\"], [\"2\", \"ojaswi\", \"vvit\"], [\"3\", \"rohith\", \"vvit\"], [\"4\", \"sridevi\", \"vignan\"], [\"6\", \"ravi\", \"vrs\"], [\"5\", \"gnanesh\", \"iit\"]] # specify column namescolumns = ['ID', 'NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print('Actual data in dataframe')dataframe.show()", "e": 26328, "s": 25674, "text": null }, { "code": null, "e": 26336, "s": 26328, "text": "Output:" }, { "code": null, "e": 26369, "s": 26336, "text": "Method 1: Using where() function" }, { "code": null, "e": 26509, "s": 26369, "text": "This function is used to check the condition and give the results. That means it drops the rows based on the values in the dataframe column" }, { "code": null, "e": 26544, "s": 26509, "text": "Syntax: dataframe.where(condition)" }, { "code": null, "e": 26603, "s": 26544, "text": "Example 1: Python program to drop rows with college = vrs." }, { "code": null, "e": 26611, "s": 26603, "text": "Python3" }, { "code": "# drop rows with college vrsdataframe.where(dataframe.college!='vrs').show()", "e": 26688, "s": 26611, "text": null }, { "code": null, "e": 26696, "s": 26688, "text": "Output:" }, { "code": null, "e": 26745, "s": 26696, "text": "Example 2: Python program to drop rows with ID=1" }, { "code": null, "e": 26753, "s": 26745, "text": "Python3" }, { "code": "# drop rows with id=1 dataframe.where(dataframe.ID !='1').show()", "e": 26818, "s": 26753, "text": null }, { "code": null, "e": 26826, "s": 26818, "text": "Output:" }, { "code": null, "e": 26860, "s": 26826, "text": "Method 2: Using filter() function" }, { "code": null, "e": 27020, "s": 26860, "text": "This function is used to check the condition and give the results, Which means it drops the rows based on the values in the dataframe column. Both are similar." }, { "code": null, "e": 27056, "s": 27020, "text": "Syntax: dataframe.filter(condition)" }, { "code": null, "e": 27107, "s": 27056, "text": "Example: Python code to drop row with name = ravi." }, { "code": null, "e": 27115, "s": 27107, "text": "Python3" }, { "code": "# drop rows with name = ravi dataframe.filter(dataframe.NAME !='ravi').show()", "e": 27193, "s": 27115, "text": null }, { "code": null, "e": 27201, "s": 27193, "text": "Output:" }, { "code": null, "e": 27208, "s": 27201, "text": "Picked" }, { "code": null, "e": 27223, "s": 27208, "text": "Python-Pyspark" }, { "code": null, "e": 27230, "s": 27223, "text": "Python" }, { "code": null, "e": 27328, "s": 27230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27360, "s": 27328, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27402, "s": 27360, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27444, "s": 27402, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27471, "s": 27444, "text": "Python Classes and Objects" }, { "code": null, "e": 27527, "s": 27471, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27566, "s": 27527, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27588, "s": 27566, "text": "Defaultdict in Python" }, { "code": null, "e": 27619, "s": 27588, "text": "Python | os.path.join() method" }, { "code": null, "e": 27648, "s": 27619, "text": "Create a directory in Python" } ]
Introduction to Docker - GeeksforGeeks
30 Jul, 2020 Docker is a set of platforms as a service (PaaS) products that use the Operating system level visualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries, and configuration files; they can communicate with each other through well-defined channels. All containers are run by a single operating system kernel and therefore use fewer resources than a virtual machine. Docker Containers contain binaries, libraries, and configuration files along with the application itself. They don’t contain a guest OS for each container and rely on the underlying OS kernel, which makes the containers lightweight. Containers share resources with other containers in the same host OS and provide OS-level process isolation. Virtual Machines (VMs) run on Hypervisors, which allow multiple Virtual Machines to run on a single machine along with its own operating system. Each VM has its own copy of an operating system along with the application and necessary binaries, which makes it significantly larger and it requires more resources. They provide Hardware-level process isolation and are slow to boot. It is a file, comprised of multiple layers, used to execute code in a Docker container. They are a set of instructions used to create docker containers. It is a runtime instance of an image. Allows developers to package applications with all parts needed such as libraries and other dependencies. It is a text document that contains necessary commands which on execution helps assemble a Docker Image. Docker image is created using a Docker file. The software that hosts the containers is named Docker Engine. Docker Engine is a client-server based application The docker engine has 3 main components:Server: It is responsible for creating and managing Docker images, containers, networks, and volumes on the Docker. It is referred to as a daemon process.REST API: It specifies how the applications can interact with the Server and instructs it what to do.Client: The Client is a docker command-line interface (CLI), that allows us to interact with Docker using the docker commands. Server: It is responsible for creating and managing Docker images, containers, networks, and volumes on the Docker. It is referred to as a daemon process. REST API: It specifies how the applications can interact with the Server and instructs it what to do. Client: The Client is a docker command-line interface (CLI), that allows us to interact with Docker using the docker commands. Docker Hub is the official online repository where you can find other Docker Images that are available for use. It makes it easy to find, manage, and share container images with others. $ sudo apt-get remove docker docker-engine docker.io containerd runc $ sudo apt-get update $ sudo apt-get install \ apt-transport-https \ ca-certificates \ curl \ gnupg-agent \ software-properties-common $ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - $ sudo apt-key fingerprint 0EBFCD88 $ sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable nightly test" $ sudo apt-get update $ sudo apt-get install docker-ce docker-ce-cli containerd.io Check if docker is successfully installed in your system $ sudo docker run hello-world Dockerfile main.py Python3 #!/usr/bin/env python3 print("Docker and GFG rock!") FROM python:latest COPY main.py / CMD [ "python", "./main.py" ] Once you have created and edited the main.py file and the Dockerfile, create your image to contain your application. $ docker build -t python-test . The ‘-t’ option allows to define the name of your image. ‘python-test’ is the name we have chosen for the image. Once the image is created, your code is ready to launch. $ docker run python-test 1. Create an Account on Docker Hub. 2. Click on the “Create Repository” button, put the name of the file, and click on “Create”. 3. Now will “tag our image” and “push it to the Docker Hub repository” which we just created. Now, run the below command to list docker images: $ docker images The above will give us this result REPOSITORY TAG IMAGE_ID CREATED SIZE afrozchakure/python-test latest c7857f97ebbd 2 hours ago 933MB Image ID is used to tag the image. The syntax to tag the image is: docker tag <image-id> <your dockerhub username>/python-test:latest $ docker tag c7857f97ebbd afrozchakure/python-test:latest 4. Push image to Docker Hub repository $ docker push afrozchakure/python-test 1. To remove all versions of a particular image from our local system, we use the Image ID for it. $ docker rmi -f af939ee31fdc 2. Now run the image, it will fetch the image from the docker hub if it doesn’t exist on your local machine. $ docker run afrozchakure/python-test So you have learned about the basics of Docker, the difference between Virtual Machines and Docker Containers along some common terminologies in Docker. Also, we went through the installation of Docker on our systems. We created an application using Docker and pushed our image to Docker Hub. Lastly, we learned how we could remove a particular image from our local system and later pull the image from Docker Hub if it doesn’t exist locally. Advanced Computer Subject GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression System Design Tutorial Decision Tree Introduction with example Python | Decision tree implementation Copying Files to and from Docker Containers Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... DSA Sheet by Love Babbar Socket Programming in C/C++ GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 25654, "s": 25626, "text": "\n30 Jul, 2020" }, { "code": null, "e": 26106, "s": 25654, "text": "Docker is a set of platforms as a service (PaaS) products that use the Operating system level visualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries, and configuration files; they can communicate with each other through well-defined channels. All containers are run by a single operating system kernel and therefore use fewer resources than a virtual machine." }, { "code": null, "e": 26212, "s": 26106, "text": "Docker Containers contain binaries, libraries, and configuration files along with the application itself." }, { "code": null, "e": 26339, "s": 26212, "text": "They don’t contain a guest OS for each container and rely on the underlying OS kernel, which makes the containers lightweight." }, { "code": null, "e": 26448, "s": 26339, "text": "Containers share resources with other containers in the same host OS and provide OS-level process isolation." }, { "code": null, "e": 26593, "s": 26448, "text": "Virtual Machines (VMs) run on Hypervisors, which allow multiple Virtual Machines to run on a single machine along with its own operating system." }, { "code": null, "e": 26760, "s": 26593, "text": "Each VM has its own copy of an operating system along with the application and necessary binaries, which makes it significantly larger and it requires more resources." }, { "code": null, "e": 26828, "s": 26760, "text": "They provide Hardware-level process isolation and are slow to boot." }, { "code": null, "e": 26916, "s": 26828, "text": "It is a file, comprised of multiple layers, used to execute code in a Docker container." }, { "code": null, "e": 26981, "s": 26916, "text": "They are a set of instructions used to create docker containers." }, { "code": null, "e": 27019, "s": 26981, "text": "It is a runtime instance of an image." }, { "code": null, "e": 27125, "s": 27019, "text": "Allows developers to package applications with all parts needed such as libraries and other dependencies." }, { "code": null, "e": 27230, "s": 27125, "text": "It is a text document that contains necessary commands which on execution helps assemble a Docker Image." }, { "code": null, "e": 27275, "s": 27230, "text": "Docker image is created using a Docker file." }, { "code": null, "e": 27338, "s": 27275, "text": "The software that hosts the containers is named Docker Engine." }, { "code": null, "e": 27389, "s": 27338, "text": "Docker Engine is a client-server based application" }, { "code": null, "e": 27811, "s": 27389, "text": "The docker engine has 3 main components:Server: It is responsible for creating and managing Docker images, containers, networks, and volumes on the Docker. It is referred to as a daemon process.REST API: It specifies how the applications can interact with the Server and instructs it what to do.Client: The Client is a docker command-line interface (CLI), that allows us to interact with Docker using the docker commands." }, { "code": null, "e": 27966, "s": 27811, "text": "Server: It is responsible for creating and managing Docker images, containers, networks, and volumes on the Docker. It is referred to as a daemon process." }, { "code": null, "e": 28068, "s": 27966, "text": "REST API: It specifies how the applications can interact with the Server and instructs it what to do." }, { "code": null, "e": 28195, "s": 28068, "text": "Client: The Client is a docker command-line interface (CLI), that allows us to interact with Docker using the docker commands." }, { "code": null, "e": 28307, "s": 28195, "text": "Docker Hub is the official online repository where you can find other Docker Images that are available for use." }, { "code": null, "e": 28381, "s": 28307, "text": "It makes it easy to find, manage, and share container images with others." }, { "code": null, "e": 28451, "s": 28381, "text": "$ sudo apt-get remove docker docker-engine docker.io containerd runc\n" }, { "code": null, "e": 28937, "s": 28451, "text": "$ sudo apt-get update\n$ sudo apt-get install \\\n apt-transport-https \\\n ca-certificates \\\n curl \\\n gnupg-agent \\\n software-properties-common\n$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n$ sudo apt-key fingerprint 0EBFCD88\n$ sudo add-apt-repository \\\n \"deb [arch=amd64] https://download.docker.com/linux/ubuntu \\\n $(lsb_release -cs) \\\n stable nightly test\"\n$ sudo apt-get update\n$ sudo apt-get install docker-ce docker-ce-cli containerd.io\n" }, { "code": null, "e": 28995, "s": 28937, "text": " Check if docker is successfully installed in your system" }, { "code": null, "e": 29026, "s": 28995, "text": "$ sudo docker run hello-world\n" }, { "code": null, "e": 29037, "s": 29026, "text": "Dockerfile" }, { "code": null, "e": 29045, "s": 29037, "text": "main.py" }, { "code": null, "e": 29053, "s": 29045, "text": "Python3" }, { "code": "#!/usr/bin/env python3 print(\"Docker and GFG rock!\")", "e": 29107, "s": 29053, "text": null }, { "code": null, "e": 29172, "s": 29107, "text": "FROM python:latest\nCOPY main.py /\nCMD [ \"python\", \"./main.py\" ]\n" }, { "code": null, "e": 29289, "s": 29172, "text": "Once you have created and edited the main.py file and the Dockerfile, create your image to contain your application." }, { "code": null, "e": 29322, "s": 29289, "text": "$ docker build -t python-test .\n" }, { "code": null, "e": 29435, "s": 29322, "text": "The ‘-t’ option allows to define the name of your image. ‘python-test’ is the name we have chosen for the image." }, { "code": null, "e": 29492, "s": 29435, "text": "Once the image is created, your code is ready to launch." }, { "code": null, "e": 29518, "s": 29492, "text": "$ docker run python-test\n" }, { "code": null, "e": 29554, "s": 29518, "text": "1. Create an Account on Docker Hub." }, { "code": null, "e": 29647, "s": 29554, "text": "2. Click on the “Create Repository” button, put the name of the file, and click on “Create”." }, { "code": null, "e": 29741, "s": 29647, "text": "3. Now will “tag our image” and “push it to the Docker Hub repository” which we just created." }, { "code": null, "e": 29791, "s": 29741, "text": "Now, run the below command to list docker images:" }, { "code": null, "e": 29808, "s": 29791, "text": "$ docker images\n" }, { "code": null, "e": 29843, "s": 29808, "text": "The above will give us this result" }, { "code": null, "e": 29944, "s": 29843, "text": "REPOSITORY TAG IMAGE_ID CREATED SIZE afrozchakure/python-test latest c7857f97ebbd 2 hours ago 933MB\n" }, { "code": null, "e": 30011, "s": 29944, "text": "Image ID is used to tag the image. The syntax to tag the image is:" }, { "code": null, "e": 30137, "s": 30011, "text": "docker tag <image-id> <your dockerhub username>/python-test:latest\n$ docker tag c7857f97ebbd afrozchakure/python-test:latest\n" }, { "code": null, "e": 30176, "s": 30137, "text": "4. Push image to Docker Hub repository" }, { "code": null, "e": 30216, "s": 30176, "text": "$ docker push afrozchakure/python-test\n" }, { "code": null, "e": 30315, "s": 30216, "text": "1. To remove all versions of a particular image from our local system, we use the Image ID for it." }, { "code": null, "e": 30345, "s": 30315, "text": "$ docker rmi -f af939ee31fdc\n" }, { "code": null, "e": 30454, "s": 30345, "text": "2. Now run the image, it will fetch the image from the docker hub if it doesn’t exist on your local machine." }, { "code": null, "e": 30493, "s": 30454, "text": "$ docker run afrozchakure/python-test\n" }, { "code": null, "e": 30936, "s": 30493, "text": "So you have learned about the basics of Docker, the difference between Virtual Machines and Docker Containers along some common terminologies in Docker. Also, we went through the installation of Docker on our systems. We created an application using Docker and pushed our image to Docker Hub. Lastly, we learned how we could remove a particular image from our local system and later pull the image from Docker Hub if it doesn’t exist locally." }, { "code": null, "e": 30962, "s": 30936, "text": "Advanced Computer Subject" }, { "code": null, "e": 30968, "s": 30962, "text": "GBlog" }, { "code": null, "e": 31066, "s": 30968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31089, "s": 31066, "text": "ML | Linear Regression" }, { "code": null, "e": 31112, "s": 31089, "text": "System Design Tutorial" }, { "code": null, "e": 31152, "s": 31112, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31190, "s": 31152, "text": "Python | Decision tree implementation" }, { "code": null, "e": 31234, "s": 31190, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 31308, "s": 31234, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 31333, "s": 31308, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31361, "s": 31333, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31396, "s": 31361, "text": "GET and POST requests using Python" } ]
Python | os.getegid() and os.setegid() method - GeeksforGeeks
31 Oct, 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. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.getegid() method in Python is used to get the current process’s effective group id and os.setegid() method is used to set effective group id of the current process. Note: os.setegid() and os.getegid() methods are available only on UNIX platforms and the functionality of os.setegid() method is typically available only to the superuser.Superuser means a root user or an administrative user who has all the permissions to run or execute any program in the operating system. Syntax: os.getegid() Parameter: No parameter is required Return Type: This method returns an integer value which represents the current process’s effective group id. # Python program to explain os.getegid() method # importing os module import os # Get the effective group id# of the current process# using os.getegid() methodegid = os.getegid() # Print the effective group id# of the current processprint("Effective group id of the current process:", egid) Output: Syntax: os.setegid(egid) Parameter:egid: An integer value representing new effective group id for the current process. Return Type: This method does not return any value. # Python program to explain os.setegid() method # importing os module import os # Get the effective group id# of the current process# using os.getegid() methodegid = os.getegid() # Print the effective group id# of the current processprint("Effective group id of the current process:", egid) # Change the effective group id# for the current process# using os.setegid() methodegid = 200os.setegid(egid)print("Effective group id changed") # Print the effective group id# of the current processegid = os.getegid()print("Effective group id of the current process:", egid) Output: Akanksha_Rai python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n31 Oct, 2019" }, { "code": null, "e": 25756, "s": 25537, "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": 25951, "s": 25756, "text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system." }, { "code": null, "e": 26119, "s": 25951, "text": "os.getegid() method in Python is used to get the current process’s effective group id and os.setegid() method is used to set effective group id of the current process." }, { "code": null, "e": 26427, "s": 26119, "text": "Note: os.setegid() and os.getegid() methods are available only on UNIX platforms and the functionality of os.setegid() method is typically available only to the superuser.Superuser means a root user or an administrative user who has all the permissions to run or execute any program in the operating system." }, { "code": null, "e": 26448, "s": 26427, "text": "Syntax: os.getegid()" }, { "code": null, "e": 26484, "s": 26448, "text": "Parameter: No parameter is required" }, { "code": null, "e": 26593, "s": 26484, "text": "Return Type: This method returns an integer value which represents the current process’s effective group id." }, { "code": "# Python program to explain os.getegid() method # importing os module import os # Get the effective group id# of the current process# using os.getegid() methodegid = os.getegid() # Print the effective group id# of the current processprint(\"Effective group id of the current process:\", egid)", "e": 26888, "s": 26593, "text": null }, { "code": null, "e": 26896, "s": 26888, "text": "Output:" }, { "code": null, "e": 26921, "s": 26896, "text": "Syntax: os.setegid(egid)" }, { "code": null, "e": 27015, "s": 26921, "text": "Parameter:egid: An integer value representing new effective group id for the current process." }, { "code": null, "e": 27067, "s": 27015, "text": "Return Type: This method does not return any value." }, { "code": "# Python program to explain os.setegid() method # importing os module import os # Get the effective group id# of the current process# using os.getegid() methodegid = os.getegid() # Print the effective group id# of the current processprint(\"Effective group id of the current process:\", egid) # Change the effective group id# for the current process# using os.setegid() methodegid = 200os.setegid(egid)print(\"Effective group id changed\") # Print the effective group id# of the current processegid = os.getegid()print(\"Effective group id of the current process:\", egid)", "e": 27642, "s": 27067, "text": null }, { "code": null, "e": 27650, "s": 27642, "text": "Output:" }, { "code": null, "e": 27663, "s": 27650, "text": "Akanksha_Rai" }, { "code": null, "e": 27680, "s": 27663, "text": "python-os-module" }, { "code": null, "e": 27687, "s": 27680, "text": "Python" }, { "code": null, "e": 27785, "s": 27687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27817, "s": 27785, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27859, "s": 27817, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27901, "s": 27859, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27957, "s": 27901, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27984, "s": 27957, "text": "Python Classes and Objects" }, { "code": null, "e": 28015, "s": 27984, "text": "Python | os.path.join() method" }, { "code": null, "e": 28054, "s": 28015, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28083, "s": 28054, "text": "Create a directory in Python" }, { "code": null, "e": 28105, "s": 28083, "text": "Defaultdict in Python" } ]
How to change default font in Tkinter? - GeeksforGeeks
24 Jan, 2021 Prerequisites: Tkinter Tkinter provides a variety of fonts for different things i.e Heading, Caption, Text, Menu, etc. But the good thing is we can override these fonts using tkinter.font module. Some fonts provided by the Tkinter are: TkDefaultFont TkMenuFont TkFixedFont TkSmallCaptionFont and so on. In this article, we are going to change the default font. In order to do this, we need to override/ change the configuration of TkDefaultFont. Changing/ overriding the default font is very easy and can be done in the listed way: Create the font object using font.nametofont method. Use the configure method on the font object Then change font style such as font-family, font-size, and so on. Given below is the proper approach for doing the same. Import module Create window Create the font object using font.nametofont method. Use the configure method on the font object Then change font style such as font-family, font-size, and so on. Add required elements Execute code Program: Python3 # Import tkinter.Tk and widgetsfrom tkinter import Tk, fontfrom tkinter.ttk import Button, Label class App: def __init__(self, master: Tk) -> None: self.master = master # Creating a Font object of "TkDefaultFont" self.defaultFont = font.nametofont("TkDefaultFont") # Overriding default-font with custom settings # i.e changing font-family, size and weight self.defaultFont.configure(family="Segoe Script", size=19, weight=font.BOLD) # Label widget self.label = Label(self.master, text="I'm Label") self.label.pack() # Button widget self.btn = Button(self.master, text="I'm Button") self.btn.pack() if __name__ == "__main__": # Top level widget root = Tk() # Setting window dimensions root.geometry("300x150") # Setting app title root.title("Changing Default Font") print(font.names()) app = App(root) # Mainloop to run application # infinitely root.mainloop() Output: Before changing configuration After changing configuration Picked Python-tkinter Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25631, "s": 25603, "text": "\n24 Jan, 2021" }, { "code": null, "e": 25654, "s": 25631, "text": "Prerequisites: Tkinter" }, { "code": null, "e": 25827, "s": 25654, "text": "Tkinter provides a variety of fonts for different things i.e Heading, Caption, Text, Menu, etc. But the good thing is we can override these fonts using tkinter.font module." }, { "code": null, "e": 25867, "s": 25827, "text": "Some fonts provided by the Tkinter are:" }, { "code": null, "e": 25881, "s": 25867, "text": "TkDefaultFont" }, { "code": null, "e": 25892, "s": 25881, "text": "TkMenuFont" }, { "code": null, "e": 25904, "s": 25892, "text": "TkFixedFont" }, { "code": null, "e": 25934, "s": 25904, "text": "TkSmallCaptionFont and so on." }, { "code": null, "e": 26163, "s": 25934, "text": "In this article, we are going to change the default font. In order to do this, we need to override/ change the configuration of TkDefaultFont. Changing/ overriding the default font is very easy and can be done in the listed way:" }, { "code": null, "e": 26216, "s": 26163, "text": "Create the font object using font.nametofont method." }, { "code": null, "e": 26260, "s": 26216, "text": "Use the configure method on the font object" }, { "code": null, "e": 26326, "s": 26260, "text": "Then change font style such as font-family, font-size, and so on." }, { "code": null, "e": 26381, "s": 26326, "text": "Given below is the proper approach for doing the same." }, { "code": null, "e": 26395, "s": 26381, "text": "Import module" }, { "code": null, "e": 26409, "s": 26395, "text": "Create window" }, { "code": null, "e": 26462, "s": 26409, "text": "Create the font object using font.nametofont method." }, { "code": null, "e": 26506, "s": 26462, "text": "Use the configure method on the font object" }, { "code": null, "e": 26572, "s": 26506, "text": "Then change font style such as font-family, font-size, and so on." }, { "code": null, "e": 26594, "s": 26572, "text": "Add required elements" }, { "code": null, "e": 26607, "s": 26594, "text": "Execute code" }, { "code": null, "e": 26616, "s": 26607, "text": "Program:" }, { "code": null, "e": 26624, "s": 26616, "text": "Python3" }, { "code": "# Import tkinter.Tk and widgetsfrom tkinter import Tk, fontfrom tkinter.ttk import Button, Label class App: def __init__(self, master: Tk) -> None: self.master = master # Creating a Font object of \"TkDefaultFont\" self.defaultFont = font.nametofont(\"TkDefaultFont\") # Overriding default-font with custom settings # i.e changing font-family, size and weight self.defaultFont.configure(family=\"Segoe Script\", size=19, weight=font.BOLD) # Label widget self.label = Label(self.master, text=\"I'm Label\") self.label.pack() # Button widget self.btn = Button(self.master, text=\"I'm Button\") self.btn.pack() if __name__ == \"__main__\": # Top level widget root = Tk() # Setting window dimensions root.geometry(\"300x150\") # Setting app title root.title(\"Changing Default Font\") print(font.names()) app = App(root) # Mainloop to run application # infinitely root.mainloop()", "e": 27696, "s": 26624, "text": null }, { "code": null, "e": 27704, "s": 27696, "text": "Output:" }, { "code": null, "e": 27734, "s": 27704, "text": "Before changing configuration" }, { "code": null, "e": 27763, "s": 27734, "text": "After changing configuration" }, { "code": null, "e": 27770, "s": 27763, "text": "Picked" }, { "code": null, "e": 27785, "s": 27770, "text": "Python-tkinter" }, { "code": null, "e": 27809, "s": 27785, "text": "Technical Scripter 2020" }, { "code": null, "e": 27816, "s": 27809, "text": "Python" }, { "code": null, "e": 27835, "s": 27816, "text": "Technical Scripter" }, { "code": null, "e": 27933, "s": 27835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27951, "s": 27933, "text": "Python Dictionary" }, { "code": null, "e": 27986, "s": 27951, "text": "Read a file line by line in Python" }, { "code": null, "e": 28018, "s": 27986, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28040, "s": 28018, "text": "Enumerate() in Python" }, { "code": null, "e": 28082, "s": 28040, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28112, "s": 28082, "text": "Iterate over a list in Python" }, { "code": null, "e": 28138, "s": 28112, "text": "Python String | replace()" }, { "code": null, "e": 28167, "s": 28138, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28211, "s": 28167, "text": "Reading and Writing to text files in Python" } ]
What are the best input sanitizing functions in PHP ? - GeeksforGeeks
08 Aug, 2020 Sanitizing data means removing any illegal character from the data. Sanitizing user input is one of the most common tasks in a web application. To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.The PHP Filter Extension: PHP filters are used to sanitize and validate external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to do data sanitization easier and quicker. This function, when using the flag in the example, is making sure that the code removes all characters except letters, digits and the following characters !#$%&’*+-=?_`{|}~@.[] . Advantages of using Filters: Many web applications receive external input. External input/data can be: User input from a form Cookies Web services data Server Variables Database query results Sanitizing a String: The following example uses the filter_var() function to remove all HTML tags from a string.Program php <?php //Use of filter_var()$str = "<h1>GeeksforGeeks</h1>"; $newstr = filter_var($str, FILTER_SANITIZE_STRING); echo $newstr;?> GeeksforGeeks Sanitizing an Email Address: The following example uses the filter_var() function to remove all illegal characters from the $email variable.Program: php <?php $email = "[email protected]<m>"; // Remove all illegal characters// from email$nemail = filter_var($email, FILTER_SANITIZE_EMAIL); echo $nemail;?> [email protected] Sanitizing a URL: The following example uses the filter_var() function to remove all illegal characters from a URL:Program: php <?php $url = "www.geeksforgeeks.or°g"; // Remove all illegal characters// from a url$nurl = filter_var($url, FILTER_SANITIZE_URL); echo $nurl;?> www.geeksforgeeks.org apoorv__maheshwari PHP-Misc Picked PHP PHP Programs 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 ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP
[ { "code": null, "e": 25739, "s": 25711, "text": "\n08 Aug, 2020" }, { "code": null, "e": 26548, "s": 25739, "text": "Sanitizing data means removing any illegal character from the data. Sanitizing user input is one of the most common tasks in a web application. To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.The PHP Filter Extension: PHP filters are used to sanitize and validate external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to do data sanitization easier and quicker. This function, when using the flag in the example, is making sure that the code removes all characters except letters, digits and the following characters !#$%&’*+-=?_`{|}~@.[] . Advantages of using Filters: Many web applications receive external input. External input/data can be: " }, { "code": null, "e": 26571, "s": 26548, "text": "User input from a form" }, { "code": null, "e": 26579, "s": 26571, "text": "Cookies" }, { "code": null, "e": 26597, "s": 26579, "text": "Web services data" }, { "code": null, "e": 26614, "s": 26597, "text": "Server Variables" }, { "code": null, "e": 26637, "s": 26614, "text": "Database query results" }, { "code": null, "e": 26759, "s": 26637, "text": "Sanitizing a String: The following example uses the filter_var() function to remove all HTML tags from a string.Program " }, { "code": null, "e": 26763, "s": 26759, "text": "php" }, { "code": "<?php //Use of filter_var()$str = \"<h1>GeeksforGeeks</h1>\"; $newstr = filter_var($str, FILTER_SANITIZE_STRING); echo $newstr;?>", "e": 26898, "s": 26763, "text": null }, { "code": null, "e": 26915, "s": 26898, "text": "GeeksforGeeks\n\n\n" }, { "code": null, "e": 27067, "s": 26917, "text": "Sanitizing an Email Address: The following example uses the filter_var() function to remove all illegal characters from the $email variable.Program: " }, { "code": null, "e": 27071, "s": 27067, "text": "php" }, { "code": "<?php $email = \"[email protected]<m>\"; // Remove all illegal characters// from email$nemail = filter_var($email, FILTER_SANITIZE_EMAIL); echo $nemail;?>", "e": 27245, "s": 27071, "text": null }, { "code": null, "e": 27272, "s": 27245, "text": "[email protected]\n\n\n" }, { "code": null, "e": 27400, "s": 27274, "text": "Sanitizing a URL: The following example uses the filter_var() function to remove all illegal characters from a URL:Program: " }, { "code": null, "e": 27404, "s": 27400, "text": "php" }, { "code": "<?php $url = \"www.geeksforgeeks.or°g\"; // Remove all illegal characters// from a url$nurl = filter_var($url, FILTER_SANITIZE_URL); echo $nurl;?>", "e": 27565, "s": 27404, "text": null }, { "code": null, "e": 27590, "s": 27565, "text": "www.geeksforgeeks.org\n\n\n" }, { "code": null, "e": 27611, "s": 27592, "text": "apoorv__maheshwari" }, { "code": null, "e": 27620, "s": 27611, "text": "PHP-Misc" }, { "code": null, "e": 27627, "s": 27620, "text": "Picked" }, { "code": null, "e": 27631, "s": 27627, "text": "PHP" }, { "code": null, "e": 27644, "s": 27631, "text": "PHP Programs" }, { "code": null, "e": 27661, "s": 27644, "text": "Web Technologies" }, { "code": null, "e": 27665, "s": 27661, "text": "PHP" }, { "code": null, "e": 27763, "s": 27665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27813, "s": 27763, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27853, "s": 27813, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27898, "s": 27853, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27940, "s": 27898, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27992, "s": 27940, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 28042, "s": 27992, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28082, "s": 28042, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28134, "s": 28082, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28176, "s": 28134, "text": "How to pass JavaScript variables to PHP ?" } ]
ListView - Class Based Views Django - GeeksforGeeks
11 Jan, 2022 List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed the basics of List View in List View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching. Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components. Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based view with few lines only. This is where Object Oriented Programming comes into impact. Illustration of How to create and use List view using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, Python3 # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title After creating this model, we need to run two commands in order to create Database for the same. Python manage.py makemigrations Python manage.py migrate Now let’s create some instances of this model using shell, run form bash, Python manage.py shell Enter following commands >>> from geeks.models import GeeksModel >>> GeeksModel.objects.create( title="title1", description="description1").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create ListView for, then Class based ListView will automatically try to find a template in app_name/modelname_list.html. In our case it is geeks/templates/geeks/geeksmodel_list.html. Let’s create our class based view. In geeks/views.py, Python3 from django.views.generic.list import ListViewfrom .models import GeeksModel class GeeksList(ListView): # specify the model for list view model = GeeksModel Now create a url path to map the view. In geeks/urls.py, Python3 from django.urls import path # importing views from views..pyfrom .views import GeeksListurlpatterns = [ path('', GeeksList.as_view()),] Create a template in templates/geeks/geeksmodel_list.html, HTML <ul> <!-- Iterate over object_list --> {% for object in object_list %} <!-- Display Objects --> <li>{{ object.title }}</li> <li>{{ object.description }}</li> <hr/> <!-- If object_list is empty --> {% empty %} <li>No objects yet.</li> {% endfor %}</ul> Let’s check what is there on http://localhost:8000/ By default ListView will display all instances of a table in the order they were created. If one wants to modify the sequence of these instances or the ordering, get_queryset method need to be overriden. In geeks/views.py, Python3 from django.views.generic.list import ListViewfrom .models import GeeksModel class GeeksList(ListView): # specify the model for list view model = GeeksModel def get_queryset(self, *args, **kwargs): qs = super(GeeksList, self).get_queryset(*args, **kwargs) qs = qs.order_by("-id") return qs Now check, if the order of instances has been reversed. This way one can modify the entire queryset in any manner possible. dannybrown Django-views Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25575, "s": 25547, "text": "\n11 Jan, 2022" }, { "code": null, "e": 25992, "s": 25575, "text": "List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed the basics of List View in List View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: " }, { "code": null, "e": 26135, "s": 25992, "text": "Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching." }, { "code": null, "e": 26253, "s": 26135, "text": "Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components." }, { "code": null, "e": 26507, "s": 26253, "text": "Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based view with few lines only. This is where Object Oriented Programming comes into impact. " }, { "code": null, "e": 26640, "s": 26507, "text": "Illustration of How to create and use List view using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 26728, "s": 26640, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 26779, "s": 26728, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26812, "s": 26779, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26948, "s": 26812, "text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, " }, { "code": null, "e": 26956, "s": 26948, "text": "Python3" }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 27344, "s": 26956, "text": null }, { "code": null, "e": 27442, "s": 27344, "text": "After creating this model, we need to run two commands in order to create Database for the same. " }, { "code": null, "e": 27499, "s": 27442, "text": "Python manage.py makemigrations\nPython manage.py migrate" }, { "code": null, "e": 27574, "s": 27499, "text": "Now let’s create some instances of this model using shell, run form bash, " }, { "code": null, "e": 27597, "s": 27574, "text": "Python manage.py shell" }, { "code": null, "e": 27624, "s": 27597, "text": "Enter following commands " }, { "code": null, "e": 28048, "s": 27624, "text": ">>> from geeks.models import GeeksModel\n>>> GeeksModel.objects.create(\n title=\"title1\",\n description=\"description1\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()" }, { "code": null, "e": 28183, "s": 28048, "text": "Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ " }, { "code": null, "e": 28525, "s": 28183, "text": "Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create ListView for, then Class based ListView will automatically try to find a template in app_name/modelname_list.html. In our case it is geeks/templates/geeks/geeksmodel_list.html. Let’s create our class based view. In geeks/views.py, " }, { "code": null, "e": 28533, "s": 28525, "text": "Python3" }, { "code": "from django.views.generic.list import ListViewfrom .models import GeeksModel class GeeksList(ListView): # specify the model for list view model = GeeksModel", "e": 28697, "s": 28533, "text": null }, { "code": null, "e": 28755, "s": 28697, "text": "Now create a url path to map the view. In geeks/urls.py, " }, { "code": null, "e": 28763, "s": 28755, "text": "Python3" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import GeeksListurlpatterns = [ path('', GeeksList.as_view()),]", "e": 28903, "s": 28763, "text": null }, { "code": null, "e": 28963, "s": 28903, "text": "Create a template in templates/geeks/geeksmodel_list.html, " }, { "code": null, "e": 28968, "s": 28963, "text": "HTML" }, { "code": "<ul> <!-- Iterate over object_list --> {% for object in object_list %} <!-- Display Objects --> <li>{{ object.title }}</li> <li>{{ object.description }}</li> <hr/> <!-- If object_list is empty --> {% empty %} <li>No objects yet.</li> {% endfor %}</ul>", "e": 29254, "s": 28968, "text": null }, { "code": null, "e": 29307, "s": 29254, "text": "Let’s check what is there on http://localhost:8000/ " }, { "code": null, "e": 29531, "s": 29307, "text": "By default ListView will display all instances of a table in the order they were created. If one wants to modify the sequence of these instances or the ordering, get_queryset method need to be overriden. In geeks/views.py, " }, { "code": null, "e": 29539, "s": 29531, "text": "Python3" }, { "code": "from django.views.generic.list import ListViewfrom .models import GeeksModel class GeeksList(ListView): # specify the model for list view model = GeeksModel def get_queryset(self, *args, **kwargs): qs = super(GeeksList, self).get_queryset(*args, **kwargs) qs = qs.order_by(\"-id\") return qs", "e": 29867, "s": 29539, "text": null }, { "code": null, "e": 29924, "s": 29867, "text": "Now check, if the order of instances has been reversed. " }, { "code": null, "e": 29993, "s": 29924, "text": "This way one can modify the entire queryset in any manner possible. " }, { "code": null, "e": 30004, "s": 29993, "text": "dannybrown" }, { "code": null, "e": 30017, "s": 30004, "text": "Django-views" }, { "code": null, "e": 30031, "s": 30017, "text": "Python Django" }, { "code": null, "e": 30038, "s": 30031, "text": "Python" }, { "code": null, "e": 30136, "s": 30038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30168, "s": 30136, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30190, "s": 30168, "text": "Enumerate() in Python" }, { "code": null, "e": 30232, "s": 30190, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30258, "s": 30232, "text": "Python String | replace()" }, { "code": null, "e": 30287, "s": 30258, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30324, "s": 30287, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30360, "s": 30324, "text": "Convert integer to string in Python" }, { "code": null, "e": 30402, "s": 30360, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30427, "s": 30402, "text": "sum() function in Python" } ]
How to disable spell checking from Input Box and Textarea in HTML forms? - GeeksforGeeks
06 Sep, 2021 Basically the concept of spell check feature is used when we enter the grammatically incorrect words inside <input> or <textarea> fields in HTML form you will see the red underline below the incorrect words. It is used to detect grammatical or spelling mistakes in the text fields. To disable spellcheck in an HTML form the spellcheck attribute is set to “false”. Below is the sample HTML program with disabled spellcheck. Example: html <!DOCTYPE html><html><body><h2>a GeeksForGeeks</h2> <h2> How to disable spell checkingfrom Input Box and Textarea in HTML forms </h2> <form> <h4>Enabling the spell check Property</h4> <input type="text" spellcheck="true"> <h4> Disabling the spell check Property</h4> <input type="text" spellcheck="false"> </p> <p> <textarea spellcheck="false"></textarea> </p> <button type="reset">Reset</button> </form></body></html> Output: Supported Browsers are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. anikaseth98 HTML-Misc HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n06 Sep, 2021" }, { "code": null, "e": 26421, "s": 26139, "text": "Basically the concept of spell check feature is used when we enter the grammatically incorrect words inside <input> or <textarea> fields in HTML form you will see the red underline below the incorrect words. It is used to detect grammatical or spelling mistakes in the text fields." }, { "code": null, "e": 26562, "s": 26421, "text": "To disable spellcheck in an HTML form the spellcheck attribute is set to “false”. Below is the sample HTML program with disabled spellcheck." }, { "code": null, "e": 26573, "s": 26562, "text": "Example: " }, { "code": null, "e": 26578, "s": 26573, "text": "html" }, { "code": "<!DOCTYPE html><html><body><h2>a GeeksForGeeks</h2> <h2> How to disable spell checkingfrom Input Box and Textarea in HTML forms </h2> <form> <h4>Enabling the spell check Property</h4> <input type=\"text\" spellcheck=\"true\"> <h4> Disabling the spell check Property</h4> <input type=\"text\" spellcheck=\"false\"> </p> <p> <textarea spellcheck=\"false\"></textarea> </p> <button type=\"reset\">Reset</button> </form></body></html>", "e": 27086, "s": 26578, "text": null }, { "code": null, "e": 27094, "s": 27086, "text": "Output:" }, { "code": null, "e": 27131, "s": 27094, "text": "Supported Browsers are listed below:" }, { "code": null, "e": 27145, "s": 27131, "text": "Google Chrome" }, { "code": null, "e": 27163, "s": 27145, "text": "Internet Explorer" }, { "code": null, "e": 27171, "s": 27163, "text": "Firefox" }, { "code": null, "e": 27177, "s": 27171, "text": "Opera" }, { "code": null, "e": 27184, "s": 27177, "text": "Safari" }, { "code": null, "e": 27321, "s": 27184, "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": 27333, "s": 27321, "text": "anikaseth98" }, { "code": null, "e": 27343, "s": 27333, "text": "HTML-Misc" }, { "code": null, "e": 27348, "s": 27343, "text": "HTML" }, { "code": null, "e": 27365, "s": 27348, "text": "Web Technologies" }, { "code": null, "e": 27370, "s": 27365, "text": "HTML" }, { "code": null, "e": 27468, "s": 27370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27492, "s": 27468, "text": "REST API (Introduction)" }, { "code": null, "e": 27533, "s": 27492, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27570, "s": 27533, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27599, "s": 27570, "text": "Form validation using jQuery" }, { "code": null, "e": 27619, "s": 27599, "text": "Angular File Upload" }, { "code": null, "e": 27659, "s": 27619, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27692, "s": 27659, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27737, "s": 27692, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27780, "s": 27737, "text": "How to fetch data from an API in ReactJS ?" } ]
Catch and Throw Exception In Ruby - GeeksforGeeks
11 Oct, 2019 An exception is an object of class Exception or a child of that class. Exceptions occurs when the program reaches a state in its execution that’s not defined. Now the program does not know what to do so it raises an exception. This can be done automatically by Ruby or manually. Catch and Throw is similar raise and rescue keywords, Exceptions can also be handled using catch and throw keywords in Ruby. Throw keyword generates an exception and whenever it is met, the program control goes to the catch statement. Syntax: catch :lable_name do # matching catch will be executed when the throw block encounter throw :lable_name condition # this block will not be executed end The catch block is used to jump out from the nested block and the block is labeled with a name. This block works normally until it encounters with the throw block that’s why catch and throw used instead of raise or rescue. Example #1: # Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do # a code block of catch similar to begin number = rand(2) throw :divide if number == 0 number # set gfg = number if # no exception is thrownendputs gfg Output : In above example, if the number is 0 then the exception:divide is thrown which returns nothing to the catch statement resulting in “”set to gfg. if the number is 1 then the exception is not thrown and the gfg variable is set to 1. Example #2: throw with default value. In the above example when the exception was thrown, the value of variable gfg was set to “”. we can change that by passing the default argument to the throw keyword. # Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do # a code block of catch similar to begin number = rand(2) throw :divide, 10 if number == 0 number # set gfg = number if # no exception is thrownendputs gfg Output : 10 In above example, if number is 0 we get 10. if number is 1 we get 1. Example 3: nested construct example, here we will see how we can jump out of nested constructs. # Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do # a code block of catch similar to begin 100.times do 100.times do 100.times do number = rand(10000) # comes out of all of the loops # and goes to catch statement throw :divide, 10 if number == 0 end end end number # set gfg = number if # no exception is thrownendputs gfg Output : 10 if number is 0 even once in the loops we get 10 otherwise we get the number . Picked Ruby-Exception-handling Ruby Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Array count() operation Include v/s Extend in Ruby Global Variable in Ruby Ruby | Hash delete() function Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types Ruby | Numeric round() function
[ { "code": null, "e": 24955, "s": 24927, "text": "\n11 Oct, 2019" }, { "code": null, "e": 25469, "s": 24955, "text": "An exception is an object of class Exception or a child of that class. Exceptions occurs when the program reaches a state in its execution that’s not defined. Now the program does not know what to do so it raises an exception. This can be done automatically by Ruby or manually. Catch and Throw is similar raise and rescue keywords, Exceptions can also be handled using catch and throw keywords in Ruby. Throw keyword generates an exception and whenever it is met, the program control goes to the catch statement." }, { "code": null, "e": 25477, "s": 25469, "text": "Syntax:" }, { "code": null, "e": 25631, "s": 25477, "text": "catch :lable_name do\n# matching catch will be executed when the throw block encounter\n\nthrow :lable_name condition\n# this block will not be executed\n\nend" }, { "code": null, "e": 25854, "s": 25631, "text": "The catch block is used to jump out from the nested block and the block is labeled with a name. This block works normally until it encounters with the throw block that’s why catch and throw used instead of raise or rescue." }, { "code": null, "e": 25866, "s": 25854, "text": "Example #1:" }, { "code": "# Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do # a code block of catch similar to begin number = rand(2) throw :divide if number == 0 number # set gfg = number if # no exception is thrownendputs gfg", "e": 26098, "s": 25866, "text": null }, { "code": null, "e": 26107, "s": 26098, "text": "Output :" }, { "code": null, "e": 26340, "s": 26109, "text": "In above example, if the number is 0 then the exception:divide is thrown which returns nothing to the catch statement resulting in “”set to gfg. if the number is 1 then the exception is not thrown and the gfg variable is set to 1." }, { "code": null, "e": 26380, "s": 26342, "text": "Example #2: throw with default value." }, { "code": null, "e": 26546, "s": 26380, "text": "In the above example when the exception was thrown, the value of variable gfg was set to “”. we can change that by passing the default argument to the throw keyword." }, { "code": "# Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do # a code block of catch similar to begin number = rand(2) throw :divide, 10 if number == 0 number # set gfg = number if # no exception is thrownendputs gfg", "e": 26782, "s": 26546, "text": null }, { "code": null, "e": 26791, "s": 26782, "text": "Output :" }, { "code": null, "e": 26795, "s": 26791, "text": "10\n" }, { "code": null, "e": 26960, "s": 26795, "text": "In above example, if number is 0 we get 10. if number is 1 we get 1. Example 3: nested construct example, here we will see how we can jump out of nested constructs." }, { "code": "# Ruby Program of Catch and Throw Exceptiongfg = catch(:divide) do # a code block of catch similar to begin 100.times do 100.times do 100.times do number = rand(10000) # comes out of all of the loops # and goes to catch statement throw :divide, 10 if number == 0 end end end number # set gfg = number if # no exception is thrownendputs gfg", "e": 27374, "s": 26960, "text": null }, { "code": null, "e": 27383, "s": 27374, "text": "Output :" }, { "code": null, "e": 27387, "s": 27383, "text": "10\n" }, { "code": null, "e": 27465, "s": 27387, "text": "if number is 0 even once in the loops we get 10 otherwise we get the number ." }, { "code": null, "e": 27472, "s": 27465, "text": "Picked" }, { "code": null, "e": 27496, "s": 27472, "text": "Ruby-Exception-handling" }, { "code": null, "e": 27501, "s": 27496, "text": "Ruby" }, { "code": null, "e": 27520, "s": 27501, "text": "Technical Scripter" }, { "code": null, "e": 27618, "s": 27520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27649, "s": 27618, "text": "Ruby | Array count() operation" }, { "code": null, "e": 27676, "s": 27649, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 27700, "s": 27676, "text": "Global Variable in Ruby" }, { "code": null, "e": 27730, "s": 27700, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 27756, "s": 27730, "text": "Ruby | Types of Variables" }, { "code": null, "e": 27799, "s": 27756, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 27821, "s": 27799, "text": "Ruby | Case Statement" }, { "code": null, "e": 27852, "s": 27821, "text": "Ruby | Array select() function" }, { "code": null, "e": 27870, "s": 27852, "text": "Ruby | Data Types" } ]
Recursive Functions - GeeksforGeeks
26 May, 2021 Recursion:In programming terms, a recursive function can be defined as a routine that calls itself directly or indirectly.Using the recursive algorithm, certain problems can be solved quite easily. Towers of Hanoi (TOH) is one such programming exercise. Try to write an iterative algorithm for TOH. Moreover, every recursive program can be written using iterative methods.Mathematically, recursion helps to solve a few puzzles easily.For example, a routine interview question,In a party of N people, each person will shake her/his hand with each other person only once. In total how many hand-shakes would happen? Solution:It can be solved in different ways; graphs, recursions, etc. Let us see how recursively it can be solved.There are N persons. Each person shakes hands with each other only once. Considering N-th person, (s)he has to shake a hand with (N-1) the person. Now the problem is reduced to small instances of (N-1) persons. Assuming TN as a total shake-hands, it can be formulated recursively.TN = (N-1) + TN-1 [T1 = 0, i.e. the last person has already shook-hand with every one]Solving it recursively yields an arithmetic series, which can be evaluated into N(N-1)/2.Exercise: In a party of N couples, only one gender (either male or female) can shake hands with everyone. How many shake-hands would happen?Usually, recursive programs result in poor time complexity. An example is a Fibonacci series. The time complexity of calculating the n-th Fibonacci number using recursion is approximately 1.6n. It means the same computer takes almost 60% more time for the next Fibonacci number. The recursive Fibonacci algorithm has overlapping subproblems. There are other techniques like dynamic programming to improve such overlapped algorithms.However, a few algorithms, (e.g. merge sort, quick sort, etc...) result in optimal time complexity using recursion. Base Case:One critical requirement of recursive functions is the termination point or base case. Every recursive program must have a base case to make sure that the function will terminate. Missing base case results in unexpected behavior. Different Ways of Writing Recursive Functions Function calling itself: (Direct way) Most of us are aware of at least two different ways of writing recursive programs. Given below are towers of the Hanoi code. It is an example of direct calling. C++ C Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; // Assuming n-th disk is bottom disk (count down)void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole){ // Base case (termination condition)if(0 == n) return; // Move first n-1 disks from source pole// to auxiliary pole using destination as// temporary poletower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source// pole to destination polecout << "Move the disk "<< n << " from " << sourcePole <<" to "<< destinationPole << endl; // Move the n-1 disks from auxiliary (now source)// pole to destination pole using source pole as// temporary (auxiliary) poletower(n - 1, auxiliaryPole, destinationPole, sourcePole);} // Driver codeint main(){ tower(3, 'S', 'D', 'A'); return 0;} // This code is contributed by SHUBHAMSINGH10 #include<stdio.h> // Assuming n-th disk is bottom disk (count down)void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole){ // Base case (termination condition) if(0 == n) return; // Move first n-1 disks from source pole // to auxiliary pole using destination as // temporary pole tower(n-1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source // pole to destination pole printf("Move the disk %d from %c to %c\n", n,sourcePole, destinationPole); // Move the n-1 disks from auxiliary (now source) // pole to destination pole using source pole as // temporary (auxiliary) pole tower(n-1, auxiliaryPole, destinationPole, sourcePole);} int main(){ tower(3, 'S', 'D', 'A'); return 0;} // Assuming n-th disk is// bottom disk (count down)class GFG { static void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole){ // Base case (termination condition) if (0 == n) return; // Move first n-1 disks from source pole // to auxiliary pole using destination as // temporary pole tower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source // pole to destination pole System.out.printf("Move the disk %d from %c to %c\n", n, sourcePole, destinationPole); // Move the n-1 disks from auxiliary (now source) // pole to destination pole using source pole as // temporary (auxiliary) pole tower(n - 1, auxiliaryPole, destinationPole, sourcePole);} public static void main(String[] args){ tower(3, 'S', 'D', 'A');}} // This code is contributed by Smitha Dinesh Semwal. # Assuming n-th disk is# bottom disk (count down)def tower(n, sourcePole, destinationPole, auxiliaryPole): # Base case (termination condition) if(0 == n): return # Move first n-1 disks # from source pole # to auxiliary pole # using destination as # temporary pole tower(n-1, sourcePole, auxiliaryPole, destinationPole) # Move the remaining # disk from source # pole to destination pole print("Move the disk",sourcePole,"from",sourcePole,"to",destinationPole) # Move the n-1 disks from # auxiliary (now source) # pole to destination pole # using source pole as # temporary (auxiliary) pole tower(n-1, auxiliaryPole, destinationPole,sourcePole) # Driver codetower(3, 'S', 'D', 'A') // Assuming n-th disk is bottom disk// (count down)using System; class GFG { static void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole) { // Base case (termination condition) if (0 == n) return; // Move first n-1 disks from source // pole to auxiliary pole using // destination as temporary pole tower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source // pole to destination pole Console.WriteLine("Move the disk " + n + "from " + sourcePole + "to " + destinationPole); // Move the n-1 disks from auxiliary // (now source) pole to destination // pole using source pole as temporary // (auxiliary) pole tower(n - 1, auxiliaryPole, destinationPole, sourcePole); } // Driver code public static void Main() { tower(3, 'S', 'D', 'A'); }} // This code is contributed by Anant Agarwal. <?php// Assuming n-th disk is// bottom disk (count down) function tower($n, $sourcePole, $destinationPole, $auxiliaryPole){ // Base case // (termination condition) if(0 == $n) return; // Move first n-1 disks // from source pole to // auxiliary pole using // destination as temporary // pole tower($n - 1, $sourcePole, $auxiliaryPole, $destinationPole); // Move the remaining // disk from source // pole to destination pole echo "Move the disk ", $n, " from ", $sourcePole, " to ", $destinationPole, "\n"; // Move the n-1 disks from // auxiliary (now source) // pole to destination pole // using source pole as // temporary (auxiliary) pole tower($n - 1, $auxiliaryPole, $destinationPole, $sourcePole);} // Driver Codetower(3, 'S', 'D', 'A'); // This code is contributed by Ajit.?> <script> // Assuming n-th disk is bottom disk (count down)function tower(n, sourcePole, destinationPole, auxiliaryPole){ // Base case (termination condition)if(0 == n) return; // Move first n-1 disks from source pole// to auxiliary pole using destination as// temporary poletower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source// pole to destination poledocument.write("Move the disk " + n + " from " + sourcePole + n + " to " + destinationPole + "<br>"); // Move the n-1 disks from auxiliary (now source)// pole to destination pole using source pole as// temporary (auxiliary) poletower(n - 1, auxiliaryPole, destinationPole, sourcePole);} // Driver codetower(3, 'S', 'D', 'A'); // This code is contributed by Manoj </script> Output: Move the disk 1 from S to D Move the disk 2 from S to A Move the disk 1 from D to A Move the disk 3 from S to D Move the disk 1 from A to S Move the disk 2 from A to D Move the disk 1 from S to D The time complexity of TOH can be calculated by formulating the number of moves.We need to move the first N-1 disks from Source to Auxiliary and from Auxiliary to Destination, i.e. the first N-1 disk requires two moves. One more move of the last disk from Source to Destination. Mathematically, it can be defined recursively.MN = 2MN-1 + 1.We can easily solve the above recursive relation (2N-1), which is exponential. Recursion using mutual function call: (Indirect way) Indirect calling. Though least practical, a function [funA()] can call another function [funB()] which in turn calls [funA()] the former function. In this case, both the functions should have the base case.Defensive Programming:We can combine defensive coding techniques with recursion for the graceful functionality of the application. Usually, recursive programming is not allowed in safety-critical applications, such as flight controls, health monitoring, etc. However, one can use a static count technique to avoid uncontrolled calls (NOT in safety-critical systems, but may be used in soft real-time systems). C++ C Java Python3 C# Javascript void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;} // This code is contributed by rutvik_56 void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;} static void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;} // This code is contributed by divyeh072019 def recursive(data): callDepth = 0 if(callDepth > MAX_DEPTH): return; # Increase call depth callDepth+=1 # do other processing recursive(data); # do other processing # Decrease call depth callDepth -= 1 # This code is contributed by Pratham76 static void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;} // This code is contributed by divyeshrabadiya07 <script>//Javascript Implementationfunction recursive(data){ const callDepth = 0; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;}// This code is contributed by shubhamsingh10</script> callDepth depth depends on function stack frame size and maximum stack size. Recursion using function pointers: (Indirect way) Recursion can also implemented with function pointers. An example is a signal handler in POSIX compliant systems. If the handler causes to trigger the same event due to which the handler being called, the function will reenter. jit_t RishabhPrabhu SHUBHAMSINGH10 divyeshrabadiya07 divyesh072019 pratham76 rutvik_56 mank1083 Articles Misc Recursion Misc Recursion Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Class and Object Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
[ { "code": null, "e": 25705, "s": 25677, "text": "\n26 May, 2021" }, { "code": null, "e": 26320, "s": 25705, "text": "Recursion:In programming terms, a recursive function can be defined as a routine that calls itself directly or indirectly.Using the recursive algorithm, certain problems can be solved quite easily. Towers of Hanoi (TOH) is one such programming exercise. Try to write an iterative algorithm for TOH. Moreover, every recursive program can be written using iterative methods.Mathematically, recursion helps to solve a few puzzles easily.For example, a routine interview question,In a party of N people, each person will shake her/his hand with each other person only once. In total how many hand-shakes would happen? " }, { "code": null, "e": 27578, "s": 26320, "text": "Solution:It can be solved in different ways; graphs, recursions, etc. Let us see how recursively it can be solved.There are N persons. Each person shakes hands with each other only once. Considering N-th person, (s)he has to shake a hand with (N-1) the person. Now the problem is reduced to small instances of (N-1) persons. Assuming TN as a total shake-hands, it can be formulated recursively.TN = (N-1) + TN-1 [T1 = 0, i.e. the last person has already shook-hand with every one]Solving it recursively yields an arithmetic series, which can be evaluated into N(N-1)/2.Exercise: In a party of N couples, only one gender (either male or female) can shake hands with everyone. How many shake-hands would happen?Usually, recursive programs result in poor time complexity. An example is a Fibonacci series. The time complexity of calculating the n-th Fibonacci number using recursion is approximately 1.6n. It means the same computer takes almost 60% more time for the next Fibonacci number. The recursive Fibonacci algorithm has overlapping subproblems. There are other techniques like dynamic programming to improve such overlapped algorithms.However, a few algorithms, (e.g. merge sort, quick sort, etc...) result in optimal time complexity using recursion. " }, { "code": null, "e": 27819, "s": 27578, "text": "Base Case:One critical requirement of recursive functions is the termination point or base case. Every recursive program must have a base case to make sure that the function will terminate. Missing base case results in unexpected behavior. " }, { "code": null, "e": 28064, "s": 27819, "text": "Different Ways of Writing Recursive Functions Function calling itself: (Direct way) Most of us are aware of at least two different ways of writing recursive programs. Given below are towers of the Hanoi code. It is an example of direct calling." }, { "code": null, "e": 28068, "s": 28064, "text": "C++" }, { "code": null, "e": 28070, "s": 28068, "text": "C" }, { "code": null, "e": 28075, "s": 28070, "text": "Java" }, { "code": null, "e": 28083, "s": 28075, "text": "Python3" }, { "code": null, "e": 28086, "s": 28083, "text": "C#" }, { "code": null, "e": 28090, "s": 28086, "text": "PHP" }, { "code": null, "e": 28101, "s": 28090, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Assuming n-th disk is bottom disk (count down)void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole){ // Base case (termination condition)if(0 == n) return; // Move first n-1 disks from source pole// to auxiliary pole using destination as// temporary poletower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source// pole to destination polecout << \"Move the disk \"<< n << \" from \" << sourcePole <<\" to \"<< destinationPole << endl; // Move the n-1 disks from auxiliary (now source)// pole to destination pole using source pole as// temporary (auxiliary) poletower(n - 1, auxiliaryPole, destinationPole, sourcePole);} // Driver codeint main(){ tower(3, 'S', 'D', 'A'); return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 28971, "s": 28101, "text": null }, { "code": "#include<stdio.h> // Assuming n-th disk is bottom disk (count down)void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole){ // Base case (termination condition) if(0 == n) return; // Move first n-1 disks from source pole // to auxiliary pole using destination as // temporary pole tower(n-1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source // pole to destination pole printf(\"Move the disk %d from %c to %c\\n\", n,sourcePole, destinationPole); // Move the n-1 disks from auxiliary (now source) // pole to destination pole using source pole as // temporary (auxiliary) pole tower(n-1, auxiliaryPole, destinationPole, sourcePole);} int main(){ tower(3, 'S', 'D', 'A'); return 0;}", "e": 29759, "s": 28971, "text": null }, { "code": "// Assuming n-th disk is// bottom disk (count down)class GFG { static void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole){ // Base case (termination condition) if (0 == n) return; // Move first n-1 disks from source pole // to auxiliary pole using destination as // temporary pole tower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source // pole to destination pole System.out.printf(\"Move the disk %d from %c to %c\\n\", n, sourcePole, destinationPole); // Move the n-1 disks from auxiliary (now source) // pole to destination pole using source pole as // temporary (auxiliary) pole tower(n - 1, auxiliaryPole, destinationPole, sourcePole);} public static void main(String[] args){ tower(3, 'S', 'D', 'A');}} // This code is contributed by Smitha Dinesh Semwal.", "e": 30703, "s": 29759, "text": null }, { "code": "# Assuming n-th disk is# bottom disk (count down)def tower(n, sourcePole, destinationPole, auxiliaryPole): # Base case (termination condition) if(0 == n): return # Move first n-1 disks # from source pole # to auxiliary pole # using destination as # temporary pole tower(n-1, sourcePole, auxiliaryPole, destinationPole) # Move the remaining # disk from source # pole to destination pole print(\"Move the disk\",sourcePole,\"from\",sourcePole,\"to\",destinationPole) # Move the n-1 disks from # auxiliary (now source) # pole to destination pole # using source pole as # temporary (auxiliary) pole tower(n-1, auxiliaryPole, destinationPole,sourcePole) # Driver codetower(3, 'S', 'D', 'A')", "e": 31461, "s": 30703, "text": null }, { "code": "// Assuming n-th disk is bottom disk// (count down)using System; class GFG { static void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole) { // Base case (termination condition) if (0 == n) return; // Move first n-1 disks from source // pole to auxiliary pole using // destination as temporary pole tower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source // pole to destination pole Console.WriteLine(\"Move the disk \" + n + \"from \" + sourcePole + \"to \" + destinationPole); // Move the n-1 disks from auxiliary // (now source) pole to destination // pole using source pole as temporary // (auxiliary) pole tower(n - 1, auxiliaryPole, destinationPole, sourcePole); } // Driver code public static void Main() { tower(3, 'S', 'D', 'A'); }} // This code is contributed by Anant Agarwal.", "e": 32617, "s": 31461, "text": null }, { "code": "<?php// Assuming n-th disk is// bottom disk (count down) function tower($n, $sourcePole, $destinationPole, $auxiliaryPole){ // Base case // (termination condition) if(0 == $n) return; // Move first n-1 disks // from source pole to // auxiliary pole using // destination as temporary // pole tower($n - 1, $sourcePole, $auxiliaryPole, $destinationPole); // Move the remaining // disk from source // pole to destination pole echo \"Move the disk \", $n, \" from \", $sourcePole, \" to \", $destinationPole, \"\\n\"; // Move the n-1 disks from // auxiliary (now source) // pole to destination pole // using source pole as // temporary (auxiliary) pole tower($n - 1, $auxiliaryPole, $destinationPole, $sourcePole);} // Driver Codetower(3, 'S', 'D', 'A'); // This code is contributed by Ajit.?>", "e": 33589, "s": 32617, "text": null }, { "code": "<script> // Assuming n-th disk is bottom disk (count down)function tower(n, sourcePole, destinationPole, auxiliaryPole){ // Base case (termination condition)if(0 == n) return; // Move first n-1 disks from source pole// to auxiliary pole using destination as// temporary poletower(n - 1, sourcePole, auxiliaryPole, destinationPole); // Move the remaining disk from source// pole to destination poledocument.write(\"Move the disk \" + n + \" from \" + sourcePole + n + \" to \" + destinationPole + \"<br>\"); // Move the n-1 disks from auxiliary (now source)// pole to destination pole using source pole as// temporary (auxiliary) poletower(n - 1, auxiliaryPole, destinationPole, sourcePole);} // Driver codetower(3, 'S', 'D', 'A'); // This code is contributed by Manoj </script>", "e": 34390, "s": 33589, "text": null }, { "code": null, "e": 34400, "s": 34390, "text": "Output: " }, { "code": null, "e": 34596, "s": 34400, "text": "Move the disk 1 from S to D\nMove the disk 2 from S to A\nMove the disk 1 from D to A\nMove the disk 3 from S to D\nMove the disk 1 from A to S\nMove the disk 2 from A to D\nMove the disk 1 from S to D" }, { "code": null, "e": 35017, "s": 34596, "text": "The time complexity of TOH can be calculated by formulating the number of moves.We need to move the first N-1 disks from Source to Auxiliary and from Auxiliary to Destination, i.e. the first N-1 disk requires two moves. One more move of the last disk from Source to Destination. Mathematically, it can be defined recursively.MN = 2MN-1 + 1.We can easily solve the above recursive relation (2N-1), which is exponential. " }, { "code": null, "e": 35687, "s": 35017, "text": "Recursion using mutual function call: (Indirect way) Indirect calling. Though least practical, a function [funA()] can call another function [funB()] which in turn calls [funA()] the former function. In this case, both the functions should have the base case.Defensive Programming:We can combine defensive coding techniques with recursion for the graceful functionality of the application. Usually, recursive programming is not allowed in safety-critical applications, such as flight controls, health monitoring, etc. However, one can use a static count technique to avoid uncontrolled calls (NOT in safety-critical systems, but may be used in soft real-time systems). " }, { "code": null, "e": 35691, "s": 35687, "text": "C++" }, { "code": null, "e": 35693, "s": 35691, "text": "C" }, { "code": null, "e": 35698, "s": 35693, "text": "Java" }, { "code": null, "e": 35706, "s": 35698, "text": "Python3" }, { "code": null, "e": 35709, "s": 35706, "text": "C#" }, { "code": null, "e": 35720, "s": 35709, "text": "Javascript" }, { "code": "void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;} // This code is contributed by rutvik_56", "e": 36004, "s": 35720, "text": null }, { "code": "void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;}", "e": 36244, "s": 36004, "text": null }, { "code": "static void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;} // This code is contributed by divyeh072019", "e": 36544, "s": 36244, "text": null }, { "code": "def recursive(data): callDepth = 0 if(callDepth > MAX_DEPTH): return; # Increase call depth callDepth+=1 # do other processing recursive(data); # do other processing # Decrease call depth callDepth -= 1 # This code is contributed by Pratham76", "e": 36823, "s": 36544, "text": null }, { "code": "static void recursive(int data){ static callDepth; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;} // This code is contributed by divyeshrabadiya07", "e": 37125, "s": 36823, "text": null }, { "code": "<script>//Javascript Implementationfunction recursive(data){ const callDepth = 0; if(callDepth > MAX_DEPTH) return; // Increase call depth callDepth++; // do other processing recursive(data); // do other processing // Decrease call depth callDepth--;}// This code is contributed by shubhamsingh10</script>", "e": 37464, "s": 37125, "text": null }, { "code": null, "e": 37542, "s": 37464, "text": "callDepth depth depends on function stack frame size and maximum stack size. " }, { "code": null, "e": 37821, "s": 37542, "text": "Recursion using function pointers: (Indirect way) Recursion can also implemented with function pointers. An example is a signal handler in POSIX compliant systems. If the handler causes to trigger the same event due to which the handler being called, the function will reenter. " }, { "code": null, "e": 37827, "s": 37821, "text": "jit_t" }, { "code": null, "e": 37841, "s": 37827, "text": "RishabhPrabhu" }, { "code": null, "e": 37856, "s": 37841, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 37874, "s": 37856, "text": "divyeshrabadiya07" }, { "code": null, "e": 37888, "s": 37874, "text": "divyesh072019" }, { "code": null, "e": 37898, "s": 37888, "text": "pratham76" }, { "code": null, "e": 37908, "s": 37898, "text": "rutvik_56" }, { "code": null, "e": 37917, "s": 37908, "text": "mank1083" }, { "code": null, "e": 37926, "s": 37917, "text": "Articles" }, { "code": null, "e": 37931, "s": 37926, "text": "Misc" }, { "code": null, "e": 37941, "s": 37931, "text": "Recursion" }, { "code": null, "e": 37946, "s": 37941, "text": "Misc" }, { "code": null, "e": 37956, "s": 37946, "text": "Recursion" }, { "code": null, "e": 37961, "s": 37956, "text": "Misc" }, { "code": null, "e": 38059, "s": 37961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38096, "s": 38059, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 38122, "s": 38096, "text": "Docker - COPY Instruction" }, { "code": null, "e": 38169, "s": 38122, "text": "Time complexities of different data structures" }, { "code": null, "e": 38190, "s": 38169, "text": "SQL | Date functions" }, { "code": null, "e": 38226, "s": 38190, "text": "Difference between Class and Object" }, { "code": null, "e": 38267, "s": 38226, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 38321, "s": 38267, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 38382, "s": 38321, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 38416, "s": 38382, "text": "How to write Regular Expressions?" } ]
Selenium Base Mini Project Using Python - GeeksforGeeks
04 Jan, 2021 Project Description:-Here, we’re going to study a simple SMS bomber trick (for amusing and educational purpose). Selenium is a free tool for automated trying out across exceptional browsers. In this tutorial, we will learn how to ship mechanically range of unsolicited mail SMS for given variety of frequency and interval. Requirement: You need to install chromedriver and set path. Click here to download.for more information follow this link. Below are the steps: First go to amazon website using this Link.Then click on investigate element by urgent ctrl + shift + i or stepping into setting of browser and clicking on investigate detail manually.Then navigate box where the friend mobile number are fill then copy the x_path.Then navigate the continue button then copy the x_path.Then navigate the forget password then copy the x_path.Then again step 3 repeat.Then again step 4 repeat. First go to amazon website using this Link. Then click on investigate element by urgent ctrl + shift + i or stepping into setting of browser and clicking on investigate detail manually. Then navigate box where the friend mobile number are fill then copy the x_path. Then navigate the continue button then copy the x_path. Then navigate the forget password then copy the x_path. Then again step 3 repeat. Then again step 4 repeat. Given some screenshot to follow this instruction step by step: Step 1- Step 2- Step 3- Step 4- Step 5- Step 6- Now, Run the script by way of putting suitable x_path and automatically send junk mail sms for your friend’s cellular number. Note: This tutorial is for educational motive only, please don’t use it for disturbing anyone or any unethical way. Below is the implementation: from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport timefor i in range(20): # create instance of Chrome webdriver driver=webdriver.Chrome() driver.get("https://www.amazon.in/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.in%2Fgp%2Fcss%2Fhomepage.html%3Ffrom%3Dhz%26ref_%3Dnav_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=inflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&") # find the element where we have to # enter the xpath # target mobile number, change it to victim's number and # also ensure that it's registered on flipkart driver.find_element_by_xpath('//*[@id="ap_email"]').send_keys('xxxx6126') # find the element continue # request using xpath # clicking on that element driver.find_element_by_xpath('//*[@id="continue"]').click() # find the element to send a forgot password # request using xpath driver.find_element_by_xpath('//*[@id="auth-fpp-link-bottom"]').click() driver.find_element_by_xpath('//*[@id="continue"]').click() # set the interval to send each sms time.sleep(4) # Close the browser driver.close() Python Selenium-Exercises Python-projects Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n04 Jan, 2021" }, { "code": null, "e": 25885, "s": 25562, "text": "Project Description:-Here, we’re going to study a simple SMS bomber trick (for amusing and educational purpose). Selenium is a free tool for automated trying out across exceptional browsers. In this tutorial, we will learn how to ship mechanically range of unsolicited mail SMS for given variety of frequency and interval." }, { "code": null, "e": 25898, "s": 25885, "text": "Requirement:" }, { "code": null, "e": 26007, "s": 25898, "text": "You need to install chromedriver and set path. Click here to download.for more information follow this link." }, { "code": null, "e": 26028, "s": 26007, "text": "Below are the steps:" }, { "code": null, "e": 26452, "s": 26028, "text": "First go to amazon website using this Link.Then click on investigate element by urgent ctrl + shift + i or stepping into setting of browser and clicking on investigate detail manually.Then navigate box where the friend mobile number are fill then copy the x_path.Then navigate the continue button then copy the x_path.Then navigate the forget password then copy the x_path.Then again step 3 repeat.Then again step 4 repeat." }, { "code": null, "e": 26496, "s": 26452, "text": "First go to amazon website using this Link." }, { "code": null, "e": 26638, "s": 26496, "text": "Then click on investigate element by urgent ctrl + shift + i or stepping into setting of browser and clicking on investigate detail manually." }, { "code": null, "e": 26718, "s": 26638, "text": "Then navigate box where the friend mobile number are fill then copy the x_path." }, { "code": null, "e": 26774, "s": 26718, "text": "Then navigate the continue button then copy the x_path." }, { "code": null, "e": 26830, "s": 26774, "text": "Then navigate the forget password then copy the x_path." }, { "code": null, "e": 26856, "s": 26830, "text": "Then again step 3 repeat." }, { "code": null, "e": 26882, "s": 26856, "text": "Then again step 4 repeat." }, { "code": null, "e": 26946, "s": 26882, "text": "Given some screenshot to follow this instruction step by step:" }, { "code": null, "e": 26954, "s": 26946, "text": "Step 1-" }, { "code": null, "e": 26962, "s": 26954, "text": "Step 2-" }, { "code": null, "e": 26970, "s": 26962, "text": "Step 3-" }, { "code": null, "e": 26978, "s": 26970, "text": "Step 4-" }, { "code": null, "e": 26986, "s": 26978, "text": "Step 5-" }, { "code": null, "e": 26994, "s": 26986, "text": "Step 6-" }, { "code": null, "e": 27121, "s": 26994, "text": "Now, Run the script by way of putting suitable x_path and automatically send junk mail sms for your friend’s cellular number." }, { "code": null, "e": 27237, "s": 27121, "text": "Note: This tutorial is for educational motive only, please don’t use it for disturbing anyone or any unethical way." }, { "code": null, "e": 27266, "s": 27237, "text": "Below is the implementation:" }, { "code": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport timefor i in range(20): # create instance of Chrome webdriver driver=webdriver.Chrome() driver.get(\"https://www.amazon.in/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.in%2Fgp%2Fcss%2Fhomepage.html%3Ffrom%3Dhz%26ref_%3Dnav_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=inflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&\") # find the element where we have to # enter the xpath # target mobile number, change it to victim's number and # also ensure that it's registered on flipkart driver.find_element_by_xpath('//*[@id=\"ap_email\"]').send_keys('xxxx6126') # find the element continue # request using xpath # clicking on that element driver.find_element_by_xpath('//*[@id=\"continue\"]').click() # find the element to send a forgot password # request using xpath driver.find_element_by_xpath('//*[@id=\"auth-fpp-link-bottom\"]').click() driver.find_element_by_xpath('//*[@id=\"continue\"]').click() # set the interval to send each sms time.sleep(4) # Close the browser driver.close()", "e": 28616, "s": 27266, "text": null }, { "code": null, "e": 28642, "s": 28616, "text": "Python Selenium-Exercises" }, { "code": null, "e": 28658, "s": 28642, "text": "Python-projects" }, { "code": null, "e": 28674, "s": 28658, "text": "Python-selenium" }, { "code": null, "e": 28681, "s": 28674, "text": "Python" }, { "code": null, "e": 28779, "s": 28681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28811, "s": 28779, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28853, "s": 28811, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28895, "s": 28853, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28922, "s": 28895, "text": "Python Classes and Objects" }, { "code": null, "e": 28978, "s": 28922, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29017, "s": 28978, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29039, "s": 29017, "text": "Defaultdict in Python" }, { "code": null, "e": 29070, "s": 29039, "text": "Python | os.path.join() method" }, { "code": null, "e": 29099, "s": 29070, "text": "Create a directory in Python" } ]
Print Strings without Quotes in R Programming - noquote() Function - GeeksforGeeks
01 Jun, 2020 noquote() function in R Language is used to prints strings without quotes. Syntax: noquote(x) Parameters:x: character vector Example 1: # R program to illustrate# noquote function # Getting letters without the help# of noquote() functionletters # Getting letters with the help# of noquote() functionnoquote(letters) Output : [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" [20] "t" "u" "v" "w" "x" "y" "z" [1] a b c d e f g h i j k l m n o p q r s t u v w x y z Example 2: # R program to illustrate# noquote function # Initializing a stringx <- "GFG" # Getting the string without the help# of noquote() functionx # Getting the string with the help# of noquote() functionnoquote(x) Output: [1] "GFG" [1] GFG R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? R Programming Language - Introduction K-Means Clustering in R Programming
[ { "code": null, "e": 26741, "s": 26713, "text": "\n01 Jun, 2020" }, { "code": null, "e": 26816, "s": 26741, "text": "noquote() function in R Language is used to prints strings without quotes." }, { "code": null, "e": 26835, "s": 26816, "text": "Syntax: noquote(x)" }, { "code": null, "e": 26866, "s": 26835, "text": "Parameters:x: character vector" }, { "code": null, "e": 26877, "s": 26866, "text": "Example 1:" }, { "code": "# R program to illustrate# noquote function # Getting letters without the help# of noquote() functionletters # Getting letters with the help# of noquote() functionnoquote(letters)", "e": 27059, "s": 26877, "text": null }, { "code": null, "e": 27068, "s": 27059, "text": "Output :" }, { "code": null, "e": 27238, "s": 27068, "text": "[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\"\n[20] \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"\n[1] a b c d e f g h i j k l m n o p q r s t u v w x y z\n" }, { "code": null, "e": 27249, "s": 27238, "text": "Example 2:" }, { "code": "# R program to illustrate# noquote function # Initializing a stringx <- \"GFG\" # Getting the string without the help# of noquote() functionx # Getting the string with the help# of noquote() functionnoquote(x)", "e": 27460, "s": 27249, "text": null }, { "code": null, "e": 27468, "s": 27460, "text": "Output:" }, { "code": null, "e": 27487, "s": 27468, "text": "[1] \"GFG\"\n[1] GFG\n" }, { "code": null, "e": 27506, "s": 27487, "text": "R String-Functions" }, { "code": null, "e": 27517, "s": 27506, "text": "R Language" }, { "code": null, "e": 27615, "s": 27517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27673, "s": 27615, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27725, "s": 27673, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27757, "s": 27725, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27809, "s": 27757, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27853, "s": 27809, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27888, "s": 27853, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27926, "s": 27888, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27984, "s": 27926, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28022, "s": 27984, "text": "R Programming Language - Introduction" } ]
How to delete text from file using preg_replace() function in PHP ? - GeeksforGeeks
14 Feb, 2020 Given a file containing some elements and the task is to delete the content of the file using preg_replace() function. The preg_replace() function is searches the string pattern in the file and if string pattern found then it replace with the required string. In simple words it can modify the contents of a file. Syntax: preg_replace( $pattern, $replacement, $subject); Parameters: $pattern: It contains the string we have to replace. $replacement: It contains the string that will replace the existing string. $subject: It contains the main string file where need to remove the string. We have created a text file named as fruits.txtfruits.txt mango apple papaya guava apple grapes mango apple Program 1: This program removes all the strings from the given file. <?php $a = 'fruits.txt';$b = file_get_contents('fruits.txt');echo "File contents before using " . "preg_replace() function<br>";echo $b;echo "<br><br>File contents after using " . "preg_replace() function<br> ";$c = preg_replace('/[a-z]/', '', $b);echo $c;file_put_contents($a, $c);?> Output: File contents before using preg_replace() function mango apple papaya guava apple grapes mango apple File contents after using preg_replace() function Program 2: This program deletes a specific content from the file using preg_replace() function. <?php $a = 'fruits.txt'; $b = file_get_contents('fruits.txt'); echo "File contents before using " + "preg_replace() function<br>";echo $b; echo "<br><br>File contents after using " + "preg_replace() function<br>"; $c = preg_replace('/[a]/', '', $b);echo $c; file_put_contents($a, $c); ?> Output: File contents before using preg_replace() function mango apple papaya guava apple grapes mango apple File contents after using preg_replace() function mngo pple ppy guv pple grpes mngo pple Program 3: This program deletes the entire word from the file. <?php $a = 'fruits.txt'; $b = file_get_contents('fruits.txt'); echo "File contents before using " . "preg_replace() function<br>";echo $b; echo "<br><br>File contents after using " . "preg_replace() function<br>"; $c = preg_replace('/apple/', '', $b);echo $c; file_put_contents($a, $c); ?> Output: File contents before using preg_replace() function mango apple papaya guava apple grapes mango apple File contents after using preg_replace() function mango papaya guava grapes mango PHP-function PHP-Misc Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Different ways for passing data to view in Laravel Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26217, "s": 26189, "text": "\n14 Feb, 2020" }, { "code": null, "e": 26531, "s": 26217, "text": "Given a file containing some elements and the task is to delete the content of the file using preg_replace() function. The preg_replace() function is searches the string pattern in the file and if string pattern found then it replace with the required string. In simple words it can modify the contents of a file." }, { "code": null, "e": 26539, "s": 26531, "text": "Syntax:" }, { "code": null, "e": 26589, "s": 26539, "text": "preg_replace( $pattern, $replacement, $subject);" }, { "code": null, "e": 26601, "s": 26589, "text": "Parameters:" }, { "code": null, "e": 26654, "s": 26601, "text": "$pattern: It contains the string we have to replace." }, { "code": null, "e": 26730, "s": 26654, "text": "$replacement: It contains the string that will replace the existing string." }, { "code": null, "e": 26806, "s": 26730, "text": "$subject: It contains the main string file where need to remove the string." }, { "code": null, "e": 26864, "s": 26806, "text": "We have created a text file named as fruits.txtfruits.txt" }, { "code": null, "e": 26914, "s": 26864, "text": "mango\napple\npapaya\nguava\napple\ngrapes\nmango\napple" }, { "code": null, "e": 26983, "s": 26914, "text": "Program 1: This program removes all the strings from the given file." }, { "code": "<?php $a = 'fruits.txt';$b = file_get_contents('fruits.txt');echo \"File contents before using \" . \"preg_replace() function<br>\";echo $b;echo \"<br><br>File contents after using \" . \"preg_replace() function<br> \";$c = preg_replace('/[a-z]/', '', $b);echo $c;file_put_contents($a, $c);?>", "e": 27283, "s": 26983, "text": null }, { "code": null, "e": 27291, "s": 27283, "text": "Output:" }, { "code": null, "e": 27443, "s": 27291, "text": "File contents before using preg_replace() function\nmango apple papaya guava apple grapes mango apple\n\nFile contents after using preg_replace() function" }, { "code": null, "e": 27539, "s": 27443, "text": "Program 2: This program deletes a specific content from the file using preg_replace() function." }, { "code": "<?php $a = 'fruits.txt'; $b = file_get_contents('fruits.txt'); echo \"File contents before using \" + \"preg_replace() function<br>\";echo $b; echo \"<br><br>File contents after using \" + \"preg_replace() function<br>\"; $c = preg_replace('/[a]/', '', $b);echo $c; file_put_contents($a, $c); ?>", "e": 27848, "s": 27539, "text": null }, { "code": null, "e": 27856, "s": 27848, "text": "Output:" }, { "code": null, "e": 28047, "s": 27856, "text": "File contents before using preg_replace() function\nmango apple papaya guava apple grapes mango apple\n\nFile contents after using preg_replace() function\nmngo pple ppy guv pple grpes mngo pple" }, { "code": null, "e": 28110, "s": 28047, "text": "Program 3: This program deletes the entire word from the file." }, { "code": "<?php $a = 'fruits.txt'; $b = file_get_contents('fruits.txt'); echo \"File contents before using \" . \"preg_replace() function<br>\";echo $b; echo \"<br><br>File contents after using \" . \"preg_replace() function<br>\"; $c = preg_replace('/apple/', '', $b);echo $c; file_put_contents($a, $c); ?>", "e": 28421, "s": 28110, "text": null }, { "code": null, "e": 28429, "s": 28421, "text": "Output:" }, { "code": null, "e": 28613, "s": 28429, "text": "File contents before using preg_replace() function\nmango apple papaya guava apple grapes mango apple\n\nFile contents after using preg_replace() function\nmango papaya guava grapes mango" }, { "code": null, "e": 28626, "s": 28613, "text": "PHP-function" }, { "code": null, "e": 28635, "s": 28626, "text": "PHP-Misc" }, { "code": null, "e": 28642, "s": 28635, "text": "Picked" }, { "code": null, "e": 28646, "s": 28642, "text": "PHP" }, { "code": null, "e": 28663, "s": 28646, "text": "Web Technologies" }, { "code": null, "e": 28690, "s": 28663, "text": "Web technologies Questions" }, { "code": null, "e": 28694, "s": 28690, "text": "PHP" }, { "code": null, "e": 28792, "s": 28694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28874, "s": 28792, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28916, "s": 28874, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 28943, "s": 28916, "text": "PHP str_replace() Function" }, { "code": null, "e": 29007, "s": 28943, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 29058, "s": 29007, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 29098, "s": 29058, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29131, "s": 29098, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29176, "s": 29131, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29219, "s": 29176, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use SQLMAP to test a website for SQL Injection vulnerability - GeeksforGeeks
28 Jun, 2021 This article explains how to test whether a website is safe from SQL injection using the SQLMAP penetration testing tool. What is SQL Injection? SQL Injection is a code injection technique where an attacker executes malicious SQL queries that control a web application’s database. With the right set of queries, a user can gain access to information stored in databases. SQLMAP tests whether a ‘GET’ parameter is vulnerable to SQL Injection. For example, Consider the following php code segment: $variable = $_POST['input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$variable')"); If the user enters “value’); DROP TABLE table;–” as the input, the query becomes INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--') which is undesirable for us, as here the user input is directly compiled along with the pre written sql query. Hence the user will be able to enter an sql query required to manipulate the database. Where can you use SQLMAP? If you observe a web url that is of the form http://testphp.vulnweb.com/listproducts.php?cat=1, where the ‘GET’ parameter is in bold, then the website may be vulnerable to this mode of SQL injection, and an attacker may be able to gain access to information in the database. Furthermore, SQLMAP works when it is php based. A simple test to check whether your website is vulnerable would to be to replace the value in the get request parameter with an asterisk (*). For example, http://testphp.vulnweb.com/listproducts.php?cat=* If this results in an error such as the error given above, then we can conclusively say that the website is vulnerable. Installing sqlmap SQLMAP comes pre – installed with kali linux, which is the preferred choice of most penetration testers. However, you can install sqlmap on other debian based linux systems using the command sudo apt-get install sqlmap Usage In this article, we will make use of a website that is designed with vulnerabilities for demonstration purposes: http://testphp.vulnweb.com/listproducts.php?cat=1 As you can see, there is a GET request parameter (cat = 1) that can be changed by the user by modifying the value of cat. So this website might be vulnerable to SQL injection of this kind. To test for this, we use SQLMAP. To look at the set of parameters that can be passed, type in the terminal, sqlmap -h The parameters that we will use for the basic SQL Injection are shown in the above picture. Along with these, we will also use the –dbs and -u parameter, the usage of which has been explained in Step 1. Using SQLMAP to test a website for SQL Injection vulnerability: Step 1: List information about the existing databases So firstly, we have to enter the web url that we want to check along with the -u parameter. We may also use the –tor parameter if we wish to test the website using proxies. Now typically, we would want to test whether it is possible to gain access to a database. So we use the –dbs option to do so. –dbs lists all the available databases. Step 1: List information about the existing databases So firstly, we have to enter the web url that we want to check along with the -u parameter. We may also use the –tor parameter if we wish to test the website using proxies. Now typically, we would want to test whether it is possible to gain access to a database. So we use the –dbs option to do so. –dbs lists all the available databases. sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dbs We get the following output showing us that there are two available databases. Sometimes, the application will tell you that it has identified the database and ask whether you want to test other database types. You can go ahead and type ‘Y’. Further, it may ask whether you want to test other parameters for vulnerabilities, type ‘Y’ over here as we want to thoroughly test the web application. We get the following output showing us that there are two available databases. Sometimes, the application will tell you that it has identified the database and ask whether you want to test other database types. You can go ahead and type ‘Y’. Further, it may ask whether you want to test other parameters for vulnerabilities, type ‘Y’ over here as we want to thoroughly test the web application. We observe that their are two databases, acuart and information_schema Step 2: List information about Tables present in a particular Database To try and access any of the databases, we have to slightly modify our command. We now use -D to specify the name of the database that we wish to access, and once we have access to the database, we would want to see whether we can access the tables. For this, we use the –tables query. Let us access the acuart database. We observe that their are two databases, acuart and information_schema Step 2: List information about Tables present in a particular Database To try and access any of the databases, we have to slightly modify our command. We now use -D to specify the name of the database that we wish to access, and once we have access to the database, we would want to see whether we can access the tables. For this, we use the –tables query. Let us access the acuart database. sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart --tables Tables In the above picture, we see that 8 tables have been retrieved. So now we definitely know that the website is vulnerable. Step 3: List information about the columns of a particular table If we want to view the columns of a particular table, we can use the following command, in which we use -T to specify the table name, and –columns to query the column names. We will try to access the table ‘artists’. In the above picture, we see that 8 tables have been retrieved. So now we definitely know that the website is vulnerable. In the above picture, we see that 8 tables have been retrieved. So now we definitely know that the website is vulnerable. Step 3: List information about the columns of a particular table If we want to view the columns of a particular table, we can use the following command, in which we use -T to specify the table name, and –columns to query the column names. We will try to access the table ‘artists’. If we want to view the columns of a particular table, we can use the following command, in which we use -T to specify the table name, and –columns to query the column names. We will try to access the table ‘artists’. sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists --columns Columns Step 4: Dump the data from the columns Similarly, we can access the information in a specific column by using the following command, where -C can be used to specify multiple column name separated by a comma, and the –dump query retrieves the data Step 4: Dump the data from the columns Similarly, we can access the information in a specific column by using the following command, where -C can be used to specify multiple column name separated by a comma, and the –dump query retrieves the data sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists -C aname --dump From the above picture, we can see that we have accessed the data from the database. Similarly, in such vulnerable websites, we can literally explore through the databases to extract information From the above picture, we can see that we have accessed the data from the database. Similarly, in such vulnerable websites, we can literally explore through the databases to extract information Prevent SQL Injection SQL injection can be generally prevented by using Prepared Statements . When we use a prepared statement, we are basically using a template for the code and analyzing the code and user input separately. It does not mix the user entered query and the code. In the example given at the beginning of this article, the input entered by the user is directly inserted into the code and they are compiled together, and hence we are able to execute malicious code. For prepared statements, we basically send the sql query with a placeholder for the user input and then send the actual user input as a separate command. Consider the following php code segment. $db = new PDO('connection details'); $stmt = db->prepare("Select name from users where id = :id"); $stmt->execute(array(':id', $data)); In this code, the user input is not combined with the prepared statement. They are compiled separately. So even if malicious code is entered as user input, the program will simply treat the malicious part of the code as a string and not a command. Note: This application is to be used solely for testing purposes Related Article Basic SQL injection and mitigation Reference:stackoverflow.com This article is contributed by Deepak Srivatsav. 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. simmytarika5 secure-coding sql-injection vulnerability GBlog SQL Web Technologies SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Supervised and Unsupervised learning Differences between Procedural and Object Oriented Programming 12 pip Commands For Python Developers SQL | DDL, DQL, DML, DCL and TCL Commands SQL | WITH clause SQL | Join (Inner, Left, Right and Full Joins) How to find Nth highest salary from a table SQL | ALTER (RENAME)
[ { "code": null, "e": 26044, "s": 26016, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26168, "s": 26044, "text": "This article explains how to test whether a website is safe from SQL injection using the SQLMAP penetration testing tool. " }, { "code": null, "e": 26191, "s": 26168, "text": "What is SQL Injection?" }, { "code": null, "e": 26544, "s": 26191, "text": "SQL Injection is a code injection technique where an attacker executes malicious SQL queries that control a web application’s database. With the right set of queries, a user can gain access to information stored in databases. SQLMAP tests whether a ‘GET’ parameter is vulnerable to SQL Injection. For example, Consider the following php code segment: " }, { "code": null, "e": 26641, "s": 26544, "text": "$variable = $_POST['input'];\nmysql_query(\"INSERT INTO `table` (`column`) VALUES ('$variable')\");" }, { "code": null, "e": 26724, "s": 26641, "text": "If the user enters “value’); DROP TABLE table;–” as the input, the query becomes " }, { "code": null, "e": 26794, "s": 26724, "text": "INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')" }, { "code": null, "e": 26993, "s": 26794, "text": "which is undesirable for us, as here the user input is directly compiled along with the pre written sql query. Hence the user will be able to enter an sql query required to manipulate the database. " }, { "code": null, "e": 27021, "s": 26995, "text": "Where can you use SQLMAP?" }, { "code": null, "e": 27346, "s": 27021, "text": "If you observe a web url that is of the form http://testphp.vulnweb.com/listproducts.php?cat=1, where the ‘GET’ parameter is in bold, then the website may be vulnerable to this mode of SQL injection, and an attacker may be able to gain access to information in the database. Furthermore, SQLMAP works when it is php based. " }, { "code": null, "e": 27503, "s": 27346, "text": "A simple test to check whether your website is vulnerable would to be to replace the value in the get request parameter with an asterisk (*). For example, " }, { "code": null, "e": 27554, "s": 27503, "text": "http://testphp.vulnweb.com/listproducts.php?cat=* " }, { "code": null, "e": 27677, "s": 27556, "text": "If this results in an error such as the error given above, then we can conclusively say that the website is vulnerable. " }, { "code": null, "e": 27697, "s": 27679, "text": "Installing sqlmap" }, { "code": null, "e": 27890, "s": 27697, "text": "SQLMAP comes pre – installed with kali linux, which is the preferred choice of most penetration testers. However, you can install sqlmap on other debian based linux systems using the command " }, { "code": null, "e": 27920, "s": 27890, "text": " sudo apt-get install sqlmap " }, { "code": null, "e": 27928, "s": 27922, "text": "Usage" }, { "code": null, "e": 28043, "s": 27928, "text": "In this article, we will make use of a website that is designed with vulnerabilities for demonstration purposes: " }, { "code": null, "e": 28095, "s": 28043, "text": " http://testphp.vulnweb.com/listproducts.php?cat=1 " }, { "code": null, "e": 28394, "s": 28095, "text": "As you can see, there is a GET request parameter (cat = 1) that can be changed by the user by modifying the value of cat. So this website might be vulnerable to SQL injection of this kind. To test for this, we use SQLMAP. To look at the set of parameters that can be passed, type in the terminal, " }, { "code": null, "e": 28406, "s": 28394, "text": " sqlmap -h " }, { "code": null, "e": 28677, "s": 28408, "text": "The parameters that we will use for the basic SQL Injection are shown in the above picture. Along with these, we will also use the –dbs and -u parameter, the usage of which has been explained in Step 1. Using SQLMAP to test a website for SQL Injection vulnerability: " }, { "code": null, "e": 29072, "s": 28677, "text": "Step 1: List information about the existing databases So firstly, we have to enter the web url that we want to check along with the -u parameter. We may also use the –tor parameter if we wish to test the website using proxies. Now typically, we would want to test whether it is possible to gain access to a database. So we use the –dbs option to do so. –dbs lists all the available databases. " }, { "code": null, "e": 29467, "s": 29072, "text": "Step 1: List information about the existing databases So firstly, we have to enter the web url that we want to check along with the -u parameter. We may also use the –tor parameter if we wish to test the website using proxies. Now typically, we would want to test whether it is possible to gain access to a database. So we use the –dbs option to do so. –dbs lists all the available databases. " }, { "code": null, "e": 29535, "s": 29467, "text": " sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dbs " }, { "code": null, "e": 29938, "s": 29541, "text": "We get the following output showing us that there are two available databases. Sometimes, the application will tell you that it has identified the database and ask whether you want to test other database types. You can go ahead and type ‘Y’. Further, it may ask whether you want to test other parameters for vulnerabilities, type ‘Y’ over here as we want to thoroughly test the web application. " }, { "code": null, "e": 30335, "s": 29938, "text": "We get the following output showing us that there are two available databases. Sometimes, the application will tell you that it has identified the database and ask whether you want to test other database types. You can go ahead and type ‘Y’. Further, it may ask whether you want to test other parameters for vulnerabilities, type ‘Y’ over here as we want to thoroughly test the web application. " }, { "code": null, "e": 30801, "s": 30335, "text": "We observe that their are two databases, acuart and information_schema Step 2: List information about Tables present in a particular Database To try and access any of the databases, we have to slightly modify our command. We now use -D to specify the name of the database that we wish to access, and once we have access to the database, we would want to see whether we can access the tables. For this, we use the –tables query. Let us access the acuart database. " }, { "code": null, "e": 30874, "s": 30801, "text": "We observe that their are two databases, acuart and information_schema " }, { "code": null, "e": 31270, "s": 30876, "text": "Step 2: List information about Tables present in a particular Database To try and access any of the databases, we have to slightly modify our command. We now use -D to specify the name of the database that we wish to access, and once we have access to the database, we would want to see whether we can access the tables. For this, we use the –tables query. Let us access the acuart database. " }, { "code": null, "e": 31352, "s": 31270, "text": " sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 \n-D acuart --tables " }, { "code": null, "e": 31365, "s": 31358, "text": "Tables" }, { "code": null, "e": 31772, "s": 31365, "text": "In the above picture, we see that 8 tables have been retrieved. So now we definitely know that the website is vulnerable. Step 3: List information about the columns of a particular table If we want to view the columns of a particular table, we can use the following command, in which we use -T to specify the table name, and –columns to query the column names. We will try to access the table ‘artists’. " }, { "code": null, "e": 31896, "s": 31772, "text": "In the above picture, we see that 8 tables have been retrieved. So now we definitely know that the website is vulnerable. " }, { "code": null, "e": 32020, "s": 31896, "text": "In the above picture, we see that 8 tables have been retrieved. So now we definitely know that the website is vulnerable. " }, { "code": null, "e": 32304, "s": 32020, "text": "Step 3: List information about the columns of a particular table If we want to view the columns of a particular table, we can use the following command, in which we use -T to specify the table name, and –columns to query the column names. We will try to access the table ‘artists’. " }, { "code": null, "e": 32523, "s": 32304, "text": "If we want to view the columns of a particular table, we can use the following command, in which we use -T to specify the table name, and –columns to query the column names. We will try to access the table ‘artists’. " }, { "code": null, "e": 32617, "s": 32523, "text": " sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 \n-D acuart -T artists --columns " }, { "code": null, "e": 32629, "s": 32621, "text": "Columns" }, { "code": null, "e": 32879, "s": 32629, "text": " Step 4: Dump the data from the columns Similarly, we can access the information in a specific column by using the following command, where -C can be used to specify multiple column name separated by a comma, and the –dump query retrieves the data " }, { "code": null, "e": 33130, "s": 32881, "text": "Step 4: Dump the data from the columns Similarly, we can access the information in a specific column by using the following command, where -C can be used to specify multiple column name separated by a comma, and the –dump query retrieves the data " }, { "code": null, "e": 33229, "s": 33130, "text": " sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1\n-D acuart -T artists -C aname --dump " }, { "code": null, "e": 33430, "s": 33233, "text": "From the above picture, we can see that we have accessed the data from the database. Similarly, in such vulnerable websites, we can literally explore through the databases to extract information " }, { "code": null, "e": 33627, "s": 33430, "text": "From the above picture, we can see that we have accessed the data from the database. Similarly, in such vulnerable websites, we can literally explore through the databases to extract information " }, { "code": null, "e": 33651, "s": 33629, "text": "Prevent SQL Injection" }, { "code": null, "e": 34305, "s": 33651, "text": "SQL injection can be generally prevented by using Prepared Statements . When we use a prepared statement, we are basically using a template for the code and analyzing the code and user input separately. It does not mix the user entered query and the code. In the example given at the beginning of this article, the input entered by the user is directly inserted into the code and they are compiled together, and hence we are able to execute malicious code. For prepared statements, we basically send the sql query with a placeholder for the user input and then send the actual user input as a separate command. Consider the following php code segment. " }, { "code": null, "e": 34441, "s": 34305, "text": "$db = new PDO('connection details');\n$stmt = db->prepare(\"Select name from users where id = :id\");\n$stmt->execute(array(':id', $data));" }, { "code": null, "e": 34690, "s": 34441, "text": "In this code, the user input is not combined with the prepared statement. They are compiled separately. So even if malicious code is entered as user input, the program will simply treat the malicious part of the code as a string and not a command. " }, { "code": null, "e": 34807, "s": 34690, "text": "Note: This application is to be used solely for testing purposes Related Article Basic SQL injection and mitigation " }, { "code": null, "e": 34836, "s": 34807, "text": "Reference:stackoverflow.com " }, { "code": null, "e": 35137, "s": 34836, "text": "This article is contributed by Deepak Srivatsav. 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": 35263, "s": 35137, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 35276, "s": 35263, "text": "simmytarika5" }, { "code": null, "e": 35290, "s": 35276, "text": "secure-coding" }, { "code": null, "e": 35304, "s": 35290, "text": "sql-injection" }, { "code": null, "e": 35318, "s": 35304, "text": "vulnerability" }, { "code": null, "e": 35324, "s": 35318, "text": "GBlog" }, { "code": null, "e": 35328, "s": 35324, "text": "SQL" }, { "code": null, "e": 35345, "s": 35328, "text": "Web Technologies" }, { "code": null, "e": 35349, "s": 35345, "text": "SQL" }, { "code": null, "e": 35447, "s": 35349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35472, "s": 35447, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 35499, "s": 35472, "text": "How to Start Learning DSA?" }, { "code": null, "e": 35536, "s": 35499, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 35599, "s": 35536, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 35637, "s": 35599, "text": "12 pip Commands For Python Developers" }, { "code": null, "e": 35679, "s": 35637, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 35697, "s": 35679, "text": "SQL | WITH clause" }, { "code": null, "e": 35744, "s": 35697, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 35788, "s": 35744, "text": "How to find Nth highest salary from a table" } ]
SQL Query to Count the Number of Rows in a Table - GeeksforGeeks
13 Apr, 2021 In this article, we are going to write an SQL query to count the number of rows in a table. For is we will be making use of the count() function of SQL. For this article, we will be making use of the Microsoft SQL Server as our database. Let’s do the same by building a table inside the database and counting its rows. We will first create a database called “geeks” and then create an “Employee” table in this database and will execute our query on that table. Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks; USE geeks; We have the following Employee table in our geeks database : CREATE TABLE geeks( id int(20) , name varchar(200)); Output: You can use the below statement to query the description of the created table: EXEC sp_columns employees; Use the below statement to add data to the Employee table: INSERT INTO geeks(id,name) values(1,'nikhil'); INSERT INTO geeks(id,name) values(2,'kartik'); The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement. Syntax: SELECT COUNT(colmn_name) from table_name; Example: Using ‘ * ‘ we get all the rows as shown below: SELECT * FROM geeks; This will result in the below image: The table we will be operating has 2 rows. So let’s feed in the query to get the no. of rows a specific column(say, id)as: SELECT COUNT(id) from geeks; Output: We can even change the display name for displaying count: SELECT COUNT(id) as id_count FROM geeks Output: Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25753, "s": 25513, "text": "In this article, we are going to write an SQL query to count the number of rows in a table. For is we will be making use of the count() function of SQL. For this article, we will be making use of the Microsoft SQL Server as our database." }, { "code": null, "e": 25976, "s": 25753, "text": "Let’s do the same by building a table inside the database and counting its rows. We will first create a database called “geeks” and then create an “Employee” table in this database and will execute our query on that table." }, { "code": null, "e": 26039, "s": 25976, "text": "Use the below SQL statement to create a database called geeks:" }, { "code": null, "e": 26062, "s": 26039, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 26073, "s": 26062, "text": "USE geeks;" }, { "code": null, "e": 26134, "s": 26073, "text": "We have the following Employee table in our geeks database :" }, { "code": null, "e": 26196, "s": 26134, "text": "CREATE TABLE geeks(\n id int(20) , \n name varchar(200));" }, { "code": null, "e": 26204, "s": 26196, "text": "Output:" }, { "code": null, "e": 26283, "s": 26204, "text": "You can use the below statement to query the description of the created table:" }, { "code": null, "e": 26310, "s": 26283, "text": "EXEC sp_columns employees;" }, { "code": null, "e": 26369, "s": 26310, "text": "Use the below statement to add data to the Employee table:" }, { "code": null, "e": 26463, "s": 26369, "text": "INSERT INTO geeks(id,name) values(1,'nikhil');\nINSERT INTO geeks(id,name) values(2,'kartik');" }, { "code": null, "e": 26579, "s": 26463, "text": "The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement." }, { "code": null, "e": 26629, "s": 26579, "text": "Syntax: SELECT COUNT(colmn_name) from table_name;" }, { "code": null, "e": 26638, "s": 26629, "text": "Example:" }, { "code": null, "e": 26687, "s": 26638, "text": "Using ‘ * ‘ we get all the rows as shown below:" }, { "code": null, "e": 26708, "s": 26687, "text": "SELECT * FROM geeks;" }, { "code": null, "e": 26745, "s": 26708, "text": "This will result in the below image:" }, { "code": null, "e": 26868, "s": 26745, "text": "The table we will be operating has 2 rows. So let’s feed in the query to get the no. of rows a specific column(say, id)as:" }, { "code": null, "e": 26897, "s": 26868, "text": "SELECT COUNT(id) from geeks;" }, { "code": null, "e": 26905, "s": 26897, "text": "Output:" }, { "code": null, "e": 26963, "s": 26905, "text": "We can even change the display name for displaying count:" }, { "code": null, "e": 27003, "s": 26963, "text": "SELECT COUNT(id) as id_count FROM geeks" }, { "code": null, "e": 27011, "s": 27003, "text": "Output:" }, { "code": null, "e": 27018, "s": 27011, "text": "Picked" }, { "code": null, "e": 27028, "s": 27018, "text": "SQL-Query" }, { "code": null, "e": 27032, "s": 27028, "text": "SQL" }, { "code": null, "e": 27036, "s": 27032, "text": "SQL" }, { "code": null, "e": 27134, "s": 27036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27200, "s": 27134, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27215, "s": 27200, "text": "SQL | Subquery" }, { "code": null, "e": 27272, "s": 27215, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27304, "s": 27272, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27382, "s": 27304, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27418, "s": 27382, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27435, "s": 27418, "text": "SQL using Python" }, { "code": null, "e": 27501, "s": 27435, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27563, "s": 27501, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Check if elements of Linked List are present in pair - GeeksforGeeks
29 Jun, 2021 Given a singly linked list of integers. The task is to check if each element in the linked list is present in a pair i.e. all elements occur even no. of times.Examples: Input: 1 -> 2 -> 3 -> 3 -> 1 -> 2 Output: Yes Input: 10 -> 20 -> 30 -> 20 Output: No Approach: Initialize a temp node pointing to head. Take a variable to calculate XOR of all elements. Start traversing linked list and keep calculating the XOR with node->data. Return true if XOR is 0, else return false. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to check if elements of// linked lists are present in pair#include <bits/stdc++.h> using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; // Function to check if elements of// linked list are present in pairbool isPair(struct Node* head){ int xxor = 0; struct Node* temp = head; while (temp != NULL) { xxor ^= temp->data; temp = temp->next; } return xxor;} // Function to add a node at the// beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver program to test above functionint main(){ struct Node* first = NULL; /* First constructed linked list is: 10 -> 34 -> 1 -> 10 -> 34 -> 1 */ push(&first, 1); push(&first, 34); push(&first, 10); push(&first, 1); push(&first, 34); push(&first, 10); // Calling function to check pair elements if (!isPair(first)) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0;} // Java program to check if elements of// linked lists are present in pair // Node Classclass Node{ int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; }} class SLL{ // function to insert a node at the beginning // of the Singly Linked List static Node push(Node head, int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to check if elements of // linked list are present in pair static boolean isPair(Node head) { int xxor = 0; Node temp = head; while (temp != null) { xxor ^= temp.data; temp = temp.next; } return xxor != 0; } // Driver code public static void main(String[] args) { Node head = null; // First constructed linked list // 10 -> 34 -> 1 -> 10 -> 34 -> 1 head = push(head, 1); head = push(head, 34); head = push(head, 10); head = push(head, 1); head = push(head, 34); head = push(head, 10); // Calling function to check pair elements if (!isPair(head)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code is contributed by Vivekkumar Singh # Python3 program to check if elements of# linked lists are present in pair # A linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to check if elements of# linked list are present in pairdef isPair( head): xxor = 0 temp = head while (temp != None) : xxor = xxor ^ temp.data temp = temp.next return xxor # Function to add a node at the# beginning of Linked Listdef push( head_ref, new_data): # allocate node new_node = Node() # put in the data new_node.data = new_data # link the old list off the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref # Driver code first = None # First constructed linked list is:# 10 . 34 . 1 . 10 . 34 . 1first = push(first, 1)first = push(first, 34)first = push(first, 10)first = push(first, 1)first = push(first, 34)first = push(first, 10) # Calling function to check pair elementsif (not isPair(first)): print( "Yes" ) else : print( "No" ) # This code is contributed by Arnab Kundu // C# program to check if elements of// linked lists are present in pairusing System; // Node Classpublic class Node{ public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; }} public class SLL{ // function to insert a node at the beginning // of the Singly Linked List static Node push(Node head, int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to check if elements of // linked list are present in pair static Boolean isPair(Node head) { int xxor = 0; Node temp = head; while (temp != null) { xxor ^= temp.data; temp = temp.next; } return xxor != 0; } // Driver code public static void Main(String[] args) { Node head = null; // First constructed linked list // 10 -> 34 -> 1 -> 10 -> 34 -> 1 head = push(head, 1); head = push(head, 34); head = push(head, 10); head = push(head, 1); head = push(head, 34); head = push(head, 10); // Calling function to check pair elements if (!isPair(head)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by Rajput-Ji <script> // JavaScript program to check if elements of // linked lists are present in pair // Node Class class Node { // Constructor to create a new node constructor(d) { this.data = d; this.next = null; } } // function to insert a node at the beginning // of the Singly Linked List function push(head, data) { var newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to check if elements of // linked list are present in pair function isPair(head) { var xxor = 0; var temp = head; while (temp != null) { xxor ^= temp.data; temp = temp.next; } return xxor != 0; } // Driver code var head = null; // First constructed linked list // 10 -> 34 -> 1 -> 10 -> 34 -> 1 head = push(head, 1); head = push(head, 34); head = push(head, 10); head = push(head, 1); head = push(head, 34); head = push(head, 10); // Calling function to check pair elements if (!isPair(head)) { document.write("Yes"); } else { document.write("No"); } </script> Yes Vivekkumar Singh Rajput-Ji Akanksha_Rai andrew1234 rdtank Bitwise-XOR Bit Magic Linked List Linked List Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Swap two nibbles in a byte Write an Efficient Method to Check if a Number is Multiple of 3 Highest power of 2 less than or equal to given number Swap bits in a given number Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 26277, "s": 26249, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26448, "s": 26277, "text": "Given a singly linked list of integers. The task is to check if each element in the linked list is present in a pair i.e. all elements occur even no. of times.Examples: " }, { "code": null, "e": 26534, "s": 26448, "text": "Input: 1 -> 2 -> 3 -> 3 -> 1 -> 2\nOutput: Yes\n\nInput: 10 -> 20 -> 30 -> 20\nOutput: No" }, { "code": null, "e": 26548, "s": 26536, "text": "Approach: " }, { "code": null, "e": 26589, "s": 26548, "text": "Initialize a temp node pointing to head." }, { "code": null, "e": 26639, "s": 26589, "text": "Take a variable to calculate XOR of all elements." }, { "code": null, "e": 26714, "s": 26639, "text": "Start traversing linked list and keep calculating the XOR with node->data." }, { "code": null, "e": 26758, "s": 26714, "text": "Return true if XOR is 0, else return false." }, { "code": null, "e": 26807, "s": 26758, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 26811, "s": 26807, "text": "C++" }, { "code": null, "e": 26816, "s": 26811, "text": "Java" }, { "code": null, "e": 26824, "s": 26816, "text": "Python3" }, { "code": null, "e": 26827, "s": 26824, "text": "C#" }, { "code": null, "e": 26838, "s": 26827, "text": "Javascript" }, { "code": "// C++ program to check if elements of// linked lists are present in pair#include <bits/stdc++.h> using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; // Function to check if elements of// linked list are present in pairbool isPair(struct Node* head){ int xxor = 0; struct Node* temp = head; while (temp != NULL) { xxor ^= temp->data; temp = temp->next; } return xxor;} // Function to add a node at the// beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver program to test above functionint main(){ struct Node* first = NULL; /* First constructed linked list is: 10 -> 34 -> 1 -> 10 -> 34 -> 1 */ push(&first, 1); push(&first, 34); push(&first, 10); push(&first, 1); push(&first, 34); push(&first, 10); // Calling function to check pair elements if (!isPair(first)) { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; } return 0;}", "e": 28143, "s": 26838, "text": null }, { "code": "// Java program to check if elements of// linked lists are present in pair // Node Classclass Node{ int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; }} class SLL{ // function to insert a node at the beginning // of the Singly Linked List static Node push(Node head, int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to check if elements of // linked list are present in pair static boolean isPair(Node head) { int xxor = 0; Node temp = head; while (temp != null) { xxor ^= temp.data; temp = temp.next; } return xxor != 0; } // Driver code public static void main(String[] args) { Node head = null; // First constructed linked list // 10 -> 34 -> 1 -> 10 -> 34 -> 1 head = push(head, 1); head = push(head, 34); head = push(head, 10); head = push(head, 1); head = push(head, 34); head = push(head, 10); // Calling function to check pair elements if (!isPair(head)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code is contributed by Vivekkumar Singh", "e": 29532, "s": 28143, "text": null }, { "code": "# Python3 program to check if elements of# linked lists are present in pair # A linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to check if elements of# linked list are present in pairdef isPair( head): xxor = 0 temp = head while (temp != None) : xxor = xxor ^ temp.data temp = temp.next return xxor # Function to add a node at the# beginning of Linked Listdef push( head_ref, new_data): # allocate node new_node = Node() # put in the data new_node.data = new_data # link the old list off the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref # Driver code first = None # First constructed linked list is:# 10 . 34 . 1 . 10 . 34 . 1first = push(first, 1)first = push(first, 34)first = push(first, 10)first = push(first, 1)first = push(first, 34)first = push(first, 10) # Calling function to check pair elementsif (not isPair(first)): print( \"Yes\" ) else : print( \"No\" ) # This code is contributed by Arnab Kundu", "e": 30646, "s": 29532, "text": null }, { "code": "// C# program to check if elements of// linked lists are present in pairusing System; // Node Classpublic class Node{ public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; }} public class SLL{ // function to insert a node at the beginning // of the Singly Linked List static Node push(Node head, int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to check if elements of // linked list are present in pair static Boolean isPair(Node head) { int xxor = 0; Node temp = head; while (temp != null) { xxor ^= temp.data; temp = temp.next; } return xxor != 0; } // Driver code public static void Main(String[] args) { Node head = null; // First constructed linked list // 10 -> 34 -> 1 -> 10 -> 34 -> 1 head = push(head, 1); head = push(head, 34); head = push(head, 10); head = push(head, 1); head = push(head, 34); head = push(head, 10); // Calling function to check pair elements if (!isPair(head)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by Rajput-Ji", "e": 32072, "s": 30646, "text": null }, { "code": "<script> // JavaScript program to check if elements of // linked lists are present in pair // Node Class class Node { // Constructor to create a new node constructor(d) { this.data = d; this.next = null; } } // function to insert a node at the beginning // of the Singly Linked List function push(head, data) { var newNode = new Node(data); newNode.next = head; head = newNode; return head; } // Function to check if elements of // linked list are present in pair function isPair(head) { var xxor = 0; var temp = head; while (temp != null) { xxor ^= temp.data; temp = temp.next; } return xxor != 0; } // Driver code var head = null; // First constructed linked list // 10 -> 34 -> 1 -> 10 -> 34 -> 1 head = push(head, 1); head = push(head, 34); head = push(head, 10); head = push(head, 1); head = push(head, 34); head = push(head, 10); // Calling function to check pair elements if (!isPair(head)) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>", "e": 33320, "s": 32072, "text": null }, { "code": null, "e": 33324, "s": 33320, "text": "Yes" }, { "code": null, "e": 33343, "s": 33326, "text": "Vivekkumar Singh" }, { "code": null, "e": 33353, "s": 33343, "text": "Rajput-Ji" }, { "code": null, "e": 33366, "s": 33353, "text": "Akanksha_Rai" }, { "code": null, "e": 33377, "s": 33366, "text": "andrew1234" }, { "code": null, "e": 33384, "s": 33377, "text": "rdtank" }, { "code": null, "e": 33396, "s": 33384, "text": "Bitwise-XOR" }, { "code": null, "e": 33406, "s": 33396, "text": "Bit Magic" }, { "code": null, "e": 33418, "s": 33406, "text": "Linked List" }, { "code": null, "e": 33430, "s": 33418, "text": "Linked List" }, { "code": null, "e": 33440, "s": 33430, "text": "Bit Magic" }, { "code": null, "e": 33538, "s": 33440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33589, "s": 33538, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 33616, "s": 33589, "text": "Swap two nibbles in a byte" }, { "code": null, "e": 33680, "s": 33616, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 33734, "s": 33680, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 33762, "s": 33734, "text": "Swap bits in a given number" }, { "code": null, "e": 33797, "s": 33762, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 33836, "s": 33797, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 33858, "s": 33836, "text": "Reverse a linked list" }, { "code": null, "e": 33906, "s": 33858, "text": "Stack Data Structure (Introduction and Program)" } ]
MATLAB - Ideal Lowpass Filter in Image Processing - GeeksforGeeks
22 Apr, 2020 In the field of Image Processing, Ideal Lowpass Filter (ILPF) is used for image smoothing in the frequency domain. It removes high-frequency noise from a digital image and preserves low-frequency components. It can be specified by the function- Where, is a positive constant. ILPF passes all the frequencies within a circle of radius from the origin without attenuation and cuts off all the frequencies outside the circle. This is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed as cutoff frequency. is the Euclidean Distance from any point (u, v) to the origin of the frequency plane, i.e, Approach: Step 1: Input – Read an imageStep 2: Saving the size of the input image in pixelsStep 3: Get the Fourier Transform of the input_imageStep 4: Assign the Cut-off Frequency Step 5: Designing filter: Ideal Low Pass FilterStep 6: Convolution between the Fourier Transformed input image and the filtering maskStep 7: Take Inverse Fourier Transform of the convoluted imageStep 8: Display the resultant image as output Implementation in MATLAB: % MATLAB Code | Ideal Low Pass Filter % Reading input image : input_image input_image = imread('[name of input image file].[file format]'); % Saving the size of the input_image in pixels-% M : no of rows (height of the image)% N : no of columns (width of the image)[M, N] = size(input_image); % Getting Fourier Transform of the input_image% using MATLAB library function fft2 (2D fast fourier transform) FT_img = fft2(double(input_image)); % Assign Cut-off Frequency D0 = 30; % one can change this value accordingly % Designing filteru = 0:(M-1);idx = find(u>M/2);u(idx) = u(idx)-M;v = 0:(N-1);idy = find(v>N/2);v(idy) = v(idy)-N; % MATLAB library function meshgrid(v, u) returns% 2D grid which contains the coordinates of vectors% v and u. Matrix V with each row is a copy % of v, and matrix U with each column is a copy of u[V, U] = meshgrid(v, u); % Calculating Euclidean DistanceD = sqrt(U.^2+V.^2); % Comparing with the cut-off frequency and % determining the filtering maskH = double(D <= D0); % Convolution between the Fourier Transformed% image and the maskG = H.*FT_img; % Getting the resultant image by Inverse Fourier Transform% of the convoluted image using MATLAB library function % ifft2 (2D inverse fast fourier transform) output_image = real(ifft2(double(G))); % Displaying Input Image and Output Imagesubplot(2, 1, 1), imshow(input_image),subplot(2, 1, 2), imshow(output_image, [ ]); Input Image – Output: Image-Processing MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example System Design Tutorial Python | Decision tree implementation Copying Files to and from Docker Containers ML | Underfitting and Overfitting Clustering in Machine Learning Docker - COPY Instruction
[ { "code": null, "e": 26019, "s": 25991, "text": "\n22 Apr, 2020" }, { "code": null, "e": 26227, "s": 26019, "text": "In the field of Image Processing, Ideal Lowpass Filter (ILPF) is used for image smoothing in the frequency domain. It removes high-frequency noise from a digital image and preserves low-frequency components." }, { "code": null, "e": 26264, "s": 26227, "text": "It can be specified by the function-" }, { "code": null, "e": 26271, "s": 26264, "text": "Where," }, { "code": null, "e": 26444, "s": 26271, "text": " is a positive constant. ILPF passes all the frequencies within a circle of radius from the origin without attenuation and cuts off all the frequencies outside the circle." }, { "code": null, "e": 26550, "s": 26444, "text": "This is the transition point between H(u, v) = 1 and H(u, v) = 0, so this is termed as cutoff frequency." }, { "code": null, "e": 26642, "s": 26550, "text": " is the Euclidean Distance from any point (u, v) to the origin of the frequency plane, i.e," }, { "code": null, "e": 26652, "s": 26642, "text": "Approach:" }, { "code": null, "e": 27063, "s": 26652, "text": "Step 1: Input – Read an imageStep 2: Saving the size of the input image in pixelsStep 3: Get the Fourier Transform of the input_imageStep 4: Assign the Cut-off Frequency Step 5: Designing filter: Ideal Low Pass FilterStep 6: Convolution between the Fourier Transformed input image and the filtering maskStep 7: Take Inverse Fourier Transform of the convoluted imageStep 8: Display the resultant image as output" }, { "code": null, "e": 27089, "s": 27063, "text": "Implementation in MATLAB:" }, { "code": "% MATLAB Code | Ideal Low Pass Filter % Reading input image : input_image input_image = imread('[name of input image file].[file format]'); % Saving the size of the input_image in pixels-% M : no of rows (height of the image)% N : no of columns (width of the image)[M, N] = size(input_image); % Getting Fourier Transform of the input_image% using MATLAB library function fft2 (2D fast fourier transform) FT_img = fft2(double(input_image)); % Assign Cut-off Frequency D0 = 30; % one can change this value accordingly % Designing filteru = 0:(M-1);idx = find(u>M/2);u(idx) = u(idx)-M;v = 0:(N-1);idy = find(v>N/2);v(idy) = v(idy)-N; % MATLAB library function meshgrid(v, u) returns% 2D grid which contains the coordinates of vectors% v and u. Matrix V with each row is a copy % of v, and matrix U with each column is a copy of u[V, U] = meshgrid(v, u); % Calculating Euclidean DistanceD = sqrt(U.^2+V.^2); % Comparing with the cut-off frequency and % determining the filtering maskH = double(D <= D0); % Convolution between the Fourier Transformed% image and the maskG = H.*FT_img; % Getting the resultant image by Inverse Fourier Transform% of the convoluted image using MATLAB library function % ifft2 (2D inverse fast fourier transform) output_image = real(ifft2(double(G))); % Displaying Input Image and Output Imagesubplot(2, 1, 1), imshow(input_image),subplot(2, 1, 2), imshow(output_image, [ ]);", "e": 28504, "s": 27089, "text": null }, { "code": null, "e": 28518, "s": 28504, "text": "Input Image –" }, { "code": null, "e": 28526, "s": 28518, "text": "Output:" }, { "code": null, "e": 28543, "s": 28526, "text": "Image-Processing" }, { "code": null, "e": 28550, "s": 28543, "text": "MATLAB" }, { "code": null, "e": 28576, "s": 28550, "text": "Advanced Computer Subject" }, { "code": null, "e": 28674, "s": 28576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28697, "s": 28674, "text": "ML | Linear Regression" }, { "code": null, "e": 28720, "s": 28697, "text": "Reinforcement learning" }, { "code": null, "e": 28734, "s": 28720, "text": "Decision Tree" }, { "code": null, "e": 28774, "s": 28734, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 28797, "s": 28774, "text": "System Design Tutorial" }, { "code": null, "e": 28835, "s": 28797, "text": "Python | Decision tree implementation" }, { "code": null, "e": 28879, "s": 28835, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 28913, "s": 28879, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 28944, "s": 28913, "text": "Clustering in Machine Learning" } ]
Maximum value of signed char in C++ - GeeksforGeeks
06 Jan, 2021 In this article, we will discuss the signed char data type in C++. Some properties of the signed char data type are: It is generally used to store 8-bit characters. Being a signed data type, it can store positive values as well as negative values. Size of 8 bits is occupied where 1 bit is used to store the sign of the value. A maximum value that can be stored in a signed char data type is typically 127, around 27 – 1(but is compiler dependent). The maximum and minimum value that can be stored in a signed char is stored as a constant in climits header file and can be named as SCHAR_MAX and SCHAR_MIN respectively. A minimum value that can be stored in a signed char data type is typically -128, i.e. around –27 (but is compiler dependent). In case of overflow or underflow of data type, the value is wrapped around. For example, if -128 is stored in a signed char data type and 1 is subtracted from it, the value in that variable will become equal to 127. Similarly, in the case of overflow, the value will round back to -128. Below is the program to get the highest value that can be stored in signed char in C++: C++ // C++ program to obtain the maximum value// that we can store in signed char#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file signed char valueFromLimits = SCHAR_MAX; cout << "Maximum value from " << "climits constant: " << (int)valueFromLimits << '\n'; valueFromLimits = SCHAR_MIN; cout << "Minimum value from " << "climits constant: " << (int)valueFromLimits << '\n'; // Using the wrap around property // of data types // Initialize two variables one // value with -1 as previous and // one with 0 as present signed char previous = -1; signed char present = 0; // Keep on increasing both values // until the present increases to // the max limit and wraps around to // the negative value i.e., present // becomes less the previous value while (present > previous) { previous++; present++; } cout << "Maximum value using the " << "wrap around property: " << (int)previous << '\n'; cout << "Maximum value using the " << "wrap around property: " << (int)present; return 0;} Maximum value from climits constant: 127 Minimum value from climits constant: -128 Maximum value using the wrap around property: 127 Maximum value using the wrap around property: -128 C-Data Types Data Type Data Types C++ C++ Programs Data Type CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25343, "s": 25315, "text": "\n06 Jan, 2021" }, { "code": null, "e": 25410, "s": 25343, "text": "In this article, we will discuss the signed char data type in C++." }, { "code": null, "e": 25460, "s": 25410, "text": "Some properties of the signed char data type are:" }, { "code": null, "e": 25508, "s": 25460, "text": "It is generally used to store 8-bit characters." }, { "code": null, "e": 25591, "s": 25508, "text": "Being a signed data type, it can store positive values as well as negative values." }, { "code": null, "e": 25670, "s": 25591, "text": "Size of 8 bits is occupied where 1 bit is used to store the sign of the value." }, { "code": null, "e": 25792, "s": 25670, "text": "A maximum value that can be stored in a signed char data type is typically 127, around 27 – 1(but is compiler dependent)." }, { "code": null, "e": 25963, "s": 25792, "text": "The maximum and minimum value that can be stored in a signed char is stored as a constant in climits header file and can be named as SCHAR_MAX and SCHAR_MIN respectively." }, { "code": null, "e": 26089, "s": 25963, "text": "A minimum value that can be stored in a signed char data type is typically -128, i.e. around –27 (but is compiler dependent)." }, { "code": null, "e": 26376, "s": 26089, "text": "In case of overflow or underflow of data type, the value is wrapped around. For example, if -128 is stored in a signed char data type and 1 is subtracted from it, the value in that variable will become equal to 127. Similarly, in the case of overflow, the value will round back to -128." }, { "code": null, "e": 26464, "s": 26376, "text": "Below is the program to get the highest value that can be stored in signed char in C++:" }, { "code": null, "e": 26468, "s": 26464, "text": "C++" }, { "code": "// C++ program to obtain the maximum value// that we can store in signed char#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file signed char valueFromLimits = SCHAR_MAX; cout << \"Maximum value from \" << \"climits constant: \" << (int)valueFromLimits << '\\n'; valueFromLimits = SCHAR_MIN; cout << \"Minimum value from \" << \"climits constant: \" << (int)valueFromLimits << '\\n'; // Using the wrap around property // of data types // Initialize two variables one // value with -1 as previous and // one with 0 as present signed char previous = -1; signed char present = 0; // Keep on increasing both values // until the present increases to // the max limit and wraps around to // the negative value i.e., present // becomes less the previous value while (present > previous) { previous++; present++; } cout << \"Maximum value using the \" << \"wrap around property: \" << (int)previous << '\\n'; cout << \"Maximum value using the \" << \"wrap around property: \" << (int)present; return 0;}", "e": 27703, "s": 26468, "text": null }, { "code": null, "e": 27888, "s": 27703, "text": "Maximum value from climits constant: 127\nMinimum value from climits constant: -128\nMaximum value using the wrap around property: 127\nMaximum value using the wrap around property: -128\n" }, { "code": null, "e": 27901, "s": 27888, "text": "C-Data Types" }, { "code": null, "e": 27911, "s": 27901, "text": "Data Type" }, { "code": null, "e": 27922, "s": 27911, "text": "Data Types" }, { "code": null, "e": 27926, "s": 27922, "text": "C++" }, { "code": null, "e": 27939, "s": 27926, "text": "C++ Programs" }, { "code": null, "e": 27949, "s": 27939, "text": "Data Type" }, { "code": null, "e": 27953, "s": 27949, "text": "CPP" }, { "code": null, "e": 28051, "s": 27953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28079, "s": 28051, "text": "Operator Overloading in C++" }, { "code": null, "e": 28099, "s": 28079, "text": "Polymorphism in C++" }, { "code": null, "e": 28132, "s": 28099, "text": "Friend class and function in C++" }, { "code": null, "e": 28156, "s": 28132, "text": "Sorting a vector in C++" }, { "code": null, "e": 28181, "s": 28156, "text": "std::string class in C++" }, { "code": null, "e": 28216, "s": 28181, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 28260, "s": 28216, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 28319, "s": 28260, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 28345, "s": 28319, "text": "C++ Program for QuickSort" } ]
C# Program to Create a Directory - GeeksforGeeks
30 Nov, 2021 A directory is a file system that stores file. Now our task is to create a directory in C#. We can create a directory by using the CreateDirectory() method of the Directory class. This method is used to create directories and subdirectories in a specified path. If the specified directory exists or the given path is invalid then this method will not create a directory. To use CreateDirectory() method we have to import the system.IO namespace in the program. Syntax: public static System.IO.DirectoryInfo CreateDirectory (string path); Parameter: path is the directory path. Return: This will return the object of the specified created directory. Exception: It will throw the following exception: IOException: This exception occurs when the directory specified by path is a file. UnauthorizedAccessException: This exception occurs when the caller does not have the required permission. ArgumentException: This exception occurs when the path is prefixed with, or contains, only a colon character (:). ArgumentNullException: This exception occurs when the path is null. PathTooLongException: This exception occurs when the specified path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: This exception occurs when the specified path is invalid NotSupportedException: This exception occurs when the path contains a colon character(:) that is not part of a drive label (“D:\”). Example: C# // C# program to illustrate how// to create directoryusing System;using System.IO; class GFG{ public static void Main(){ // Create directory named Sravan in C drive // Using CreateDirectory() method Directory.CreateDirectory("C:\\sravan"); Console.WriteLine("Created");}} Output: Created CSharp-File-Handling Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Convert String to Character Array in C# Program to Print a New Line in C# Getting a Month Name Using Month Number in C# Socket Programming in C# C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
[ { "code": null, "e": 25547, "s": 25519, "text": "\n30 Nov, 2021" }, { "code": null, "e": 26008, "s": 25547, "text": "A directory is a file system that stores file. Now our task is to create a directory in C#. We can create a directory by using the CreateDirectory() method of the Directory class. This method is used to create directories and subdirectories in a specified path. If the specified directory exists or the given path is invalid then this method will not create a directory. To use CreateDirectory() method we have to import the system.IO namespace in the program." }, { "code": null, "e": 26016, "s": 26008, "text": "Syntax:" }, { "code": null, "e": 26085, "s": 26016, "text": "public static System.IO.DirectoryInfo CreateDirectory (string path);" }, { "code": null, "e": 26124, "s": 26085, "text": "Parameter: path is the directory path." }, { "code": null, "e": 26196, "s": 26124, "text": "Return: This will return the object of the specified created directory." }, { "code": null, "e": 26246, "s": 26196, "text": "Exception: It will throw the following exception:" }, { "code": null, "e": 26329, "s": 26246, "text": "IOException: This exception occurs when the directory specified by path is a file." }, { "code": null, "e": 26435, "s": 26329, "text": "UnauthorizedAccessException: This exception occurs when the caller does not have the required permission." }, { "code": null, "e": 26549, "s": 26435, "text": "ArgumentException: This exception occurs when the path is prefixed with, or contains, only a colon character (:)." }, { "code": null, "e": 26617, "s": 26549, "text": "ArgumentNullException: This exception occurs when the path is null." }, { "code": null, "e": 26747, "s": 26617, "text": "PathTooLongException: This exception occurs when the specified path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 26833, "s": 26747, "text": "DirectoryNotFoundException: This exception occurs when the specified path is invalid " }, { "code": null, "e": 26965, "s": 26833, "text": "NotSupportedException: This exception occurs when the path contains a colon character(:) that is not part of a drive label (“D:\\”)." }, { "code": null, "e": 26974, "s": 26965, "text": "Example:" }, { "code": null, "e": 26977, "s": 26974, "text": "C#" }, { "code": "// C# program to illustrate how// to create directoryusing System;using System.IO; class GFG{ public static void Main(){ // Create directory named Sravan in C drive // Using CreateDirectory() method Directory.CreateDirectory(\"C:\\\\sravan\"); Console.WriteLine(\"Created\");}}", "e": 27279, "s": 26977, "text": null }, { "code": null, "e": 27287, "s": 27279, "text": "Output:" }, { "code": null, "e": 27295, "s": 27287, "text": "Created" }, { "code": null, "e": 27316, "s": 27295, "text": "CSharp-File-Handling" }, { "code": null, "e": 27323, "s": 27316, "text": "Picked" }, { "code": null, "e": 27326, "s": 27323, "text": "C#" }, { "code": null, "e": 27338, "s": 27326, "text": "C# Programs" }, { "code": null, "e": 27436, "s": 27338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27459, "s": 27436, "text": "Extension Method in C#" }, { "code": null, "e": 27487, "s": 27459, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27504, "s": 27487, "text": "C# | Inheritance" }, { "code": null, "e": 27526, "s": 27504, "text": "Partial Classes in C#" }, { "code": null, "e": 27555, "s": 27526, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27595, "s": 27555, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27629, "s": 27595, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 27675, "s": 27629, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 27700, "s": 27675, "text": "Socket Programming in C#" } ]
Print the first shortest root to leaf path in a Binary Tree - GeeksforGeeks
06 Aug, 2021 Given a Binary Tree with distinct values, the task is to print the first smallest root to leaf path. We basically need to print the leftmost root to leaf path that has the minimum number of nodes. Input: 1 / \ 2 3 / / \ 4 5 7 / \ \ 10 11 8 Output: 1 3 5 Input: 1 / \ 2 3 / / \ 40 5 7 \ 8 Output: 1 2 40 Approach: The idea is to use a queue to perform level order traversal, a map parent to store the nodes that will be present in the shortest path. Using level order traversal, we find the leftmost leaf. Once we find the leftmost leaf, we print path using the map. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print first shortest// root to leaf path#include <bits/stdc++.h>using namespace std; // Binary tree nodestruct Node { struct Node* left; struct Node* right; int data;}; // Function to create a new// Binary nodestruct Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // Recursive function used by leftMostShortest// to print the first shortest root to leaf pathvoid printPath(int Data, unordered_map<int, int> parent){ // If the root's data is same as // its parent data then return if (parent[Data] == Data) return; // Recur for the function printPath printPath(parent[Data], parent); // Print the parent node's data cout << parent[Data] << " ";} // Function to perform level order traversal// until we find the first leaf nodevoid leftMostShortest(struct Node* root){ // Queue to store the nodes queue<struct Node*> q; // Push the root node q.push(root); // Initialize the value of first // leaf node to occur as -1 int LeafData = -1; // To store the current node struct Node* temp = NULL; // Map to store the parent node's data unordered_map<int, int> parent; // Parent of root data is set as it's // own value parent[root->data] = root->data; // We store first node of the smallest level while (!q.empty()) { temp = q.front(); q.pop(); // If the first leaf node has been found // set the flag variable as 1 if (!temp->left && !temp->right) { LeafData = temp->data; break; } else { // If current node has left // child, push in the queue if (temp->left) { q.push(temp->left); // Set temp's left node's parent as temp parent[temp->left->data] = temp->data; } // If current node has right // child, push in the queue if (temp->right) { q.push(temp->right); // Set temp's right node's parent // as temp parent[temp->right->data] = temp->data; } } } // Recursive function to print the first // shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path cout << LeafData << " ";} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(7); root->left->left->left = newNode(10); root->left->left->right = newNode(11); root->right->right->left = newNode(8); leftMostShortest(root); return 0;} // Java program to print first shortest// root to leaf pathimport java.util.*; class GFG{ // Binary tree nodestatic class Node{ Node left; Node right; int data;}; // Function to create a new// Binary nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} // Recursive function used by leftMostShortest// to print the first shortest root to leaf pathstatic void printPath(int Data, HashMap<Integer, Integer> parent){ // If the root's data is same as // its parent data then return if (parent.get(Data) == Data) return; // Recur for the function printPath printPath(parent.get(Data), parent); // Print the parent node's data System.out.print(parent.get(Data) + " ");} // Function to perform level order traversal// until we find the first leaf nodestatic void leftMostShortest(Node root){ // Queue to store the nodes Queue<Node> q = new LinkedList<>(); // Add the root node q.add(root); // Initialize the value of first // leaf node to occur as -1 int LeafData = -1; // To store the current node Node temp = null; // Map to store the parent node's data HashMap<Integer, Integer> parent = new HashMap<>(); // Parent of root data is set as it's // own value parent.put(root.data, root.data); // We store first node of the smallest level while (!q.isEmpty()) { temp = q.poll(); // If the first leaf node has been found // set the flag variable as 1 if (temp.left == null && temp.right == null) { LeafData = temp.data; break; } else { // If current node has left // child, add in the queue if (temp.left != null) { q.add(temp.left); // Set temp's left node's parent // as temp parent.put(temp.left.data, temp.data); } // If current node has right // child, add in the queue if (temp.right != null) { q.add(temp.right); // Set temp's right node's parent // as temp parent.put(temp.right.data, temp.data); } } } // Recursive function to print the // first shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path System.out.println(LeafData + " ");} // Driver Codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(10); root.left.left.right = newNode(11); root.right.right.left = newNode(8); leftMostShortest(root);}} // This code is contributed by sanjeev2552 # Python3 program to print first# shortest root to leaf path # Binary tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Recursive function used by leftMostShortest# to print the first shortest root to leaf pathdef printPath(Data, parent): # If the root's data is same as # its parent data then return if parent[Data] == Data: return # Recur for the function printPath printPath(parent[Data], parent) # Print the parent node's data print(parent[Data], end = " ") # Function to perform level order traversal# until we find the first leaf nodedef leftMostShortest(root): # Queue to store the nodes q = [] # Push the root node q.append(root) # Initialize the value of first # leaf node to occur as -1 LeafData = -1 # To store the current node temp = None # Map to store the parent node's data parent = {} # Parent of root data is set # as it's own value parent[root.data] = root.data # We store first node of the # smallest level while len(q) != 0: temp = q.pop(0) # If the first leaf node has been # found set the flag variable as 1 if not temp.left and not temp.right: LeafData = temp.data break else: # If current node has left # child, push in the queue if temp.left: q.append(temp.left) # Set temp's left node's parent as temp parent[temp.left.data] = temp.data # If current node has right # child, push in the queue if temp.right: q.append(temp.right) # Set temp's right node's parent # as temp parent[temp.right.data] = temp.data # Recursive function to print the first # shortest root to leaf path printPath(LeafData, parent) # Print the leaf node of the # first shortest path print(LeafData, end = " ") # Driver codeif __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.left = Node(5) root.right.right = Node(7) root.left.left.left = Node(10) root.left.left.right = Node(11) root.right.right.left = Node(8) leftMostShortest(root) # This code is contributed by Rituraj Jain // C# program to print first shortest// root to leaf pathusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Binary tree nodepublic class Node{ public Node left; public Node right; public int data;}; // Function to create a new// Binary nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} // Recursive function used by leftMostShortest// to print the first shortest root to leaf pathstatic void printPath(int Data, Dictionary<int, int> parent){ // If the root's data is same as // its parent data then return if (parent[Data] == Data) return; // Recur for the function printPath printPath(parent[Data], parent); // Print the parent node's data Console.Write(parent[Data] + " ");} // Function to perform level order traversal// until we find the first leaf nodestatic void leftMostShortest(Node root){ // Queue to store the nodes Queue q = new Queue(); // Add the root node q.Enqueue(root); // Initialize the value of first // leaf node to occur as -1 int LeafData = -1; // To store the current node Node temp = null; // Map to store the parent node's data Dictionary<int, int> parent = new Dictionary<int, int>(); // Parent of root data is set as it's // own value parent[root.data] = root.data; // We store first node of the // smallest level while (q.Count != 0) { temp = (Node)q.Dequeue(); // If the first leaf node has been // found set the flag variable as 1 if (temp.left == null && temp.right == null) { LeafData = temp.data; break; } else { // If current node has left // child, add in the queue if (temp.left != null) { q.Enqueue(temp.left); // Set temp's left node's parent // as temp parent[temp.left.data] = temp.data; } // If current node has right // child, add in the queue if (temp.right != null) { q.Enqueue(temp.right); // Set temp's right node's parent // as temp parent[temp.right.data] = temp.data; } } } // Recursive function to print the // first shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path Console.Write(LeafData + " ");} // Driver Codepublic static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(10); root.left.left.right = newNode(11); root.right.right.left = newNode(8); leftMostShortest(root);}} // This code is contributed by rutvik_56 <script> // JavaScript program to print first // shortest root to leaf path // Binary tree node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to create a new // Binary node function newNode(data) { let temp = new Node(data); return temp; } // Recursive function used by leftMostShortest // to print the first shortest root to leaf path function printPath(Data, parent) { // If the root's data is same as // its parent data then return if (parent.get(Data) == Data) return; // Recur for the function printPath printPath(parent.get(Data), parent); // Print the parent node's data document.write(parent.get(Data) + " "); } // Function to perform level order traversal // until we find the first leaf node function leftMostShortest(root) { // Queue to store the nodes let q = []; // Add the root node q.push(root); // Initialize the value of first // leaf node to occur as -1 let LeafData = -1; // To store the current node let temp = null; // Map to store the parent node's data let parent = new Map(); // Parent of root data is set as it's // own value parent.set(root.data, root.data); // We store first node of the smallest level while (q.length > 0) { temp = q[0]; q.shift(); // If the first leaf node has been found // set the flag variable as 1 if (temp.left == null && temp.right == null) { LeafData = temp.data; break; } else { // If current node has left // child, add in the queue if (temp.left != null) { q.push(temp.left); // Set temp's left node's parent // as temp parent.set(temp.left.data, temp.data); } // If current node has right // child, add in the queue if (temp.right != null) { q.push(temp.right); // Set temp's right node's parent // as temp parent.set(temp.right.data, temp.data); } } } // Recursive function to print the // first shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path document.write(LeafData + " "); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(10); root.left.left.right = newNode(11); root.right.right.left = newNode(8); leftMostShortest(root); </script> 1 3 5 Time Complexity: O(N) Auxiliary Space: O(N) rituraj_jain sanjeev2552 rutvik_56 mukesh07 pankajsharmagfg Binary Tree tree-level-order Data Structures Hash Tree Data Structures Hash Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms How to Start Learning DSA? Hash Map in Python Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26685, "s": 26657, "text": "\n06 Aug, 2021" }, { "code": null, "e": 26882, "s": 26685, "text": "Given a Binary Tree with distinct values, the task is to print the first smallest root to leaf path. We basically need to print the leftmost root to leaf path that has the minimum number of nodes." }, { "code": null, "e": 27149, "s": 26882, "text": "Input:\n 1\n / \\\n 2 3\n / / \\\n 4 5 7\n / \\ \\\n 10 11 8\nOutput: 1 3 5\n\n\nInput:\n 1\n / \\\n 2 3\n / / \\\n 40 5 7\n \\\n 8\nOutput: 1 2 40" }, { "code": null, "e": 27412, "s": 27149, "text": "Approach: The idea is to use a queue to perform level order traversal, a map parent to store the nodes that will be present in the shortest path. Using level order traversal, we find the leftmost leaf. Once we find the leftmost leaf, we print path using the map." }, { "code": null, "e": 27463, "s": 27412, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27467, "s": 27463, "text": "C++" }, { "code": null, "e": 27472, "s": 27467, "text": "Java" }, { "code": null, "e": 27480, "s": 27472, "text": "Python3" }, { "code": null, "e": 27483, "s": 27480, "text": "C#" }, { "code": null, "e": 27494, "s": 27483, "text": "Javascript" }, { "code": "// C++ program to print first shortest// root to leaf path#include <bits/stdc++.h>using namespace std; // Binary tree nodestruct Node { struct Node* left; struct Node* right; int data;}; // Function to create a new// Binary nodestruct Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // Recursive function used by leftMostShortest// to print the first shortest root to leaf pathvoid printPath(int Data, unordered_map<int, int> parent){ // If the root's data is same as // its parent data then return if (parent[Data] == Data) return; // Recur for the function printPath printPath(parent[Data], parent); // Print the parent node's data cout << parent[Data] << \" \";} // Function to perform level order traversal// until we find the first leaf nodevoid leftMostShortest(struct Node* root){ // Queue to store the nodes queue<struct Node*> q; // Push the root node q.push(root); // Initialize the value of first // leaf node to occur as -1 int LeafData = -1; // To store the current node struct Node* temp = NULL; // Map to store the parent node's data unordered_map<int, int> parent; // Parent of root data is set as it's // own value parent[root->data] = root->data; // We store first node of the smallest level while (!q.empty()) { temp = q.front(); q.pop(); // If the first leaf node has been found // set the flag variable as 1 if (!temp->left && !temp->right) { LeafData = temp->data; break; } else { // If current node has left // child, push in the queue if (temp->left) { q.push(temp->left); // Set temp's left node's parent as temp parent[temp->left->data] = temp->data; } // If current node has right // child, push in the queue if (temp->right) { q.push(temp->right); // Set temp's right node's parent // as temp parent[temp->right->data] = temp->data; } } } // Recursive function to print the first // shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path cout << LeafData << \" \";} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(7); root->left->left->left = newNode(10); root->left->left->right = newNode(11); root->right->right->left = newNode(8); leftMostShortest(root); return 0;}", "e": 30345, "s": 27494, "text": null }, { "code": "// Java program to print first shortest// root to leaf pathimport java.util.*; class GFG{ // Binary tree nodestatic class Node{ Node left; Node right; int data;}; // Function to create a new// Binary nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} // Recursive function used by leftMostShortest// to print the first shortest root to leaf pathstatic void printPath(int Data, HashMap<Integer, Integer> parent){ // If the root's data is same as // its parent data then return if (parent.get(Data) == Data) return; // Recur for the function printPath printPath(parent.get(Data), parent); // Print the parent node's data System.out.print(parent.get(Data) + \" \");} // Function to perform level order traversal// until we find the first leaf nodestatic void leftMostShortest(Node root){ // Queue to store the nodes Queue<Node> q = new LinkedList<>(); // Add the root node q.add(root); // Initialize the value of first // leaf node to occur as -1 int LeafData = -1; // To store the current node Node temp = null; // Map to store the parent node's data HashMap<Integer, Integer> parent = new HashMap<>(); // Parent of root data is set as it's // own value parent.put(root.data, root.data); // We store first node of the smallest level while (!q.isEmpty()) { temp = q.poll(); // If the first leaf node has been found // set the flag variable as 1 if (temp.left == null && temp.right == null) { LeafData = temp.data; break; } else { // If current node has left // child, add in the queue if (temp.left != null) { q.add(temp.left); // Set temp's left node's parent // as temp parent.put(temp.left.data, temp.data); } // If current node has right // child, add in the queue if (temp.right != null) { q.add(temp.right); // Set temp's right node's parent // as temp parent.put(temp.right.data, temp.data); } } } // Recursive function to print the // first shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path System.out.println(LeafData + \" \");} // Driver Codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(10); root.left.left.right = newNode(11); root.right.right.left = newNode(8); leftMostShortest(root);}} // This code is contributed by sanjeev2552", "e": 33432, "s": 30345, "text": null }, { "code": "# Python3 program to print first# shortest root to leaf path # Binary tree nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Recursive function used by leftMostShortest# to print the first shortest root to leaf pathdef printPath(Data, parent): # If the root's data is same as # its parent data then return if parent[Data] == Data: return # Recur for the function printPath printPath(parent[Data], parent) # Print the parent node's data print(parent[Data], end = \" \") # Function to perform level order traversal# until we find the first leaf nodedef leftMostShortest(root): # Queue to store the nodes q = [] # Push the root node q.append(root) # Initialize the value of first # leaf node to occur as -1 LeafData = -1 # To store the current node temp = None # Map to store the parent node's data parent = {} # Parent of root data is set # as it's own value parent[root.data] = root.data # We store first node of the # smallest level while len(q) != 0: temp = q.pop(0) # If the first leaf node has been # found set the flag variable as 1 if not temp.left and not temp.right: LeafData = temp.data break else: # If current node has left # child, push in the queue if temp.left: q.append(temp.left) # Set temp's left node's parent as temp parent[temp.left.data] = temp.data # If current node has right # child, push in the queue if temp.right: q.append(temp.right) # Set temp's right node's parent # as temp parent[temp.right.data] = temp.data # Recursive function to print the first # shortest root to leaf path printPath(LeafData, parent) # Print the leaf node of the # first shortest path print(LeafData, end = \" \") # Driver codeif __name__ == \"__main__\": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.left = Node(5) root.right.right = Node(7) root.left.left.left = Node(10) root.left.left.right = Node(11) root.right.right.left = Node(8) leftMostShortest(root) # This code is contributed by Rituraj Jain", "e": 35850, "s": 33432, "text": null }, { "code": "// C# program to print first shortest// root to leaf pathusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Binary tree nodepublic class Node{ public Node left; public Node right; public int data;}; // Function to create a new// Binary nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} // Recursive function used by leftMostShortest// to print the first shortest root to leaf pathstatic void printPath(int Data, Dictionary<int, int> parent){ // If the root's data is same as // its parent data then return if (parent[Data] == Data) return; // Recur for the function printPath printPath(parent[Data], parent); // Print the parent node's data Console.Write(parent[Data] + \" \");} // Function to perform level order traversal// until we find the first leaf nodestatic void leftMostShortest(Node root){ // Queue to store the nodes Queue q = new Queue(); // Add the root node q.Enqueue(root); // Initialize the value of first // leaf node to occur as -1 int LeafData = -1; // To store the current node Node temp = null; // Map to store the parent node's data Dictionary<int, int> parent = new Dictionary<int, int>(); // Parent of root data is set as it's // own value parent[root.data] = root.data; // We store first node of the // smallest level while (q.Count != 0) { temp = (Node)q.Dequeue(); // If the first leaf node has been // found set the flag variable as 1 if (temp.left == null && temp.right == null) { LeafData = temp.data; break; } else { // If current node has left // child, add in the queue if (temp.left != null) { q.Enqueue(temp.left); // Set temp's left node's parent // as temp parent[temp.left.data] = temp.data; } // If current node has right // child, add in the queue if (temp.right != null) { q.Enqueue(temp.right); // Set temp's right node's parent // as temp parent[temp.right.data] = temp.data; } } } // Recursive function to print the // first shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path Console.Write(LeafData + \" \");} // Driver Codepublic static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(10); root.left.left.right = newNode(11); root.right.right.left = newNode(8); leftMostShortest(root);}} // This code is contributed by rutvik_56", "e": 38971, "s": 35850, "text": null }, { "code": "<script> // JavaScript program to print first // shortest root to leaf path // Binary tree node class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to create a new // Binary node function newNode(data) { let temp = new Node(data); return temp; } // Recursive function used by leftMostShortest // to print the first shortest root to leaf path function printPath(Data, parent) { // If the root's data is same as // its parent data then return if (parent.get(Data) == Data) return; // Recur for the function printPath printPath(parent.get(Data), parent); // Print the parent node's data document.write(parent.get(Data) + \" \"); } // Function to perform level order traversal // until we find the first leaf node function leftMostShortest(root) { // Queue to store the nodes let q = []; // Add the root node q.push(root); // Initialize the value of first // leaf node to occur as -1 let LeafData = -1; // To store the current node let temp = null; // Map to store the parent node's data let parent = new Map(); // Parent of root data is set as it's // own value parent.set(root.data, root.data); // We store first node of the smallest level while (q.length > 0) { temp = q[0]; q.shift(); // If the first leaf node has been found // set the flag variable as 1 if (temp.left == null && temp.right == null) { LeafData = temp.data; break; } else { // If current node has left // child, add in the queue if (temp.left != null) { q.push(temp.left); // Set temp's left node's parent // as temp parent.set(temp.left.data, temp.data); } // If current node has right // child, add in the queue if (temp.right != null) { q.push(temp.right); // Set temp's right node's parent // as temp parent.set(temp.right.data, temp.data); } } } // Recursive function to print the // first shortest root to leaf path printPath(LeafData, parent); // Print the leaf node of the first // shortest path document.write(LeafData + \" \"); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(7); root.left.left.left = newNode(10); root.left.left.right = newNode(11); root.right.right.left = newNode(8); leftMostShortest(root); </script>", "e": 42168, "s": 38971, "text": null }, { "code": null, "e": 42174, "s": 42168, "text": "1 3 5" }, { "code": null, "e": 42220, "s": 42176, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 42233, "s": 42220, "text": "rituraj_jain" }, { "code": null, "e": 42245, "s": 42233, "text": "sanjeev2552" }, { "code": null, "e": 42255, "s": 42245, "text": "rutvik_56" }, { "code": null, "e": 42264, "s": 42255, "text": "mukesh07" }, { "code": null, "e": 42280, "s": 42264, "text": "pankajsharmagfg" }, { "code": null, "e": 42292, "s": 42280, "text": "Binary Tree" }, { "code": null, "e": 42309, "s": 42292, "text": "tree-level-order" }, { "code": null, "e": 42325, "s": 42309, "text": "Data Structures" }, { "code": null, "e": 42330, "s": 42325, "text": "Hash" }, { "code": null, "e": 42335, "s": 42330, "text": "Tree" }, { "code": null, "e": 42351, "s": 42335, "text": "Data Structures" }, { "code": null, "e": 42356, "s": 42351, "text": "Hash" }, { "code": null, "e": 42361, "s": 42356, "text": "Tree" }, { "code": null, "e": 42459, "s": 42361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42508, "s": 42459, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 42533, "s": 42508, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 42560, "s": 42533, "text": "Introduction to Algorithms" }, { "code": null, "e": 42587, "s": 42560, "text": "How to Start Learning DSA?" }, { "code": null, "e": 42606, "s": 42587, "text": "Hash Map in Python" }, { "code": null, "e": 42691, "s": 42606, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 42727, "s": 42691, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 42754, "s": 42727, "text": "Count pairs with given sum" }, { "code": null, "e": 42785, "s": 42754, "text": "Hashing | Set 1 (Introduction)" } ]
Mindtree Interview Experience for Software Engineer C1 | Off-Campus 2021 - GeeksforGeeks
16 Dec, 2021 I had applied for Mindtree Software Engineer C1 (Off-Campus) in the first week of November. The entire process was conducted on WeCP platform, in which one can write as well as compile codes which will be visible to the interviewer. The hiring process comprised of 3 rounds. Round 1: I had my online assessment scheduled on 13th November. The duration was 120 minutes. It had four sections: Programming, Verbal Ability, Quantitative Ability, and Logical Ability. The programing (C/C++ or Java only) section further had three parts: Implementation: 2 questions of 50 marks each DS and Algorithm: 2 questions of 75 marks each Advanced Algorithm: 2 questions of 100 marks each Round 2: My Technical interview was scheduled on November 23rd. The duration was 35 minutes. The questions that were asked to me are: Tell me about yourself Difference between data abstraction and encapsulation What is interface class What is dynamic polymorphism and overriding concept What is protected access modifier What is constructor and its types What is destructor What is garbage collection What is pointer What is multiple inheritance What is collection Difference between array and array list What is dictionary How to do exception handling What is bubble sort and how is it different from selection sort What is double linked list What is ref keyword and out keyword Difference between stack and queue What is static constructor What is normalization What is 1nf and 2nf What are ACID properties Difference between primary key and unique key What is function What is inner join and outer join What is the use of HTML What is the use of CSS What is inline CSS What is the use of javascript Can we store integer value in a string variable The interviewer also asked me to write a few basic programs which are: Print the pattern54321 4321 321 21 1 54321 4321 321 21 1 Sort a given array using any sorting technique: int[]={1,4,,8,9,5,4,7,10} Write the 2nd highest salary from the table ‘Employee’ Design ‘Customer’ class with properties and methods The method should be called from outside. Round 3: My HR interview got scheduled on 7th December. The duration was almost 6 minutes. The questions which were asked are: Tell me about yourself Do you have any active backlogs Are you okay with relocation Tell me about your family background What do you expect from Mindtree Finally, I got my congratulatory mail from Mindtree on December 10th, which said that I had been shortlisted to receive an offer for the role of Software Engineer at Mindtree! Marketing Mindtree Off-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience Amazon Interview Experience for SDE-1 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1 (On-Campus) Infosys Interview Experience for DSE 2022 Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus) EPAM Interview Experience (Off-Campus)
[ { "code": null, "e": 26379, "s": 26351, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26654, "s": 26379, "text": "I had applied for Mindtree Software Engineer C1 (Off-Campus) in the first week of November. The entire process was conducted on WeCP platform, in which one can write as well as compile codes which will be visible to the interviewer. The hiring process comprised of 3 rounds." }, { "code": null, "e": 26911, "s": 26654, "text": "Round 1: I had my online assessment scheduled on 13th November. The duration was 120 minutes. It had four sections: Programming, Verbal Ability, Quantitative Ability, and Logical Ability. The programing (C/C++ or Java only) section further had three parts:" }, { "code": null, "e": 26956, "s": 26911, "text": "Implementation: 2 questions of 50 marks each" }, { "code": null, "e": 27003, "s": 26956, "text": "DS and Algorithm: 2 questions of 75 marks each" }, { "code": null, "e": 27053, "s": 27003, "text": "Advanced Algorithm: 2 questions of 100 marks each" }, { "code": null, "e": 27187, "s": 27053, "text": "Round 2: My Technical interview was scheduled on November 23rd. The duration was 35 minutes. The questions that were asked to me are:" }, { "code": null, "e": 27210, "s": 27187, "text": "Tell me about yourself" }, { "code": null, "e": 27264, "s": 27210, "text": "Difference between data abstraction and encapsulation" }, { "code": null, "e": 27288, "s": 27264, "text": "What is interface class" }, { "code": null, "e": 27340, "s": 27288, "text": "What is dynamic polymorphism and overriding concept" }, { "code": null, "e": 27374, "s": 27340, "text": "What is protected access modifier" }, { "code": null, "e": 27408, "s": 27374, "text": "What is constructor and its types" }, { "code": null, "e": 27427, "s": 27408, "text": "What is destructor" }, { "code": null, "e": 27454, "s": 27427, "text": "What is garbage collection" }, { "code": null, "e": 27470, "s": 27454, "text": "What is pointer" }, { "code": null, "e": 27499, "s": 27470, "text": "What is multiple inheritance" }, { "code": null, "e": 27518, "s": 27499, "text": "What is collection" }, { "code": null, "e": 27558, "s": 27518, "text": "Difference between array and array list" }, { "code": null, "e": 27577, "s": 27558, "text": "What is dictionary" }, { "code": null, "e": 27606, "s": 27577, "text": "How to do exception handling" }, { "code": null, "e": 27670, "s": 27606, "text": "What is bubble sort and how is it different from selection sort" }, { "code": null, "e": 27697, "s": 27670, "text": "What is double linked list" }, { "code": null, "e": 27733, "s": 27697, "text": "What is ref keyword and out keyword" }, { "code": null, "e": 27768, "s": 27733, "text": "Difference between stack and queue" }, { "code": null, "e": 27795, "s": 27768, "text": "What is static constructor" }, { "code": null, "e": 27817, "s": 27795, "text": "What is normalization" }, { "code": null, "e": 27837, "s": 27817, "text": "What is 1nf and 2nf" }, { "code": null, "e": 27862, "s": 27837, "text": "What are ACID properties" }, { "code": null, "e": 27908, "s": 27862, "text": "Difference between primary key and unique key" }, { "code": null, "e": 27925, "s": 27908, "text": "What is function" }, { "code": null, "e": 27959, "s": 27925, "text": "What is inner join and outer join" }, { "code": null, "e": 27983, "s": 27959, "text": "What is the use of HTML" }, { "code": null, "e": 28006, "s": 27983, "text": "What is the use of CSS" }, { "code": null, "e": 28025, "s": 28006, "text": "What is inline CSS" }, { "code": null, "e": 28055, "s": 28025, "text": "What is the use of javascript" }, { "code": null, "e": 28103, "s": 28055, "text": "Can we store integer value in a string variable" }, { "code": null, "e": 28174, "s": 28103, "text": "The interviewer also asked me to write a few basic programs which are:" }, { "code": null, "e": 28211, "s": 28174, "text": "Print the pattern54321\n4321\n321\n21\n1" }, { "code": null, "e": 28231, "s": 28211, "text": "54321\n4321\n321\n21\n1" }, { "code": null, "e": 28307, "s": 28231, "text": "Sort a given array using any sorting technique: int[]={1,4,,8,9,5,4,7,10}" }, { "code": null, "e": 28362, "s": 28307, "text": "Write the 2nd highest salary from the table ‘Employee’" }, { "code": null, "e": 28456, "s": 28362, "text": "Design ‘Customer’ class with properties and methods The method should be called from outside." }, { "code": null, "e": 28583, "s": 28456, "text": "Round 3: My HR interview got scheduled on 7th December. The duration was almost 6 minutes. The questions which were asked are:" }, { "code": null, "e": 28606, "s": 28583, "text": "Tell me about yourself" }, { "code": null, "e": 28638, "s": 28606, "text": "Do you have any active backlogs" }, { "code": null, "e": 28667, "s": 28638, "text": "Are you okay with relocation" }, { "code": null, "e": 28704, "s": 28667, "text": "Tell me about your family background" }, { "code": null, "e": 28737, "s": 28704, "text": "What do you expect from Mindtree" }, { "code": null, "e": 28913, "s": 28737, "text": "Finally, I got my congratulatory mail from Mindtree on December 10th, which said that I had been shortlisted to receive an offer for the role of Software Engineer at Mindtree!" }, { "code": null, "e": 28923, "s": 28913, "text": "Marketing" }, { "code": null, "e": 28932, "s": 28923, "text": "Mindtree" }, { "code": null, "e": 28943, "s": 28932, "text": "Off-Campus" }, { "code": null, "e": 28965, "s": 28943, "text": "Interview Experiences" }, { "code": null, "e": 29063, "s": 28965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29114, "s": 29063, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 29156, "s": 29114, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 29184, "s": 29156, "text": "Amazon Interview Experience" }, { "code": null, "e": 29222, "s": 29184, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 29294, "s": 29222, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 29340, "s": 29294, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 29390, "s": 29340, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 29432, "s": 29390, "text": "Infosys Interview Experience for DSE 2022" }, { "code": null, "e": 29509, "s": 29432, "text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)" } ]
jQWidgets jqxGrid getselectedrowindexes() Method - GeeksforGeeks
27 Oct, 2021 jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxGrid is used to illustrate a jQuery widget that shows data in tabular form. Moreover, it renders full support for connecting with data, as well as paging, grouping, sorting, filtering and editing. The getselectedrowindexes() method is used to return the indexes of the rows chosen. Where, the mode of selection is a single row, multiple rows, or multiplerowsextended. It has no parameters. It returns an array of picked rows. Syntax: var rowindexes = $('#Selector').jqxGrid('getselectedrowindexes'); Linked Files: Download https://www.jqwidgets.com/download/ from the given link. In the HTML file, locate the script files in the downloaded folder. <link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery-1.11.1.min.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqxdata.js”></script><script type=”text/javascript” src=”jqwidgets/jqxbuttons.js”></script><script type=”text/javascript” src=”jqwidgets/jqxscrollbar.js”></script><script type=”text/javascript” src=”jqwidgets/jqxmenu.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.selection.js”></script> The below example illustrates the jqxGrid getselectedrowindexes() method in jQWidgets. Example: HTML <!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href= "jqwidgets/styles/jqx.base.css" type="text/css" /> <script type="text/javascript" src="scripts/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="jqwidgets/jqxcore.js"></script> <script type="text/javascript" src="jqwidgets/jqxdata.js"></script> <script type="text/javascript" src="jqwidgets/jqxbuttons.js"></script> <script type="text/javascript" src="jqwidgets/jqxscrollbar.js"></script> <script type="text/javascript" src="jqwidgets/jqxmenu.js"></script> <script type="text/javascript" src="jqwidgets/jqxgrid.js"></script> <script type="text/javascript" src="jqwidgets/jqxgrid.selection.js"></script></head> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <h3>jQWidgets jqxGrid getselectedrowindexes() method </h3> <br /> <div id="jqxg"></div> <div> <input type="button" id="jqxBtn" style="margin-top: 25px" value="Click here" /> </div> <div id="log"></div> </center> <script type="text/javascript"> $(document).ready(function () { var d = new Array(); var subjectNames = ["C++", "Scala", "Java", "C", "R", "JavaScript"]; var pageNumber = ["7", "8", "12", "11", "10", "19"]; for (var j = 0; j < 50; j++) { var r = {}; r["subjectnames"] = subjectNames[Math.floor( Math.random() * subjectNames.length) ]; r["pagenumber"] = pageNumber[Math.floor( Math.random() * pageNumber.length) ]; d[j] = r; } var src = { localdata: d, datatype: "array", }; var data_Adapter = new $.jqx.dataAdapter(src); $("#jqxg").jqxGrid({ source: data_Adapter, selectionmode: 'multiplerows', height: "240px", width: "300px", columns: [ { text: "Subject Name", datafield: "subjectnames", width: "160px", }, { text: "Page No.", datafield: "pagenumber", width: "160px", }, ], }); $("#jqxBtn").jqxButton({ width: "180px", height: "30px", }); $("#jqxg").jqxGrid('selectrow', 2); $("#jqxg").jqxGrid('selectrow', 4); $("#jqxBtn").on("click", function () { var gsri = $('#jqxg').jqxGrid( 'getselectedrowindexes'); $("#log").text("Indexes of" + " selected rows: " + gsri); }); }); </script></body> </html> Output: Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-api.htm?search= jQuery-jQWidgets jQWidgets-jqxGrid JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26954, "s": 26926, "text": "\n27 Oct, 2021" }, { "code": null, "e": 27343, "s": 26954, "text": "jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxGrid is used to illustrate a jQuery widget that shows data in tabular form. Moreover, it renders full support for connecting with data, as well as paging, grouping, sorting, filtering and editing." }, { "code": null, "e": 27572, "s": 27343, "text": "The getselectedrowindexes() method is used to return the indexes of the rows chosen. Where, the mode of selection is a single row, multiple rows, or multiplerowsextended. It has no parameters. It returns an array of picked rows." }, { "code": null, "e": 27580, "s": 27572, "text": "Syntax:" }, { "code": null, "e": 27651, "s": 27580, "text": "var rowindexes = \n $('#Selector').jqxGrid('getselectedrowindexes');" }, { "code": null, "e": 27799, "s": 27651, "text": "Linked Files: Download https://www.jqwidgets.com/download/ from the given link. In the HTML file, locate the script files in the downloaded folder." }, { "code": null, "e": 28440, "s": 27799, "text": "<link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery-1.11.1.min.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqxdata.js”></script><script type=”text/javascript” src=”jqwidgets/jqxbuttons.js”></script><script type=”text/javascript” src=”jqwidgets/jqxscrollbar.js”></script><script type=”text/javascript” src=”jqwidgets/jqxmenu.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.selection.js”></script>" }, { "code": null, "e": 28527, "s": 28440, "text": "The below example illustrates the jqxGrid getselectedrowindexes() method in jQWidgets." }, { "code": null, "e": 28536, "s": 28527, "text": "Example:" }, { "code": null, "e": 28541, "s": 28536, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href= \"jqwidgets/styles/jqx.base.css\" type=\"text/css\" /> <script type=\"text/javascript\" src=\"scripts/jquery-1.11.1.min.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxcore.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxdata.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxbuttons.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxscrollbar.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxmenu.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxgrid.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxgrid.selection.js\"></script></head> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h3>jQWidgets jqxGrid getselectedrowindexes() method </h3> <br /> <div id=\"jqxg\"></div> <div> <input type=\"button\" id=\"jqxBtn\" style=\"margin-top: 25px\" value=\"Click here\" /> </div> <div id=\"log\"></div> </center> <script type=\"text/javascript\"> $(document).ready(function () { var d = new Array(); var subjectNames = [\"C++\", \"Scala\", \"Java\", \"C\", \"R\", \"JavaScript\"]; var pageNumber = [\"7\", \"8\", \"12\", \"11\", \"10\", \"19\"]; for (var j = 0; j < 50; j++) { var r = {}; r[\"subjectnames\"] = subjectNames[Math.floor( Math.random() * subjectNames.length) ]; r[\"pagenumber\"] = pageNumber[Math.floor( Math.random() * pageNumber.length) ]; d[j] = r; } var src = { localdata: d, datatype: \"array\", }; var data_Adapter = new $.jqx.dataAdapter(src); $(\"#jqxg\").jqxGrid({ source: data_Adapter, selectionmode: 'multiplerows', height: \"240px\", width: \"300px\", columns: [ { text: \"Subject Name\", datafield: \"subjectnames\", width: \"160px\", }, { text: \"Page No.\", datafield: \"pagenumber\", width: \"160px\", }, ], }); $(\"#jqxBtn\").jqxButton({ width: \"180px\", height: \"30px\", }); $(\"#jqxg\").jqxGrid('selectrow', 2); $(\"#jqxg\").jqxGrid('selectrow', 4); $(\"#jqxBtn\").on(\"click\", function () { var gsri = $('#jqxg').jqxGrid( 'getselectedrowindexes'); $(\"#log\").text(\"Indexes of\" + \" selected rows: \" + gsri); }); }); </script></body> </html>", "e": 31692, "s": 28541, "text": null }, { "code": null, "e": 31700, "s": 31692, "text": "Output:" }, { "code": null, "e": 31816, "s": 31700, "text": "Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-api.htm?search=" }, { "code": null, "e": 31833, "s": 31816, "text": "jQuery-jQWidgets" }, { "code": null, "e": 31851, "s": 31833, "text": "jQWidgets-jqxGrid" }, { "code": null, "e": 31858, "s": 31851, "text": "JQuery" }, { "code": null, "e": 31875, "s": 31858, "text": "Web Technologies" }, { "code": null, "e": 31973, "s": 31875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32028, "s": 31973, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 32101, "s": 32028, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 32124, "s": 32101, "text": "jQuery | ajax() Method" }, { "code": null, "e": 32160, "s": 32124, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 32217, "s": 32160, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 32257, "s": 32217, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32290, "s": 32257, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32335, "s": 32290, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32378, "s": 32335, "text": "How to fetch data from an API in ReactJS ?" } ]
Analysis of different sorting techniques - GeeksforGeeks
28 Jun, 2021 In this article, we will discuss important properties of different sorting techniques including their complexity, stability and memory constraints. Before understanding this article, you should understand basics of different sorting techniques (See : Sorting Techniques). Time complexity Analysis – We have discussed the best, average and worst case complexity of different sorting techniques with possible scenarios. Comparison based sorting – In comparison based sorting, elements of an array are compared with each other to find the sorted array. Bubble sort and Insertion sort – Average and worst case time complexity: n^2 Best case time complexity: n when array is already sorted. Worst case: when the array is reverse sorted. Selection sort – Best, average and worst case time complexity: n^2 which is independent of distribution of data. Merge sort – Best, average and worst case time complexity: nlogn which is independent of distribution of data. Heap sort – Best, average and worst case time complexity: nlogn which is independent of distribution of data. Quick sort – It is a divide and conquer approach with recurrence relation: T(n) = T(k) + T(n-k-1) + cn Worst case: when the array is sorted or reverse sorted, the partition algorithm divides the array in two subarrays with 0 and n-1 elements. Therefore, T(n) = T(0) + T(n-1) + cn Solving this we get, T(n) = O(n^2) Best case and Average case: On an average, the partition algorithm divides the array in two subarrays with equal size. Therefore, T(n) = 2T(n/2) + cn Solving this we get, T(n) = O(nlogn) Non-comparison based sorting – In non-comparison based sorting, elements of array are not compared with each other to find the sorted array. Radix sort – Best, average and worst case time complexity: nk where k is the maximum number of digits in elements of array. Count sort – Best, average and worst case time complexity: n+k where k is the size of count array. Bucket sort – Best and average time complexity: n+k where k is the number of buckets. Worst case time complexity: n^2 if all elements belong to same bucket. In-place/Outplace technique – A sorting technique is inplace if it does not use any extra memory to sort the array. Among the comparison based techniques discussed, only merge sort is outplaced technique as it requires an extra array to merge the sorted subarrays. Among the non-comparison based techniques discussed, all are outplaced techniques. Counting sort uses a counting array and bucket sort uses a hash table for sorting the array. Online/Offline technique – A sorting technique is considered Online if it can accept new data while the procedure is ongoing i.e. complete data is not required to start the sorting operation. Among the comparison based techniques discussed, only Insertion Sort qualifies for this because of the underlying algorithm it uses i.e. it processes the array (not just elements) from left to right and if new elements are added to the right, it doesn’t impact the ongoing operation. Stable/Unstable technique – A sorting technique is stable if it does not change the order of elements with the same value. Out of comparison based techniques, bubble sort, insertion sort and merge sort are stable techniques. Selection sort is unstable as it may change the order of elements with the same value. For example, consider the array 4, 4, 1, 3. In the first iteration, the minimum element found is 1 and it is swapped with 4 at 0th position. Therefore, the order of 4 with respect to 4 at the 1st position will change. Similarly, quick sort and heap sort are also unstable. Out of non-comparison based techniques, Counting sort and Bucket sort are stable sorting techniques whereas radix sort stability depends on the underlying algorithm used for sorting. Analysis of sorting techniques : When the array is almost sorted, insertion sort can be preferred. When order of input is not known, merge sort is preferred as it has worst case time complexity of nlogn and it is stable as well. When the array is sorted, insertion and bubble sort gives complexity of n but quick sort gives complexity of n^2. Que – 1. Which sorting algorithm will take the least time when all elements of input array are identical? Consider typical implementations of sorting algorithms. (A) Insertion Sort (B) Heap Sort (C) Merge Sort (D) Selection Sort Solution: As discussed, insertion sort will have the complexity of n when the input array is already sorted. Que – 2. Consider the Quicksort algorithm. Suppose there is a procedure for finding a pivot element which splits the list into two sub-lists each of which contains at least one-fifth of the elements. Let T(n) be the number of comparisons required to sort n elements. Then, (GATE-CS-2012) (A) T(n) <= 2T(n/5) + n (B) T(n) <= T(n/5) + T(4n/5) + n (C) T(n) <= 2T(4n/5) + n (D) T(n) <= 2T(n/2) + n Solution: The complexity of quick sort can be written as: T(n) = T(k) + T(n-k-1) + cn As given in question, one list contains 1/5th of total elements. Therefore, another list will have 4/5 of total elements. Putting values, we get: T(n) = T(n/5) + T(4n/5) + cn, which matches option (B). Akshay Gaursundar mdamircoder ayushmangehlot8 Analysis GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Difference between Deterministic and Non-deterministic Algorithms Complexity analysis of various operations of Binary Min Heap Pseudo-polynomial Algorithms Proof that Hamiltonian Cycle is NP-Complete Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 26207, "s": 26179, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26480, "s": 26207, "text": "In this article, we will discuss important properties of different sorting techniques including their complexity, stability and memory constraints. Before understanding this article, you should understand basics of different sorting techniques (See : Sorting Techniques). " }, { "code": null, "e": 26627, "s": 26480, "text": "Time complexity Analysis – We have discussed the best, average and worst case complexity of different sorting techniques with possible scenarios. " }, { "code": null, "e": 26760, "s": 26627, "text": "Comparison based sorting – In comparison based sorting, elements of an array are compared with each other to find the sorted array. " }, { "code": null, "e": 26946, "s": 26762, "text": "Bubble sort and Insertion sort – Average and worst case time complexity: n^2 Best case time complexity: n when array is already sorted. Worst case: when the array is reverse sorted. " }, { "code": null, "e": 27061, "s": 26946, "text": "Selection sort – Best, average and worst case time complexity: n^2 which is independent of distribution of data. " }, { "code": null, "e": 27174, "s": 27061, "text": "Merge sort – Best, average and worst case time complexity: nlogn which is independent of distribution of data. " }, { "code": null, "e": 27286, "s": 27174, "text": "Heap sort – Best, average and worst case time complexity: nlogn which is independent of distribution of data. " }, { "code": null, "e": 27363, "s": 27286, "text": "Quick sort – It is a divide and conquer approach with recurrence relation: " }, { "code": null, "e": 27392, "s": 27363, "text": " T(n) = T(k) + T(n-k-1) + cn" }, { "code": null, "e": 27545, "s": 27392, "text": "Worst case: when the array is sorted or reverse sorted, the partition algorithm divides the array in two subarrays with 0 and n-1 elements. Therefore, " }, { "code": null, "e": 27606, "s": 27545, "text": "T(n) = T(0) + T(n-1) + cn\nSolving this we get, T(n) = O(n^2)" }, { "code": null, "e": 27738, "s": 27606, "text": "Best case and Average case: On an average, the partition algorithm divides the array in two subarrays with equal size. Therefore, " }, { "code": null, "e": 27796, "s": 27738, "text": "T(n) = 2T(n/2) + cn\nSolving this we get, T(n) = O(nlogn)\n" }, { "code": null, "e": 27939, "s": 27796, "text": "Non-comparison based sorting – In non-comparison based sorting, elements of array are not compared with each other to find the sorted array. " }, { "code": null, "e": 28065, "s": 27939, "text": "Radix sort – Best, average and worst case time complexity: nk where k is the maximum number of digits in elements of array. " }, { "code": null, "e": 28166, "s": 28065, "text": "Count sort – Best, average and worst case time complexity: n+k where k is the size of count array. " }, { "code": null, "e": 28325, "s": 28166, "text": "Bucket sort – Best and average time complexity: n+k where k is the number of buckets. Worst case time complexity: n^2 if all elements belong to same bucket. " }, { "code": null, "e": 28767, "s": 28325, "text": "In-place/Outplace technique – A sorting technique is inplace if it does not use any extra memory to sort the array. Among the comparison based techniques discussed, only merge sort is outplaced technique as it requires an extra array to merge the sorted subarrays. Among the non-comparison based techniques discussed, all are outplaced techniques. Counting sort uses a counting array and bucket sort uses a hash table for sorting the array. " }, { "code": null, "e": 29244, "s": 28767, "text": "Online/Offline technique – A sorting technique is considered Online if it can accept new data while the procedure is ongoing i.e. complete data is not required to start the sorting operation. Among the comparison based techniques discussed, only Insertion Sort qualifies for this because of the underlying algorithm it uses i.e. it processes the array (not just elements) from left to right and if new elements are added to the right, it doesn’t impact the ongoing operation. " }, { "code": null, "e": 29601, "s": 29244, "text": "Stable/Unstable technique – A sorting technique is stable if it does not change the order of elements with the same value. Out of comparison based techniques, bubble sort, insertion sort and merge sort are stable techniques. Selection sort is unstable as it may change the order of elements with the same value. For example, consider the array 4, 4, 1, 3. " }, { "code": null, "e": 29831, "s": 29601, "text": "In the first iteration, the minimum element found is 1 and it is swapped with 4 at 0th position. Therefore, the order of 4 with respect to 4 at the 1st position will change. Similarly, quick sort and heap sort are also unstable. " }, { "code": null, "e": 30015, "s": 29831, "text": "Out of non-comparison based techniques, Counting sort and Bucket sort are stable sorting techniques whereas radix sort stability depends on the underlying algorithm used for sorting. " }, { "code": null, "e": 30050, "s": 30015, "text": "Analysis of sorting techniques : " }, { "code": null, "e": 30116, "s": 30050, "text": "When the array is almost sorted, insertion sort can be preferred." }, { "code": null, "e": 30246, "s": 30116, "text": "When order of input is not known, merge sort is preferred as it has worst case time complexity of nlogn and it is stable as well." }, { "code": null, "e": 30360, "s": 30246, "text": "When the array is sorted, insertion and bubble sort gives complexity of n but quick sort gives complexity of n^2." }, { "code": null, "e": 30590, "s": 30360, "text": "Que – 1. Which sorting algorithm will take the least time when all elements of input array are identical? Consider typical implementations of sorting algorithms. (A) Insertion Sort (B) Heap Sort (C) Merge Sort (D) Selection Sort " }, { "code": null, "e": 30700, "s": 30590, "text": "Solution: As discussed, insertion sort will have the complexity of n when the input array is already sorted. " }, { "code": null, "e": 30988, "s": 30700, "text": "Que – 2. Consider the Quicksort algorithm. Suppose there is a procedure for finding a pivot element which splits the list into two sub-lists each of which contains at least one-fifth of the elements. Let T(n) be the number of comparisons required to sort n elements. Then, (GATE-CS-2012)" }, { "code": null, "e": 31012, "s": 30988, "text": "(A) T(n) <= 2T(n/5) + n" }, { "code": null, "e": 31045, "s": 31012, "text": "(B) T(n) <= T(n/5) + T(4n/5) + n" }, { "code": null, "e": 31070, "s": 31045, "text": "(C) T(n) <= 2T(4n/5) + n" }, { "code": null, "e": 31094, "s": 31070, "text": "(D) T(n) <= 2T(n/2) + n" }, { "code": null, "e": 31154, "s": 31094, "text": "Solution: The complexity of quick sort can be written as: " }, { "code": null, "e": 31182, "s": 31154, "text": "T(n) = T(k) + T(n-k-1) + cn" }, { "code": null, "e": 31329, "s": 31182, "text": "As given in question, one list contains 1/5th of total elements. Therefore, another list will have 4/5 of total elements. Putting values, we get: " }, { "code": null, "e": 31386, "s": 31329, "text": "T(n) = T(n/5) + T(4n/5) + cn, which matches option (B). " }, { "code": null, "e": 31406, "s": 31388, "text": "Akshay Gaursundar" }, { "code": null, "e": 31418, "s": 31406, "text": "mdamircoder" }, { "code": null, "e": 31434, "s": 31418, "text": "ayushmangehlot8" }, { "code": null, "e": 31443, "s": 31434, "text": "Analysis" }, { "code": null, "e": 31451, "s": 31443, "text": "GATE CS" }, { "code": null, "e": 31549, "s": 31451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31616, "s": 31549, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 31682, "s": 31616, "text": "Difference between Deterministic and Non-deterministic Algorithms" }, { "code": null, "e": 31743, "s": 31682, "text": "Complexity analysis of various operations of Binary Min Heap" }, { "code": null, "e": 31772, "s": 31743, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 31816, "s": 31772, "text": "Proof that Hamiltonian Cycle is NP-Complete" }, { "code": null, "e": 31836, "s": 31816, "text": "Layers of OSI Model" }, { "code": null, "e": 31860, "s": 31836, "text": "ACID Properties in DBMS" }, { "code": null, "e": 31873, "s": 31860, "text": "TCP/IP Model" }, { "code": null, "e": 31900, "s": 31873, "text": "Types of Operating Systems" } ]
disabled - Django Form Field Validation - GeeksforGeeks
13 Feb, 2020 Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data. Syntax field_name = models.Field(option = value) Illustration of disabled using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into forms.py file of geeks app. We will be using CharField for experimenting for all field options. from django import forms class GeeksForm(forms.Form): geeks_field = forms.CharField(disabled = True) Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py of geeks app, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} form = GeeksForm(request.POST or None) context['form'] = form if request.POST: if form.is_valid(): temp = form.cleaned_data.get("geeks_field") print(temp) return render(request, "home.html", context) Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. <form method = "POST"> {% csrf_token %} {{ form }} <input type = "submit" value = "Submit"></form> Finally, a URL to map to this view in urls.py from django.urls import path # importing views from views..pyfrom .views import home_view URLpatterns = [ path('', home_view ),] Let’s run the server and check what has actually happened, Run Python manage.py runserver Thus, an geeks_field CharField is created with disabled attribute and field is uneditable by user. NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 25875, "s": 25847, "text": "\n13 Feb, 2020" }, { "code": null, "e": 26120, "s": 25875, "text": "Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments." }, { "code": null, "e": 26406, "s": 26120, "text": "The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data." }, { "code": null, "e": 26413, "s": 26406, "text": "Syntax" }, { "code": null, "e": 26455, "s": 26413, "text": "field_name = models.Field(option = value)" }, { "code": null, "e": 26564, "s": 26455, "text": "Illustration of disabled using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 26651, "s": 26564, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 26702, "s": 26651, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26735, "s": 26702, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26861, "s": 26735, "text": "Enter the following code into forms.py file of geeks app. We will be using CharField for experimenting for all field options." }, { "code": "from django import forms class GeeksForm(forms.Form): geeks_field = forms.CharField(disabled = True)", "e": 26966, "s": 26861, "text": null }, { "code": null, "e": 27002, "s": 26966, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 27240, "s": 27002, "text": null }, { "code": null, "e": 27374, "s": 27240, "text": "Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py of geeks app," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} form = GeeksForm(request.POST or None) context['form'] = form if request.POST: if form.is_valid(): temp = form.cleaned_data.get(\"geeks_field\") print(temp) return render(request, \"home.html\", context)", "e": 27745, "s": 27374, "text": null }, { "code": null, "e": 28031, "s": 27745, "text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html." }, { "code": "<form method = \"POST\"> {% csrf_token %} {{ form }} <input type = \"submit\" value = \"Submit\"></form>", "e": 28139, "s": 28031, "text": null }, { "code": null, "e": 28185, "s": 28139, "text": "Finally, a URL to map to this view in urls.py" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import home_view URLpatterns = [ path('', home_view ),]", "e": 28319, "s": 28185, "text": null }, { "code": null, "e": 28382, "s": 28319, "text": "Let’s run the server and check what has actually happened, Run" }, { "code": null, "e": 28409, "s": 28382, "text": "Python manage.py runserver" }, { "code": null, "e": 28508, "s": 28409, "text": "Thus, an geeks_field CharField is created with disabled attribute and field is uneditable by user." }, { "code": null, "e": 28520, "s": 28508, "text": "NaveenArora" }, { "code": null, "e": 28533, "s": 28520, "text": "Django-forms" }, { "code": null, "e": 28547, "s": 28533, "text": "Python Django" }, { "code": null, "e": 28554, "s": 28547, "text": "Python" }, { "code": null, "e": 28652, "s": 28554, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28670, "s": 28652, "text": "Python Dictionary" }, { "code": null, "e": 28705, "s": 28670, "text": "Read a file line by line in Python" }, { "code": null, "e": 28737, "s": 28705, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28759, "s": 28737, "text": "Enumerate() in Python" }, { "code": null, "e": 28801, "s": 28759, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28831, "s": 28801, "text": "Iterate over a list in Python" }, { "code": null, "e": 28857, "s": 28831, "text": "Python String | replace()" }, { "code": null, "e": 28901, "s": 28857, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28930, "s": 28901, "text": "*args and **kwargs in Python" } ]
Divide every element of one array by other array elements - GeeksforGeeks
26 Feb, 2021 Given two arrays and the operation to be performed is that the every element of a[] should be divided by all the element of b[] and their floor value has to be calculated.Examples : Input : a[] = {5, 100, 8}, b[] = {2, 3} Output : 0 16 1 Explanation : Size of a[] is 3. Size of b[] is 2. Now 5 has to be divided by the elements of array b[] i.e. 5 is divided by 2, then the quotient obtained is divided by 3 and the floor value of this is calculated. The same process is repeated for the other array elements. First Approach : This solution is of complexity O(n * m) where size of a[] is n and size of array b[] is m. In this solution we fix the elements of array a[] and iterate it with the elements of array b[].Second Approach : In this method we have used simple maths. We first find product of array B and then divide it by each array element of a[] The complexity of this solution is O(n). C++ Java Python3 C# PHP Javascript // CPP program to find quotient of array// elements#include <bits/stdc++.h>using namespace std; // Function to calculate the quotient// of every element of the arrayvoid calculate(int a[], int b[], int n, int m){ int mul = 1; // Calculate the product of all elements for (int i = 0 ; i < m ; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (int i = 0 ; i < n ; i++) { int x = floor(a[i] / mul); cout << x << " "; }} // Driver codeint main(){ int a[] = {5 , 100 , 8}; int b[] = {2 , 3}; int n = sizeof(a)/sizeof(a[0]); int m = sizeof(b)/sizeof(b[0]); calculate(a, b, n, m); return 0;} // Java program to find quotient of array// elements import java.io.*; class GFG { // Function to calculate the quotient // of every element of the array static void calculate(int a[], int b[], int n, int m) { int mul = 1; // Calculate the product of all // elements for (int i = 0; i < m; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (int i = 0; i < n; i++) { int x = (int)Math.floor(a[i] / mul); System.out.print(x + " "); } } public static void main(String[] args) { int a[] = { 5, 100, 8 }; int b[] = { 2, 3 }; int n = a.length; int m = b.length; calculate(a, b, n, m); }} // This code is contributed by Ajit. # Python3 program to find# quotient of arrayelementsimport math # Function to calculate the quotient# of every element of the arraydef calculate(a, b, n, m): mul = 1 # Calculate the product # of all elements for i in range(m): if (b[i] != 0): mul = mul * b[i] # To calculate the quotient # of every array element for i in range(n): x = math.floor(a[i] / mul) print(x, end = " ") # Driver codea = [ 5, 100, 8 ]b = [ 2, 3 ]n = len(a)m = len(b) calculate(a, b, n, m) # This code is contributed by Anant Agarwal. // C# program to find quotient// of array elementsusing System; class GFG { // Function to calculate the quotient // of every element of the array static void calculate(int []a, int []b, int n, int m) { int mul = 1; // Calculate the product of all // elements for (int i = 0; i < m; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (int i = 0; i < n; i++) { int x = (int)Math.Floor((double)(a[i] / mul)); Console.Write(x + " "); } } // Driver code public static void Main() { int []a = { 5, 100, 8 }; int []b = { 2, 3 }; int n = a.Length; int m = b.Length; calculate(a, b, n, m); }} // This code is contributed by Anant Agarwal. <?php// PHP program to find// quotient of array elements // Function to calculate// the quotient of every// element of the arrayfunction calculate( $a, $b, $n, $m){$mul = 1; // Calculate the product // of all elements for ( $i = 0 ; $i < $m ; $i++) if ($b[$i] != 0) $mul = $mul * $b[$i]; // To calculate the quotient // of every array element for ( $i = 0 ; $i < $n ; $i++) { $x = floor($a[$i] / $mul); echo $x , " "; }} // Driver code$a = array(5 , 100 , 8);$b = array(2 , 3); $n = count($a); $m = count($b); calculate($a, $b, $n, $m); // This code is contributed by anuju_67.?> <script> // JavaScript program to find quotient of array// elements // Function to calculate the quotient// of every element of the arrayfunction calculate(a, b, n, m){ let mul = 1; // Calculate the product of all elements for (let i = 0 ; i < m ; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (let i = 0 ; i < n ; i++) { let x = Math.floor(a[i] / mul); document.write(x + " "); }} // Driver code let a = [5 , 100 , 8]; let b = [2 , 3]; let n = a.length; let m = b.length; calculate(a, b, n, m); // This code is contributed by Surbhi Tyagi </script> Output : 0 16 1 vt_m surbhityagi15 C Basics Arrays Mathematical School Programming Arrays Mathematical 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 Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 25913, "s": 25885, "text": "\n26 Feb, 2021" }, { "code": null, "e": 26097, "s": 25913, "text": "Given two arrays and the operation to be performed is that the every element of a[] should be divided by all the element of b[] and their floor value has to be calculated.Examples : " }, { "code": null, "e": 26427, "s": 26097, "text": "Input : a[] = {5, 100, 8}, b[] = {2, 3}\nOutput : 0 16 1\nExplanation :\nSize of a[] is 3.\nSize of b[] is 2.\nNow 5 has to be divided by the elements of array b[]\ni.e. 5 is divided by 2, then the quotient obtained \nis divided by 3 and the floor value of this is \ncalculated. The same process is repeated for the other\narray elements." }, { "code": null, "e": 26816, "s": 26429, "text": "First Approach : This solution is of complexity O(n * m) where size of a[] is n and size of array b[] is m. In this solution we fix the elements of array a[] and iterate it with the elements of array b[].Second Approach : In this method we have used simple maths. We first find product of array B and then divide it by each array element of a[] The complexity of this solution is O(n). " }, { "code": null, "e": 26820, "s": 26816, "text": "C++" }, { "code": null, "e": 26825, "s": 26820, "text": "Java" }, { "code": null, "e": 26833, "s": 26825, "text": "Python3" }, { "code": null, "e": 26836, "s": 26833, "text": "C#" }, { "code": null, "e": 26840, "s": 26836, "text": "PHP" }, { "code": null, "e": 26851, "s": 26840, "text": "Javascript" }, { "code": "// CPP program to find quotient of array// elements#include <bits/stdc++.h>using namespace std; // Function to calculate the quotient// of every element of the arrayvoid calculate(int a[], int b[], int n, int m){ int mul = 1; // Calculate the product of all elements for (int i = 0 ; i < m ; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (int i = 0 ; i < n ; i++) { int x = floor(a[i] / mul); cout << x << \" \"; }} // Driver codeint main(){ int a[] = {5 , 100 , 8}; int b[] = {2 , 3}; int n = sizeof(a)/sizeof(a[0]); int m = sizeof(b)/sizeof(b[0]); calculate(a, b, n, m); return 0;}", "e": 27560, "s": 26851, "text": null }, { "code": "// Java program to find quotient of array// elements import java.io.*; class GFG { // Function to calculate the quotient // of every element of the array static void calculate(int a[], int b[], int n, int m) { int mul = 1; // Calculate the product of all // elements for (int i = 0; i < m; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (int i = 0; i < n; i++) { int x = (int)Math.floor(a[i] / mul); System.out.print(x + \" \"); } } public static void main(String[] args) { int a[] = { 5, 100, 8 }; int b[] = { 2, 3 }; int n = a.length; int m = b.length; calculate(a, b, n, m); }} // This code is contributed by Ajit.", "e": 28442, "s": 27560, "text": null }, { "code": "# Python3 program to find# quotient of arrayelementsimport math # Function to calculate the quotient# of every element of the arraydef calculate(a, b, n, m): mul = 1 # Calculate the product # of all elements for i in range(m): if (b[i] != 0): mul = mul * b[i] # To calculate the quotient # of every array element for i in range(n): x = math.floor(a[i] / mul) print(x, end = \" \") # Driver codea = [ 5, 100, 8 ]b = [ 2, 3 ]n = len(a)m = len(b) calculate(a, b, n, m) # This code is contributed by Anant Agarwal.", "e": 29032, "s": 28442, "text": null }, { "code": "// C# program to find quotient// of array elementsusing System; class GFG { // Function to calculate the quotient // of every element of the array static void calculate(int []a, int []b, int n, int m) { int mul = 1; // Calculate the product of all // elements for (int i = 0; i < m; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (int i = 0; i < n; i++) { int x = (int)Math.Floor((double)(a[i] / mul)); Console.Write(x + \" \"); } } // Driver code public static void Main() { int []a = { 5, 100, 8 }; int []b = { 2, 3 }; int n = a.Length; int m = b.Length; calculate(a, b, n, m); }} // This code is contributed by Anant Agarwal.", "e": 29926, "s": 29032, "text": null }, { "code": "<?php// PHP program to find// quotient of array elements // Function to calculate// the quotient of every// element of the arrayfunction calculate( $a, $b, $n, $m){$mul = 1; // Calculate the product // of all elements for ( $i = 0 ; $i < $m ; $i++) if ($b[$i] != 0) $mul = $mul * $b[$i]; // To calculate the quotient // of every array element for ( $i = 0 ; $i < $n ; $i++) { $x = floor($a[$i] / $mul); echo $x , \" \"; }} // Driver code$a = array(5 , 100 , 8);$b = array(2 , 3); $n = count($a); $m = count($b); calculate($a, $b, $n, $m); // This code is contributed by anuju_67.?>", "e": 30592, "s": 29926, "text": null }, { "code": "<script> // JavaScript program to find quotient of array// elements // Function to calculate the quotient// of every element of the arrayfunction calculate(a, b, n, m){ let mul = 1; // Calculate the product of all elements for (let i = 0 ; i < m ; i++) if (b[i] != 0) mul = mul * b[i]; // To calculate the quotient of every // array element for (let i = 0 ; i < n ; i++) { let x = Math.floor(a[i] / mul); document.write(x + \" \"); }} // Driver code let a = [5 , 100 , 8]; let b = [2 , 3]; let n = a.length; let m = b.length; calculate(a, b, n, m); // This code is contributed by Surbhi Tyagi </script>", "e": 31266, "s": 30592, "text": null }, { "code": null, "e": 31276, "s": 31266, "text": "Output : " }, { "code": null, "e": 31283, "s": 31276, "text": "0 16 1" }, { "code": null, "e": 31290, "s": 31285, "text": "vt_m" }, { "code": null, "e": 31304, "s": 31290, "text": "surbhityagi15" }, { "code": null, "e": 31313, "s": 31304, "text": "C Basics" }, { "code": null, "e": 31320, "s": 31313, "text": "Arrays" }, { "code": null, "e": 31333, "s": 31320, "text": "Mathematical" }, { "code": null, "e": 31352, "s": 31333, "text": "School Programming" }, { "code": null, "e": 31359, "s": 31352, "text": "Arrays" }, { "code": null, "e": 31372, "s": 31359, "text": "Mathematical" }, { "code": null, "e": 31470, "s": 31372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31538, "s": 31470, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31582, "s": 31538, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31630, "s": 31582, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31653, "s": 31630, "text": "Introduction to Arrays" }, { "code": null, "e": 31685, "s": 31653, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31745, "s": 31685, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31760, "s": 31745, "text": "C++ Data Types" }, { "code": null, "e": 31803, "s": 31760, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 31822, "s": 31803, "text": "Coin Change | DP-7" } ]
Lexicographically n-th permutation of a string
07 Jul, 2022 Given a string of length m containing lowercase alphabets only. You have to find the n-th permutation of string lexicographically. Examples: Input : str[] = "abc", n = 3 Output : Result = "bac" Explanation : All possible permutation in sorted order: abc, acb, bac, bca, cab, cba Input : str[] = "aba", n = 2 Output : Result = "aba" Explanation : All possible permutation in sorted order: aab, aba, baa Prerequisite : Permutations of a given string using STL Idea behind printing n-th permutation is quite simple we should use STL (explained in above link) for finding next permutation and do it till the nth permutation. After n-th iteration, we should break from the loop and then print the string which is our nth permutation. long int i = 1; do { // check for nth iteration if (i == n) break; i++; // keep incrementing the iteration } while (next_permutation(str.begin(), str.end())); // print string after nth iteration print str; C++ Java Python3 C# // C++ program to print nth permutation with// using next_permute()#include <bits/stdc++.h>using namespace std; // Function to print nth permutation// using next_permute()void nPermute(string str, long int n){ // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach nth position long int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str.begin(), str.end())); // print string after nth iteration cout << str;} // Driver codeint main(){ string str = "GEEKSFORGEEKS"; long int n = 100; nPermute(str, n); return 0;} // Java program to print nth permutation with// using next_permute()import java.util.*; class GFG{ // Function to print nth permutation// using next_permute()static void nPermute(char[] str, int n){ // Sort the string in lexicographically // ascending order Arrays.sort(str); // Keep iterating until // we reach nth position int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str)); // print string after nth iteration System.out.println(String.valueOf(str));} static boolean next_permutation(char[] p){ for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { char t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false;} // Driver codepublic static void main(String[] args){ String str = "GEEKSFORGEEKS"; int n = 100; nPermute(str.toCharArray(), n);}} // This code contributed by Rajput-Ji # Python3 program to print nth permutation# with using next_permute() # next_permutation method implementationdef next_permutation(L): n = len(L) i = n - 2 while i >= 0 and L[i] >= L[i + 1]: i -= 1 if i == -1: return False j = i + 1 while j < n and L[j] > L[i]: j += 1 j -= 1 L[i], L[j] = L[j], L[i] left = i + 1 right = n - 1 while left < right: L[left], L[right] = L[right], L[left] left += 1 right -= 1 return True # Function to print nth permutation# using next_permute()def nPermute(string, n): string = list(string) new_string = [] # Sort the string in lexicographically # ascending order string.sort() j = 2 # Keep iterating until # we reach nth position while next_permutation(string): new_string = string # check for nth iteration if j == n: break j += 1 # print string after nth iteration print(''.join(new_string)) # Driver Codeif __name__ == "__main__": string = "GEEKSFORGEEKS" n = 100 nPermute(string, n) # This code is contributed by# sanjeev2552 // C# program to print nth permutation with// using next_permute()using System; class GFG{ // Function to print nth permutation// using next_permute()static void nPermute(char[] str, int n){ // Sort the string in lexicographically // ascending order Array.Sort(str); // Keep iterating until // we reach nth position int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str)); // print string after nth iteration Console.WriteLine(String.Join("",str));} static bool next_permutation(char[] p){ for (int a = p.Length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.Length - 1;; --b) if (p[b] > p[a]) { char t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.Length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false;} // Driver codepublic static void Main(){ String str = "GEEKSFORGEEKS"; int n = 100; nPermute(str.ToCharArray(), n);}} /* This code contributed by PrinciRaj1992 */ Output: EEEEFGGRKSOSK Time Complexity: O(n log n) Auxiliary Space: O(1) Find n-th lexicographically permutation of a string | Set 2 This article is contributed by Aarti_Rathi and Shivam Pradhan (anuj_charm). 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. Rajput-Ji princiraj1992 sanjeev2552 lexicographic-ordering Strings 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 Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 193, "s": 52, "text": "Given a string of length m containing lowercase alphabets only. You have to find the n-th permutation of string lexicographically. Examples:" }, { "code": null, "e": 455, "s": 193, "text": "Input : str[] = \"abc\", n = 3\nOutput : Result = \"bac\"\nExplanation : All possible permutation in\nsorted order: abc, acb, bac, bca, cab, cba\n\nInput : str[] = \"aba\", n = 2\nOutput : Result = \"aba\"\nExplanation : All possible permutation\nin sorted order: aab, aba, baa" }, { "code": null, "e": 782, "s": 455, "text": "Prerequisite : Permutations of a given string using STL Idea behind printing n-th permutation is quite simple we should use STL (explained in above link) for finding next permutation and do it till the nth permutation. After n-th iteration, we should break from the loop and then print the string which is our nth permutation." }, { "code": null, "e": 1047, "s": 782, "text": " long int i = 1;\n do\n {\n // check for nth iteration\n if (i == n)\n break;\n i++; // keep incrementing the iteration\n } while (next_permutation(str.begin(), str.end()));\n\n // print string after nth iteration\n print str;" }, { "code": null, "e": 1051, "s": 1047, "text": "C++" }, { "code": null, "e": 1056, "s": 1051, "text": "Java" }, { "code": null, "e": 1064, "s": 1056, "text": "Python3" }, { "code": null, "e": 1067, "s": 1064, "text": "C#" }, { "code": "// C++ program to print nth permutation with// using next_permute()#include <bits/stdc++.h>using namespace std; // Function to print nth permutation// using next_permute()void nPermute(string str, long int n){ // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach nth position long int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str.begin(), str.end())); // print string after nth iteration cout << str;} // Driver codeint main(){ string str = \"GEEKSFORGEEKS\"; long int n = 100; nPermute(str, n); return 0;}", "e": 1769, "s": 1067, "text": null }, { "code": "// Java program to print nth permutation with// using next_permute()import java.util.*; class GFG{ // Function to print nth permutation// using next_permute()static void nPermute(char[] str, int n){ // Sort the string in lexicographically // ascending order Arrays.sort(str); // Keep iterating until // we reach nth position int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str)); // print string after nth iteration System.out.println(String.valueOf(str));} static boolean next_permutation(char[] p){ for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { char t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false;} // Driver codepublic static void main(String[] args){ String str = \"GEEKSFORGEEKS\"; int n = 100; nPermute(str.toCharArray(), n);}} // This code contributed by Rajput-Ji", "e": 3036, "s": 1769, "text": null }, { "code": "# Python3 program to print nth permutation# with using next_permute() # next_permutation method implementationdef next_permutation(L): n = len(L) i = n - 2 while i >= 0 and L[i] >= L[i + 1]: i -= 1 if i == -1: return False j = i + 1 while j < n and L[j] > L[i]: j += 1 j -= 1 L[i], L[j] = L[j], L[i] left = i + 1 right = n - 1 while left < right: L[left], L[right] = L[right], L[left] left += 1 right -= 1 return True # Function to print nth permutation# using next_permute()def nPermute(string, n): string = list(string) new_string = [] # Sort the string in lexicographically # ascending order string.sort() j = 2 # Keep iterating until # we reach nth position while next_permutation(string): new_string = string # check for nth iteration if j == n: break j += 1 # print string after nth iteration print(''.join(new_string)) # Driver Codeif __name__ == \"__main__\": string = \"GEEKSFORGEEKS\" n = 100 nPermute(string, n) # This code is contributed by# sanjeev2552", "e": 4167, "s": 3036, "text": null }, { "code": "// C# program to print nth permutation with// using next_permute()using System; class GFG{ // Function to print nth permutation// using next_permute()static void nPermute(char[] str, int n){ // Sort the string in lexicographically // ascending order Array.Sort(str); // Keep iterating until // we reach nth position int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str)); // print string after nth iteration Console.WriteLine(String.Join(\"\",str));} static bool next_permutation(char[] p){ for (int a = p.Length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.Length - 1;; --b) if (p[b] > p[a]) { char t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.Length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false;} // Driver codepublic static void Main(){ String str = \"GEEKSFORGEEKS\"; int n = 100; nPermute(str.ToCharArray(), n);}} /* This code contributed by PrinciRaj1992 */", "e": 5418, "s": 4167, "text": null }, { "code": null, "e": 5426, "s": 5418, "text": "Output:" }, { "code": null, "e": 5440, "s": 5426, "text": "EEEEFGGRKSOSK" }, { "code": null, "e": 5468, "s": 5440, "text": "Time Complexity: O(n log n)" }, { "code": null, "e": 5490, "s": 5468, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6002, "s": 5490, "text": "Find n-th lexicographically permutation of a string | Set 2 This article is contributed by Aarti_Rathi and Shivam Pradhan (anuj_charm). 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": 6012, "s": 6002, "text": "Rajput-Ji" }, { "code": null, "e": 6026, "s": 6012, "text": "princiraj1992" }, { "code": null, "e": 6038, "s": 6026, "text": "sanjeev2552" }, { "code": null, "e": 6061, "s": 6038, "text": "lexicographic-ordering" }, { "code": null, "e": 6069, "s": 6061, "text": "Strings" }, { "code": null, "e": 6077, "s": 6069, "text": "Strings" }, { "code": null, "e": 6175, "s": 6077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6221, "s": 6175, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6246, "s": 6221, "text": "Reverse a string in Java" }, { "code": null, "e": 6306, "s": 6246, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6321, "s": 6306, "text": "C++ Data Types" }, { "code": null, "e": 6366, "s": 6321, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 6423, "s": 6366, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 6457, "s": 6423, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 6532, "s": 6457, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 6593, "s": 6532, "text": "Length of the longest substring without repeating characters" } ]
Best approach for “Keep Me Logged In” using PHP
10 May, 2020 We all have noticed the “Keep Me Logged In” checkbox in most of the websites we log in to. There are different ways and approaches to achieve this through code. The best approach among those is saving the User information in the user browser as cookies. Basically, we have to store both the Username and the Password in the user’s browser as cookies. Then every time the page loads the session variable will be set. Hence the user can log in without having to enter the Username and Password again until the life of that cookie expires. The example code given below is the way how to remember password checkbox works through PHP. Example <?phpsession_start();if (isset($_SESSION["name"])){ header("location:home.php");}$connect = mysqli_connect("localhost", "root", "", "testing");if (isset($_POST["login"])){ if (!empty($_POST["user_name"]) && !empty($_POST["user_password"])) { $name = mysqli_real_escape_string($connect, $_POST["user_name"]); $password = md5(mysqli_real_escape_string($connect, $_POST["user_password"])); $sql = "Select * from login where name = '" . $name . " ' and password = '" . $password . "'"; $result = mysqli_query($connect, $sql); $user = mysqli_fetch_array($result); if ($user) { // Saving the username and password as cookies if (!empty($_POST["rememberme"])) { // Username is stored as cookie for 10 years as // 10years * 365days * 24hrs * 60mins * 60secs setcookie("user_login", $name, time() + (10 * 365 * 24 * 60 * 60)); // Password is stored as cookie for 10 years as // 10years * 365days * 24hrs * 60mins * 60secs setcookie("user_password", $password, time() + (10 * 365 * 24 * 60 * 60)); // After setting cookies the session variable will be set $_SESSION["name"] = $name; } else { if (isset($_COOKIE["user_login"])) { setcookie("user_login", ""); } if (isset($_COOKIE["user_password"])) { setcookie("user_password", ""); } } header("location:home.php"); } else { $message = "Invalid Login Credentials"; } } else { $message = "Both are Required Fields. Please fill both the fields"; }}?> Output By understanding the above code by reading the comments and explanation you must able to execute the PHP code on the server with storing the Username and Password as cookies in the user’s browser. So in this way remember password task can be achieved. PHP-Misc Picked PHP PHP Programs Web Technologies Web technologies Questions Write From Home PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 189, "s": 28, "text": "We all have noticed the “Keep Me Logged In” checkbox in most of the websites we log in to. There are different ways and approaches to achieve this through code." }, { "code": null, "e": 658, "s": 189, "text": "The best approach among those is saving the User information in the user browser as cookies. Basically, we have to store both the Username and the Password in the user’s browser as cookies. Then every time the page loads the session variable will be set. Hence the user can log in without having to enter the Username and Password again until the life of that cookie expires. The example code given below is the way how to remember password checkbox works through PHP." }, { "code": null, "e": 666, "s": 658, "text": "Example" }, { "code": "<?phpsession_start();if (isset($_SESSION[\"name\"])){ header(\"location:home.php\");}$connect = mysqli_connect(\"localhost\", \"root\", \"\", \"testing\");if (isset($_POST[\"login\"])){ if (!empty($_POST[\"user_name\"]) && !empty($_POST[\"user_password\"])) { $name = mysqli_real_escape_string($connect, $_POST[\"user_name\"]); $password = md5(mysqli_real_escape_string($connect, $_POST[\"user_password\"])); $sql = \"Select * from login where name = '\" . $name . \" ' and password = '\" . $password . \"'\"; $result = mysqli_query($connect, $sql); $user = mysqli_fetch_array($result); if ($user) { // Saving the username and password as cookies if (!empty($_POST[\"rememberme\"])) { // Username is stored as cookie for 10 years as // 10years * 365days * 24hrs * 60mins * 60secs setcookie(\"user_login\", $name, time() + (10 * 365 * 24 * 60 * 60)); // Password is stored as cookie for 10 years as // 10years * 365days * 24hrs * 60mins * 60secs setcookie(\"user_password\", $password, time() + (10 * 365 * 24 * 60 * 60)); // After setting cookies the session variable will be set $_SESSION[\"name\"] = $name; } else { if (isset($_COOKIE[\"user_login\"])) { setcookie(\"user_login\", \"\"); } if (isset($_COOKIE[\"user_password\"])) { setcookie(\"user_password\", \"\"); } } header(\"location:home.php\"); } else { $message = \"Invalid Login Credentials\"; } } else { $message = \"Both are Required Fields. Please fill both the fields\"; }}?>", "e": 2665, "s": 666, "text": null }, { "code": null, "e": 2924, "s": 2665, "text": "Output By understanding the above code by reading the comments and explanation you must able to execute the PHP code on the server with storing the Username and Password as cookies in the user’s browser. So in this way remember password task can be achieved." }, { "code": null, "e": 2933, "s": 2924, "text": "PHP-Misc" }, { "code": null, "e": 2940, "s": 2933, "text": "Picked" }, { "code": null, "e": 2944, "s": 2940, "text": "PHP" }, { "code": null, "e": 2957, "s": 2944, "text": "PHP Programs" }, { "code": null, "e": 2974, "s": 2957, "text": "Web Technologies" }, { "code": null, "e": 3001, "s": 2974, "text": "Web technologies Questions" }, { "code": null, "e": 3017, "s": 3001, "text": "Write From Home" }, { "code": null, "e": 3021, "s": 3017, "text": "PHP" } ]
Types of Interfaces in Java
19 Dec, 2021 In Java, an interface is a reference type similar to a class that can contain only constants, the method signatures, default methods, and static methods, and ts Nested types. In interfaces, method bodies exist only for default methods and static methods. Writing an interface is similar to writing to a standard class. Still, a class describes the attributes and internal behaviors objects, and an interface contains behaviors that a class implements. On the other side unless the class that implements the interface is purely abstract and all the interface methods need to be defined in that given usable class. An interface is Similar To a Class In Following Ways: An interface can contain any number of methods in that interface.An interface name is written in a file with a – (.java extension ) with the name of the interface must be matching the name of the file of that Java program.The byte code of a given interface will be created in a – .class file.Interfaces appear in packages, and their corresponding bytecode file must similarly be in a structure that matches the package name with it. An interface can contain any number of methods in that interface. An interface name is written in a file with a – (.java extension ) with the name of the interface must be matching the name of the file of that Java program. The byte code of a given interface will be created in a – .class file. Interfaces appear in packages, and their corresponding bytecode file must similarly be in a structure that matches the package name with it. How To Declare Interfaces? The interface keyword is used to declare an interface. Here We have a simple example of declaring an interface. Java public interface NameOfTheinterface{ // Any final, static fields here // Any abstract method declaration here }//This is Declaration of the interface An Interfaces have the following properties: An interface is implicitly pure abstract. not need to use the abstract keyword while declaring an interface Each method in an interface is also implicitly abstract, so the abstract keyword is not needed The Methods in an interface are implicitly public within it Example: Filename – Car.java Java // This is Program To implement the Interfaceinterface car{ void display();} class model implements car{ public void display() { System.out.println("im a Car"); // the code output will print "im a car" } public static void main(String args[]) { model obj = new model(); obj.display(); }} im a Car Functional InterfaceMarker interface Functional Interface Marker interface Functional Interface is an interface that has only pure one abstract method. It can have any number of static and default methods and also even public methods of java.lang.Object classes When an interface contains only one abstract method, then it is known as a Functional Interface. Runnable : It contains only run() method ActionListener : It contains only actionPerformed() ItemListener : It contains only itemStateChanged() method Now we will see an example of a Functional Interface – Example: Java // This is Program To implement the Functional Interface interface Writable{ void write(String txt); } // FuninterExp is a Example of Functional Interface public class FuninterExp implements Writable { public void write(String txt) { System.out.println(txt); } public static void main(String[] args) { FuninterExp obj = new FuninterExp(); obj.write(" GFG - GEEKS FOR GEEKS "); } } GFG - GEEKS FOR GEEKS An interface that does not contain any methods, fields, Abstract Methods, and any Constants is Called a Marker interface. Also, if an interface is empty, then it is known as Marker Interface. The Serializable and the Cloneable interfaces are examples of Marker interfaces. For Example: Java // Simple Example to understand marker interface public interface interface_name { // empty } There are two alternatives to the marker interface that produce the same result as the marker interface. 1) Internal Flags – It is used in the place of the Marker interface to implement any specific operation. 2) Annotations – By applying annotations to any class, we can perform specific actions on it. There are three types of Built-In Marker Interfaces in Java. These are Cloneable InterfaceSerializable InterfaceRemote Interface Cloneable Interface Serializable Interface Remote Interface 1. Cloneable Interface A cloneable interface in Java is also a Marker interface that belongs to java.lang packages. It generates a replica(copy) of an object with a different name. Therefore we can implement the interface in the class of which class object is to be cloned. It implements the clone() method of the Object class to it. Note – A class that implements the Cloneable interface must override the clone() method by using a public method. For Example: Java // This is Program To implement the Cloneable Interface import java.lang.Cloneable; class abc implements Cloneable// Here The abc is a class constructor{ int x; String y; // Here The abc is a class constructor public abc(int x,String y) { this.x = x; this.y = y; } protected Object clone() throws CloneNotSupportedException { return super.clone(); }} public class Test { public static void main(String[] args) throws CloneNotSupportedException { abc p = new abc(10, "We Are Reading GFG Now"); abc q = (abc)p.clone(); System.out.println(q.x); System.out.println(q.y); } } 10 We Are Reading GFG Now 2. Serializable Interface: It is a marker interface in Java that is defined in the java.io package. If we want to make the class serializable, we must implement the Serializable interface. If a class implements the Serializable interface, we can serialize or deserialize the state of an object of that class. Serialization is a mechanism in which our object state is ready from memory and written into a file or from the databases. Deserialization- is the opposite of serialization means that object state reading from a file or database and written back into memory is called deserialization of an object. Serialization – Converting an object into byte stream. Deserialization – Converting byte stream into an object. 3. Remote Interface: A remote interface is a marker interface that belongs to java.rmi package. It marks an object as a remote that can be accessed from the host of another machine. We need to implement the Remote interface if we want to make an object remote then. Therefore, It identifies the interface. A remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. The remote interface is an interface that declares the set of methods that will be invoked from a remote Java Virtual Machine, i.e.(JVM sooda367 java-interfaces Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Dec, 2021" }, { "code": null, "e": 667, "s": 54, "text": "In Java, an interface is a reference type similar to a class that can contain only constants, the method signatures, default methods, and static methods, and ts Nested types. In interfaces, method bodies exist only for default methods and static methods. Writing an interface is similar to writing to a standard class. Still, a class describes the attributes and internal behaviors objects, and an interface contains behaviors that a class implements. On the other side unless the class that implements the interface is purely abstract and all the interface methods need to be defined in that given usable class." }, { "code": null, "e": 721, "s": 667, "text": "An interface is Similar To a Class In Following Ways:" }, { "code": null, "e": 1155, "s": 721, "text": "An interface can contain any number of methods in that interface.An interface name is written in a file with a – (.java extension ) with the name of the interface must be matching the name of the file of that Java program.The byte code of a given interface will be created in a – .class file.Interfaces appear in packages, and their corresponding bytecode file must similarly be in a structure that matches the package name with it." }, { "code": null, "e": 1221, "s": 1155, "text": "An interface can contain any number of methods in that interface." }, { "code": null, "e": 1379, "s": 1221, "text": "An interface name is written in a file with a – (.java extension ) with the name of the interface must be matching the name of the file of that Java program." }, { "code": null, "e": 1451, "s": 1379, "text": "The byte code of a given interface will be created in a – .class file." }, { "code": null, "e": 1592, "s": 1451, "text": "Interfaces appear in packages, and their corresponding bytecode file must similarly be in a structure that matches the package name with it." }, { "code": null, "e": 1619, "s": 1592, "text": "How To Declare Interfaces?" }, { "code": null, "e": 1731, "s": 1619, "text": "The interface keyword is used to declare an interface. Here We have a simple example of declaring an interface." }, { "code": null, "e": 1736, "s": 1731, "text": "Java" }, { "code": "public interface NameOfTheinterface{ // Any final, static fields here // Any abstract method declaration here }//This is Declaration of the interface", "e": 1890, "s": 1736, "text": null }, { "code": null, "e": 1935, "s": 1890, "text": "An Interfaces have the following properties:" }, { "code": null, "e": 1977, "s": 1935, "text": "An interface is implicitly pure abstract." }, { "code": null, "e": 2043, "s": 1977, "text": "not need to use the abstract keyword while declaring an interface" }, { "code": null, "e": 2138, "s": 2043, "text": "Each method in an interface is also implicitly abstract, so the abstract keyword is not needed" }, { "code": null, "e": 2198, "s": 2138, "text": "The Methods in an interface are implicitly public within it" }, { "code": null, "e": 2227, "s": 2198, "text": "Example: Filename – Car.java" }, { "code": null, "e": 2232, "s": 2227, "text": "Java" }, { "code": "// This is Program To implement the Interfaceinterface car{ void display();} class model implements car{ public void display() { System.out.println(\"im a Car\"); // the code output will print \"im a car\" } public static void main(String args[]) { model obj = new model(); obj.display(); }}", "e": 2572, "s": 2232, "text": null }, { "code": null, "e": 2581, "s": 2572, "text": "im a Car" }, { "code": null, "e": 2618, "s": 2581, "text": "Functional InterfaceMarker interface" }, { "code": null, "e": 2639, "s": 2618, "text": "Functional Interface" }, { "code": null, "e": 2656, "s": 2639, "text": "Marker interface" }, { "code": null, "e": 2733, "s": 2656, "text": "Functional Interface is an interface that has only pure one abstract method." }, { "code": null, "e": 2843, "s": 2733, "text": "It can have any number of static and default methods and also even public methods of java.lang.Object classes" }, { "code": null, "e": 2940, "s": 2843, "text": "When an interface contains only one abstract method, then it is known as a Functional Interface." }, { "code": null, "e": 2983, "s": 2940, "text": "Runnable : It contains only run() method" }, { "code": null, "e": 3036, "s": 2983, "text": "ActionListener : It contains only actionPerformed()" }, { "code": null, "e": 3095, "s": 3036, "text": "ItemListener : It contains only itemStateChanged() method" }, { "code": null, "e": 3151, "s": 3095, "text": "Now we will see an example of a Functional Interface – " }, { "code": null, "e": 3160, "s": 3151, "text": "Example:" }, { "code": null, "e": 3165, "s": 3160, "text": "Java" }, { "code": "// This is Program To implement the Functional Interface interface Writable{ void write(String txt); } // FuninterExp is a Example of Functional Interface public class FuninterExp implements Writable { public void write(String txt) { System.out.println(txt); } public static void main(String[] args) { FuninterExp obj = new FuninterExp(); obj.write(\" GFG - GEEKS FOR GEEKS \"); } }", "e": 3640, "s": 3165, "text": null }, { "code": null, "e": 3664, "s": 3640, "text": " GFG - GEEKS FOR GEEKS " }, { "code": null, "e": 3786, "s": 3664, "text": "An interface that does not contain any methods, fields, Abstract Methods, and any Constants is Called a Marker interface." }, { "code": null, "e": 3856, "s": 3786, "text": "Also, if an interface is empty, then it is known as Marker Interface." }, { "code": null, "e": 3937, "s": 3856, "text": "The Serializable and the Cloneable interfaces are examples of Marker interfaces." }, { "code": null, "e": 3950, "s": 3937, "text": "For Example:" }, { "code": null, "e": 3955, "s": 3950, "text": "Java" }, { "code": "// Simple Example to understand marker interface public interface interface_name { // empty }", "e": 4068, "s": 3955, "text": null }, { "code": null, "e": 4173, "s": 4068, "text": "There are two alternatives to the marker interface that produce the same result as the marker interface." }, { "code": null, "e": 4278, "s": 4173, "text": "1) Internal Flags – It is used in the place of the Marker interface to implement any specific operation." }, { "code": null, "e": 4372, "s": 4278, "text": "2) Annotations – By applying annotations to any class, we can perform specific actions on it." }, { "code": null, "e": 4443, "s": 4372, "text": "There are three types of Built-In Marker Interfaces in Java. These are" }, { "code": null, "e": 4501, "s": 4443, "text": "Cloneable InterfaceSerializable InterfaceRemote Interface" }, { "code": null, "e": 4521, "s": 4501, "text": "Cloneable Interface" }, { "code": null, "e": 4544, "s": 4521, "text": "Serializable Interface" }, { "code": null, "e": 4561, "s": 4544, "text": "Remote Interface" }, { "code": null, "e": 4584, "s": 4561, "text": "1. Cloneable Interface" }, { "code": null, "e": 4677, "s": 4584, "text": "A cloneable interface in Java is also a Marker interface that belongs to java.lang packages." }, { "code": null, "e": 4835, "s": 4677, "text": "It generates a replica(copy) of an object with a different name. Therefore we can implement the interface in the class of which class object is to be cloned." }, { "code": null, "e": 4895, "s": 4835, "text": "It implements the clone() method of the Object class to it." }, { "code": null, "e": 5009, "s": 4895, "text": "Note – A class that implements the Cloneable interface must override the clone() method by using a public method." }, { "code": null, "e": 5022, "s": 5009, "text": "For Example:" }, { "code": null, "e": 5027, "s": 5022, "text": "Java" }, { "code": "// This is Program To implement the Cloneable Interface import java.lang.Cloneable; class abc implements Cloneable// Here The abc is a class constructor{ int x; String y; // Here The abc is a class constructor public abc(int x,String y) { this.x = x; this.y = y; } protected Object clone() throws CloneNotSupportedException { return super.clone(); }} public class Test { public static void main(String[] args) throws CloneNotSupportedException { abc p = new abc(10, \"We Are Reading GFG Now\"); abc q = (abc)p.clone(); System.out.println(q.x); System.out.println(q.y); } }", "e": 5750, "s": 5027, "text": null }, { "code": null, "e": 5776, "s": 5750, "text": "10\nWe Are Reading GFG Now" }, { "code": null, "e": 5803, "s": 5776, "text": "2. Serializable Interface:" }, { "code": null, "e": 6085, "s": 5803, "text": "It is a marker interface in Java that is defined in the java.io package. If we want to make the class serializable, we must implement the Serializable interface. If a class implements the Serializable interface, we can serialize or deserialize the state of an object of that class." }, { "code": null, "e": 6208, "s": 6085, "text": "Serialization is a mechanism in which our object state is ready from memory and written into a file or from the databases." }, { "code": null, "e": 6383, "s": 6208, "text": "Deserialization- is the opposite of serialization means that object state reading from a file or database and written back into memory is called deserialization of an object." }, { "code": null, "e": 6438, "s": 6383, "text": "Serialization – Converting an object into byte stream." }, { "code": null, "e": 6495, "s": 6438, "text": "Deserialization – Converting byte stream into an object." }, { "code": null, "e": 6516, "s": 6495, "text": "3. Remote Interface:" }, { "code": null, "e": 6677, "s": 6516, "text": "A remote interface is a marker interface that belongs to java.rmi package. It marks an object as a remote that can be accessed from the host of another machine." }, { "code": null, "e": 6801, "s": 6677, "text": "We need to implement the Remote interface if we want to make an object remote then. Therefore, It identifies the interface." }, { "code": null, "e": 7002, "s": 6801, "text": "A remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface." }, { "code": null, "e": 7138, "s": 7002, "text": "The remote interface is an interface that declares the set of methods that will be invoked from a remote Java Virtual Machine, i.e.(JVM" }, { "code": null, "e": 7147, "s": 7138, "text": "sooda367" }, { "code": null, "e": 7163, "s": 7147, "text": "java-interfaces" }, { "code": null, "e": 7170, "s": 7163, "text": "Picked" }, { "code": null, "e": 7175, "s": 7170, "text": "Java" }, { "code": null, "e": 7180, "s": 7175, "text": "Java" } ]
Java 8 Stream Tutorial
16 Dec, 2021 Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Before proceeding further let us discuss out the difference between Collection and Streams in order to understand why this concept was introduced. Note: If we want to represent a group of objects as a single entity then we should go for collection. But if we want to process objects from the collection then we should go for streams. If we want to use the concept of streams then stream() is the method to be used. Stream is available as an interface. Stream s = c.stream(); In the above pre-tag, ‘c’ refers to the collection. So on the collection, we are calling the stream() method and at the same time, we are storing it as the Stream object. Henceforth, this way we are getting the Stream object. Note: Streams are present in java’s utility package named java.util.stream Let us now start with the basic components involved in streams. They as listed and as follows: Sequence of Elements Source Aggregate Operations Pipelining Internal iteration Features of Java stream? A stream is not a data structure instead it takes input from the Collections, Arrays, or I/O channels. Streams don’t change the original data structure, they only provide the result as per the pipelined methods. Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result. Before moving ahead in the concept consider an example in which we are having ArrayList of integers, and we suppose we apply a filter to get only even numbers from the object inserted. How does Stream Work Internally? In streams, To filter out from the objects we do have a function named filter() To impose a condition we do have a logic of predicate which is nothing but a functional interface. Here function interface can be replaced by a random expression. Hence, we can directly impose the condition check-in our predicate. To collect elements we will be using Collectors.toList() to collect all the required elements. Lastly, we will store these elements in a List and display the outputs on the console. Example Java // Java Program to illustrate FILTER & COLLECT Operations // Importing input output classesimport java.io.*; // Importing utility class for List and ArrayList classesimport java.util.*; // Importing stream classesimport java.util.stream.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList object of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Inserting elements to ArrayList class object // Custom input integer numbers al.add(2); al.add(6); al.add(9); al.add(4); al.add(20); // First lets print the collection System.out.println("Printing the collection : " + al); // Printing new line for better output readability System.out.println(); // Stream operations // 1. Getting the stream from this collection // 2. Filtering out only even elements // 3. Collecting the required elements to List List<Integer> ls = al.stream() .filter(i -> i % 2 == 0) .collect(Collectors.toList()); // Print the collection after stream operation // as stored in List object System.out.println( "Printing the List after stream operation : " + ls); }} Printing the collection : [2, 6, 9, 4, 20] Printing the List after stream operation : [2, 6, 4, 20] Output explanation: In our collection object, we were having elements entered using the add() operation. After processing the object in which they were stored through streams we impose a condition in the predicate of streams to get only even elements, we get elements in the object as per our requirement. Hence, streams helped us this way in processing over-processed collection objects. Various core operations over Streams? There are broadly 3 types of operations that are carried over streams namely as follows as depicted from the image shown above: Intermediate operationsTerminal operationsShort-circuit operations Intermediate operations Terminal operations Short-circuit operations Let us do discuss out intermediate operations here only in streams to a certain depth with the help of an example in order to figure out other operations via theoretical means. So, there are 3 types of Intermediate operations which are as follows: Operation 1: filter() method Operation 2: map() method Operation 3: sorted() method All three of them are discussed below as they go hand in hand in nearly most of the scenarios and to provide better understanding by using them later by implementing in our clean java programs below. As we already have studied in the above example of which we are trying to filter processed objects can be interpreted as filter() operation operated over streams. Later on from that processed filtered elements of objects, we are collecting the elements back to List using Collectors for which we have imported a specific package named java.util.stream with the help of Collectors.toList() method. This is referred to as collect() operation in streams so here again we won’t be taking an example to discuss them out separately. Example: Java // Java program to illustrate Intermediate Operations// in Streams // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classclass Test { // Main driver method public static void main(String[] args) { // Creating an integer Arraylist to store marks ArrayList<Integer> marks = new ArrayList<Integer>(); // These are marks of the students // Considering 5 students so input entries marks.add(30); marks.add(78); marks.add(26); marks.add(96); marks.add(79); // Printing the marks of the students before grace System.out.println( "Marks of students before grace : " + marks); // Now we want to grace marks by 6 // using the streams to process over processing // collection // Using stream, we map every object and later // collect to List // and store them List<Integer> updatedMarks = marks.stream() .map(i -> i + 6) .collect(Collectors.toList()); // Printing the marks of the students after grace System.out.println( "Marks of students after grace : " + updatedMarks); }} Marks of students before grace : [30, 78, 26, 96, 79] Marks of students after grace : [36, 84, 32, 102, 85] Note: For every object if there is urgency to do some operations be it square, double or any other than only we need to use map() function operation else try to use filter() function operation. Now geeks you are well aware of ‘why’ streams were introduced, but you should be wondering out ‘where’ to use it. The answer is very simple as we do use them too often in our day-to-day life. Hence, the geek in simpler words we say directly land p on wherever the concept of the collection is applicable, streams concept can be applied there. Example 1: In general, daily world, whenever the data is fetching from the database, it is more likely we will be using collection so there itself streams concept is must apply to deal with processed data. Now we will be discussing out real-time examples to interrelate streams in our life. Here we will be taking the most widely used namely as follows: Streams in a Grocery storeStreams in mobile networking Streams in a Grocery store Streams in mobile networking Example 2: Streams in a Grocery store The above pictorial image has been provided is implemented in streams which is as follows: List<Integer> transactionsIds = transactions.stream() .filter(t -> t.getType() == Transaction.GROCERY) .sorted(comparing(Transaction::getValue).reversed()) .map(Transaction::getId) .collect(toList()); Example 3: Streams in mobile networking Similarly, we can go for another widely used concept that is our dealing with our mobile numbers. Here we will not be proposing out listings, simply will be demonstrating how the stream concept is invoked in mobile networking by various service providers across the globe. Collection can hold any number of object so let ‘mobileNumber’ be a collection and let it be holding various mobile numbers say it be holding 100+ numbers as objects. Suppose now the only carrier named ‘Airtel’ whom with which we are supposed to send a message if there is any migration between states in a country. So here streams concept is applied as if while dealing with all mobile numbers we will look out for this carrier using the filter() method operation of streams. In this way, we are able to deliver the messages without looking out for all mobile numbers and then delivering the message which senses impractical if done so as by now we are already too late to deliver. In this way these intermediate operations namely filter(), collect(), map() help out in the real world. Processing becomes super simpler which is the necessity of today’s digital world. Hoper by now you the users come to realize the power of streams in java as if we have to do the same task we do need to map corresponding to every object, increasing in code length, decreasing optimality of our code. With the usage of streams, we are able to in a single line irrespective of elements contained in the object as with the concept of streams we are dealing with the object itself. Note: filter, sorted, and map, which can be connected together to form a pipeline. kk9826225 anikaseth98 surindertarika1234 sooda367 simranarora5sos anikakapoor java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Dec, 2021" }, { "code": null, "e": 397, "s": 52, "text": "Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Before proceeding further let us discuss out the difference between Collection and Streams in order to understand why this concept was introduced." }, { "code": null, "e": 404, "s": 397, "text": "Note: " }, { "code": null, "e": 500, "s": 404, "text": "If we want to represent a group of objects as a single entity then we should go for collection." }, { "code": null, "e": 585, "s": 500, "text": "But if we want to process objects from the collection then we should go for streams." }, { "code": null, "e": 703, "s": 585, "text": "If we want to use the concept of streams then stream() is the method to be used. Stream is available as an interface." }, { "code": null, "e": 726, "s": 703, "text": "Stream s = c.stream();" }, { "code": null, "e": 952, "s": 726, "text": "In the above pre-tag, ‘c’ refers to the collection. So on the collection, we are calling the stream() method and at the same time, we are storing it as the Stream object. Henceforth, this way we are getting the Stream object." }, { "code": null, "e": 1027, "s": 952, "text": "Note: Streams are present in java’s utility package named java.util.stream" }, { "code": null, "e": 1122, "s": 1027, "text": "Let us now start with the basic components involved in streams. They as listed and as follows:" }, { "code": null, "e": 1143, "s": 1122, "text": "Sequence of Elements" }, { "code": null, "e": 1150, "s": 1143, "text": "Source" }, { "code": null, "e": 1171, "s": 1150, "text": "Aggregate Operations" }, { "code": null, "e": 1182, "s": 1171, "text": "Pipelining" }, { "code": null, "e": 1201, "s": 1182, "text": "Internal iteration" }, { "code": null, "e": 1226, "s": 1201, "text": "Features of Java stream?" }, { "code": null, "e": 1329, "s": 1226, "text": "A stream is not a data structure instead it takes input from the Collections, Arrays, or I/O channels." }, { "code": null, "e": 1438, "s": 1329, "text": "Streams don’t change the original data structure, they only provide the result as per the pipelined methods." }, { "code": null, "e": 1645, "s": 1438, "text": "Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result." }, { "code": null, "e": 1830, "s": 1645, "text": "Before moving ahead in the concept consider an example in which we are having ArrayList of integers, and we suppose we apply a filter to get only even numbers from the object inserted." }, { "code": null, "e": 1863, "s": 1830, "text": "How does Stream Work Internally?" }, { "code": null, "e": 1875, "s": 1863, "text": "In streams," }, { "code": null, "e": 1943, "s": 1875, "text": "To filter out from the objects we do have a function named filter()" }, { "code": null, "e": 2174, "s": 1943, "text": "To impose a condition we do have a logic of predicate which is nothing but a functional interface. Here function interface can be replaced by a random expression. Hence, we can directly impose the condition check-in our predicate." }, { "code": null, "e": 2269, "s": 2174, "text": "To collect elements we will be using Collectors.toList() to collect all the required elements." }, { "code": null, "e": 2356, "s": 2269, "text": "Lastly, we will store these elements in a List and display the outputs on the console." }, { "code": null, "e": 2365, "s": 2356, "text": "Example " }, { "code": null, "e": 2370, "s": 2365, "text": "Java" }, { "code": "// Java Program to illustrate FILTER & COLLECT Operations // Importing input output classesimport java.io.*; // Importing utility class for List and ArrayList classesimport java.util.*; // Importing stream classesimport java.util.stream.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList object of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Inserting elements to ArrayList class object // Custom input integer numbers al.add(2); al.add(6); al.add(9); al.add(4); al.add(20); // First lets print the collection System.out.println(\"Printing the collection : \" + al); // Printing new line for better output readability System.out.println(); // Stream operations // 1. Getting the stream from this collection // 2. Filtering out only even elements // 3. Collecting the required elements to List List<Integer> ls = al.stream() .filter(i -> i % 2 == 0) .collect(Collectors.toList()); // Print the collection after stream operation // as stored in List object System.out.println( \"Printing the List after stream operation : \" + ls); }}", "e": 3752, "s": 2370, "text": null }, { "code": null, "e": 3853, "s": 3752, "text": "Printing the collection : [2, 6, 9, 4, 20]\n\nPrinting the List after stream operation : [2, 6, 4, 20]" }, { "code": null, "e": 4243, "s": 3853, "text": "Output explanation: In our collection object, we were having elements entered using the add() operation. After processing the object in which they were stored through streams we impose a condition in the predicate of streams to get only even elements, we get elements in the object as per our requirement. Hence, streams helped us this way in processing over-processed collection objects." }, { "code": null, "e": 4281, "s": 4243, "text": "Various core operations over Streams?" }, { "code": null, "e": 4409, "s": 4281, "text": "There are broadly 3 types of operations that are carried over streams namely as follows as depicted from the image shown above:" }, { "code": null, "e": 4476, "s": 4409, "text": "Intermediate operationsTerminal operationsShort-circuit operations" }, { "code": null, "e": 4500, "s": 4476, "text": "Intermediate operations" }, { "code": null, "e": 4520, "s": 4500, "text": "Terminal operations" }, { "code": null, "e": 4545, "s": 4520, "text": "Short-circuit operations" }, { "code": null, "e": 4793, "s": 4545, "text": "Let us do discuss out intermediate operations here only in streams to a certain depth with the help of an example in order to figure out other operations via theoretical means. So, there are 3 types of Intermediate operations which are as follows:" }, { "code": null, "e": 4822, "s": 4793, "text": "Operation 1: filter() method" }, { "code": null, "e": 4848, "s": 4822, "text": "Operation 2: map() method" }, { "code": null, "e": 4877, "s": 4848, "text": "Operation 3: sorted() method" }, { "code": null, "e": 5605, "s": 4877, "text": "All three of them are discussed below as they go hand in hand in nearly most of the scenarios and to provide better understanding by using them later by implementing in our clean java programs below. As we already have studied in the above example of which we are trying to filter processed objects can be interpreted as filter() operation operated over streams. Later on from that processed filtered elements of objects, we are collecting the elements back to List using Collectors for which we have imported a specific package named java.util.stream with the help of Collectors.toList() method. This is referred to as collect() operation in streams so here again we won’t be taking an example to discuss them out separately. " }, { "code": null, "e": 5614, "s": 5605, "text": "Example:" }, { "code": null, "e": 5619, "s": 5614, "text": "Java" }, { "code": "// Java program to illustrate Intermediate Operations// in Streams // Importing required classesimport java.io.*;import java.util.*;import java.util.stream.*; // Main classclass Test { // Main driver method public static void main(String[] args) { // Creating an integer Arraylist to store marks ArrayList<Integer> marks = new ArrayList<Integer>(); // These are marks of the students // Considering 5 students so input entries marks.add(30); marks.add(78); marks.add(26); marks.add(96); marks.add(79); // Printing the marks of the students before grace System.out.println( \"Marks of students before grace : \" + marks); // Now we want to grace marks by 6 // using the streams to process over processing // collection // Using stream, we map every object and later // collect to List // and store them List<Integer> updatedMarks = marks.stream() .map(i -> i + 6) .collect(Collectors.toList()); // Printing the marks of the students after grace System.out.println( \"Marks of students after grace : \" + updatedMarks); }}", "e": 6874, "s": 5619, "text": null }, { "code": null, "e": 6983, "s": 6874, "text": "Marks of students before grace : [30, 78, 26, 96, 79]\nMarks of students after grace : [36, 84, 32, 102, 85]" }, { "code": null, "e": 7179, "s": 6983, "text": "Note: For every object if there is urgency to do some operations be it square, double or any other than only we need to use map() function operation else try to use filter() function operation. " }, { "code": null, "e": 7523, "s": 7179, "text": "Now geeks you are well aware of ‘why’ streams were introduced, but you should be wondering out ‘where’ to use it. The answer is very simple as we do use them too often in our day-to-day life. Hence, the geek in simpler words we say directly land p on wherever the concept of the collection is applicable, streams concept can be applied there. " }, { "code": null, "e": 7729, "s": 7523, "text": "Example 1: In general, daily world, whenever the data is fetching from the database, it is more likely we will be using collection so there itself streams concept is must apply to deal with processed data." }, { "code": null, "e": 7877, "s": 7729, "text": "Now we will be discussing out real-time examples to interrelate streams in our life. Here we will be taking the most widely used namely as follows:" }, { "code": null, "e": 7932, "s": 7877, "text": "Streams in a Grocery storeStreams in mobile networking" }, { "code": null, "e": 7959, "s": 7932, "text": "Streams in a Grocery store" }, { "code": null, "e": 7988, "s": 7959, "text": "Streams in mobile networking" }, { "code": null, "e": 8027, "s": 7988, "text": "Example 2: Streams in a Grocery store " }, { "code": null, "e": 8119, "s": 8027, "text": "The above pictorial image has been provided is implemented in streams which is as follows: " }, { "code": null, "e": 8389, "s": 8119, "text": "List<Integer> transactionsIds = \n transactions.stream()\n .filter(t -> t.getType() == Transaction.GROCERY)\n .sorted(comparing(Transaction::getValue).reversed())\n .map(Transaction::getId)\n .collect(toList());" }, { "code": null, "e": 8430, "s": 8389, "text": "Example 3: Streams in mobile networking " }, { "code": null, "e": 8703, "s": 8430, "text": "Similarly, we can go for another widely used concept that is our dealing with our mobile numbers. Here we will not be proposing out listings, simply will be demonstrating how the stream concept is invoked in mobile networking by various service providers across the globe." }, { "code": null, "e": 9572, "s": 8703, "text": "Collection can hold any number of object so let ‘mobileNumber’ be a collection and let it be holding various mobile numbers say it be holding 100+ numbers as objects. Suppose now the only carrier named ‘Airtel’ whom with which we are supposed to send a message if there is any migration between states in a country. So here streams concept is applied as if while dealing with all mobile numbers we will look out for this carrier using the filter() method operation of streams. In this way, we are able to deliver the messages without looking out for all mobile numbers and then delivering the message which senses impractical if done so as by now we are already too late to deliver. In this way these intermediate operations namely filter(), collect(), map() help out in the real world. Processing becomes super simpler which is the necessity of today’s digital world." }, { "code": null, "e": 9967, "s": 9572, "text": "Hoper by now you the users come to realize the power of streams in java as if we have to do the same task we do need to map corresponding to every object, increasing in code length, decreasing optimality of our code. With the usage of streams, we are able to in a single line irrespective of elements contained in the object as with the concept of streams we are dealing with the object itself." }, { "code": null, "e": 10051, "s": 9967, "text": "Note: filter, sorted, and map, which can be connected together to form a pipeline. " }, { "code": null, "e": 10061, "s": 10051, "text": "kk9826225" }, { "code": null, "e": 10073, "s": 10061, "text": "anikaseth98" }, { "code": null, "e": 10092, "s": 10073, "text": "surindertarika1234" }, { "code": null, "e": 10101, "s": 10092, "text": "sooda367" }, { "code": null, "e": 10117, "s": 10101, "text": "simranarora5sos" }, { "code": null, "e": 10129, "s": 10117, "text": "anikakapoor" }, { "code": null, "e": 10141, "s": 10129, "text": "java-stream" }, { "code": null, "e": 10146, "s": 10141, "text": "Java" }, { "code": null, "e": 10151, "s": 10146, "text": "Java" } ]
How to Create Wave Background using CSS ?
07 Jul, 2021 The wave background can be easily generated by using before selector. We will use a wave image of .png file format which you can create on your own or can download from here.HTML Code: In this section, we will design the basic structure of the code. html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> How to Create Wave Background using CSS ? </title></head> <body> <section class="pattern"> <div class="geeks"> <h1>GEEKS FOR GEEKS</h1> </div> </section></body> </html> CSS code: In this section, we will use some CSS property to design the wave background. First we will add a basic background to the section and then use the before selector to set the wave png file on top of our background. CSS <style> body { padding: 0%; margin: 0%; } .geeks { padding: 200px; text-align: center; } section { width: 100%; min-height: 500px; } .pattern { position: relative; background-color: #3bb78f; background-image: linear-gradient(315deg, #3bb78f 0%, #0bab64 74%); } .pattern:before { content: ""; position: absolute; bottom: 0; left: 0; width: 100%; height: 215px; background: url(wave.png); background-size: cover; background-repeat: no-repeat; }</style> Complete code: It is the combination of the above two code section. html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> How to Create Wave Background using CSS ? </title> <style> body { padding: 0%; margin: 0%; } .geeks { padding: 200px; text-align: center; } section { width: 100%; min-height: 300px; } .pattern { position: relative; background-color: #3bb78f; background-image: linear-gradient(315deg, #3bb78f 0%, #0bab64 74%); } .pattern:before { content: ""; position: absolute; bottom: 0; left: 0; width: 100%; height: 250px; background: url(https://media.geeksforgeeks.org/wp-content/uploads/20200326181026/wave3.png); background-size: cover; background-repeat: no-repeat; } </style></head> <body> <section class="pattern"> <div class="geeks"> <h1>GEEKS FOR GEEKS</h1> </div> </section></body> </html> Output: akshaysingh98088 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2021" }, { "code": null, "e": 280, "s": 28, "text": "The wave background can be easily generated by using before selector. We will use a wave image of .png file format which you can create on your own or can download from here.HTML Code: In this section, we will design the basic structure of the code. " }, { "code": null, "e": 285, "s": 280, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> How to Create Wave Background using CSS ? </title></head> <body> <section class=\"pattern\"> <div class=\"geeks\"> <h1>GEEKS FOR GEEKS</h1> </div> </section></body> </html>", "e": 666, "s": 285, "text": null }, { "code": null, "e": 891, "s": 666, "text": "CSS code: In this section, we will use some CSS property to design the wave background. First we will add a basic background to the section and then use the before selector to set the wave png file on top of our background. " }, { "code": null, "e": 895, "s": 891, "text": "CSS" }, { "code": "<style> body { padding: 0%; margin: 0%; } .geeks { padding: 200px; text-align: center; } section { width: 100%; min-height: 500px; } .pattern { position: relative; background-color: #3bb78f; background-image: linear-gradient(315deg, #3bb78f 0%, #0bab64 74%); } .pattern:before { content: \"\"; position: absolute; bottom: 0; left: 0; width: 100%; height: 215px; background: url(wave.png); background-size: cover; background-repeat: no-repeat; }</style>", "e": 1543, "s": 895, "text": null }, { "code": null, "e": 1612, "s": 1543, "text": "Complete code: It is the combination of the above two code section. " }, { "code": null, "e": 1617, "s": 1612, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> How to Create Wave Background using CSS ? </title> <style> body { padding: 0%; margin: 0%; } .geeks { padding: 200px; text-align: center; } section { width: 100%; min-height: 300px; } .pattern { position: relative; background-color: #3bb78f; background-image: linear-gradient(315deg, #3bb78f 0%, #0bab64 74%); } .pattern:before { content: \"\"; position: absolute; bottom: 0; left: 0; width: 100%; height: 250px; background: url(https://media.geeksforgeeks.org/wp-content/uploads/20200326181026/wave3.png); background-size: cover; background-repeat: no-repeat; } </style></head> <body> <section class=\"pattern\"> <div class=\"geeks\"> <h1>GEEKS FOR GEEKS</h1> </div> </section></body> </html>", "e": 2807, "s": 1617, "text": null }, { "code": null, "e": 2817, "s": 2807, "text": "Output: " }, { "code": null, "e": 2836, "s": 2819, "text": "akshaysingh98088" }, { "code": null, "e": 2845, "s": 2836, "text": "CSS-Misc" }, { "code": null, "e": 2855, "s": 2845, "text": "HTML-Misc" }, { "code": null, "e": 2859, "s": 2855, "text": "CSS" }, { "code": null, "e": 2864, "s": 2859, "text": "HTML" }, { "code": null, "e": 2881, "s": 2864, "text": "Web Technologies" }, { "code": null, "e": 2908, "s": 2881, "text": "Web technologies Questions" }, { "code": null, "e": 2913, "s": 2908, "text": "HTML" }, { "code": null, "e": 3011, "s": 2913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3059, "s": 3011, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3121, "s": 3059, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3171, "s": 3121, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3229, "s": 3171, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 3279, "s": 3229, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3327, "s": 3279, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3389, "s": 3327, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3439, "s": 3389, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3463, "s": 3439, "text": "REST API (Introduction)" } ]
How to Draw a Trapezium using HTML and CSS ?
21 Jun, 2021 A Trapezium is a Quadrilateral which has two parallel and two non-parallel sides. In this article we will create a Trapezium shape using simple HTML and CSS. HTML Code: In this section, we will create a simple element using the HTML div tag. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Trapezium</title></head> <body> <div class="trapezium"></div> </body></html> CSS Code: In this section, we will first design the div element using some basic CSS properties and then use the border-bottom, border-left and border-right properties to create the trapezium shape. css <style> /* creating the trapezium shape*/ .trapezium { height: 0; width: 150px; border-bottom: 150px solid green; border-left: 100px solid transparent; border-right: 100px solid transparent; }</style> Final Code: It is the combination of the above two code sections. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Trapezium</title> <style> /* Creating the trapezium shape*/ .trapezium { height: 0; width: 150px; border-bottom: 150px solid green; border-left: 100px solid transparent; border-right: 100px solid transparent; } </style></head> <body> <div class="trapezium"></div></body> </html> Output: CoderSaty CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2021" }, { "code": null, "e": 186, "s": 28, "text": "A Trapezium is a Quadrilateral which has two parallel and two non-parallel sides. In this article we will create a Trapezium shape using simple HTML and CSS." }, { "code": null, "e": 270, "s": 186, "text": "HTML Code: In this section, we will create a simple element using the HTML div tag." }, { "code": null, "e": 275, "s": 270, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Trapezium</title></head> <body> <div class=\"trapezium\"></div> </body></html>", "e": 500, "s": 275, "text": null }, { "code": null, "e": 699, "s": 500, "text": "CSS Code: In this section, we will first design the div element using some basic CSS properties and then use the border-bottom, border-left and border-right properties to create the trapezium shape." }, { "code": null, "e": 703, "s": 699, "text": "css" }, { "code": "<style> /* creating the trapezium shape*/ .trapezium { height: 0; width: 150px; border-bottom: 150px solid green; border-left: 100px solid transparent; border-right: 100px solid transparent; }</style>", "e": 927, "s": 703, "text": null }, { "code": null, "e": 993, "s": 927, "text": "Final Code: It is the combination of the above two code sections." }, { "code": null, "e": 998, "s": 993, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Trapezium</title> <style> /* Creating the trapezium shape*/ .trapezium { height: 0; width: 150px; border-bottom: 150px solid green; border-left: 100px solid transparent; border-right: 100px solid transparent; } </style></head> <body> <div class=\"trapezium\"></div></body> </html>", "e": 1466, "s": 998, "text": null }, { "code": null, "e": 1474, "s": 1466, "text": "Output:" }, { "code": null, "e": 1484, "s": 1474, "text": "CoderSaty" }, { "code": null, "e": 1493, "s": 1484, "text": "CSS-Misc" }, { "code": null, "e": 1503, "s": 1493, "text": "HTML-Misc" }, { "code": null, "e": 1507, "s": 1503, "text": "CSS" }, { "code": null, "e": 1512, "s": 1507, "text": "HTML" }, { "code": null, "e": 1529, "s": 1512, "text": "Web Technologies" }, { "code": null, "e": 1556, "s": 1529, "text": "Web technologies Questions" }, { "code": null, "e": 1561, "s": 1556, "text": "HTML" } ]
Difference Between Multithreading vs Multiprocessing in Python
10 May, 2020 In this article, we will learn the what, why, and how of multithreading and multiprocessing in Python. Before we dive into the code, let us understand what these terms mean. A program is an executable file which consists of a set of instructions to perform some task and is usually stored on the disk of your computer. A process is what we call a program that has been loaded into memory along with all the resources it needs to operate. It has its own memory space. A thread is the unit of execution within a process. A process can have multiple threads running as a part of it, where each thread uses the process’s memory space and shares it with other threads. Multithreading is a technique where multiple threads are spawned by a process to do different tasks, at about the same time, just one after the other. This gives you the illusion that the threads are running in parallel, but they are actually run in a concurrent manner. In Python, the Global Interpreter Lock (GIL) prevents the threads from running simultaneously. Multiprocessing is a technique where parallelism in its truest form is achieved. Multiple processes are run across multiple CPU cores, which do not share the resources among them. Each process can have many threads running in its own memory space. In Python, each process has its own instance of Python interpreter doing the job of executing the instructions. Now, let’s jump into the program where we try to execute two different types of functions: IO-bound and CPU-bound in six different ways. Inside the IO-bound function, we ask the CPU to sit idle and pass time whereas, inside the CPU-bound function, the CPU is going to be busy churning out a few numbers. Requirements: A Windows computer (My machine has 6 cores). Python 3.x installed. Any text editor/IDE to write Python programs (I am using Sublime Text here). Note: Below is the structure of our program, which will be common across all the six parts. In the place where it is mentioned # YOUR CODE SNIPPET HERE, replace it with the code snippet of each part as you go. import time, osfrom threading import Thread, current_threadfrom multiprocessing import Process, current_process COUNT = 200000000SLEEP = 10 def io_bound(sec): pid = os.getpid() threadName = current_thread().name processName = current_process().name print(f"{pid} * {processName} * {threadName} \ ---> Start sleeping...") time.sleep(sec) print(f"{pid} * {processName} * {threadName} \ ---> Finished sleeping...") def cpu_bound(n): pid = os.getpid() threadName = current_thread().name processName = current_process().name print(f"{pid} * {processName} * {threadName} \ ---> Start counting...") while n>0: n -= 1 print(f"{pid} * {processName} * {threadName} \ ---> Finished counting...") if __name__=="__main__": start = time.time() # YOUR CODE SNIPPET HERE end = time.time() print('Time taken in seconds -', end - start) Part 1: Running IO-bound task twice, one after the other... # Code snippet for Part 1io_bound(SLEEP)io_bound(SLEEP) Here, we ask our CPU to execute the function io_bound(), which takes in an integer (10, here) as a parameter and asks the CPU to sleep for that many seconds. This execution takes a total of 20 seconds, as each function execution takes 10 seconds to complete. Note that, it is the same MainProcess that calls our function twice, one after the other, using its default thread, MainThread. Part 2: Using threading to run the IO-bound tasks... # Code snippet for Part 2t1 = Thread(target = io_bound, args =(SLEEP, ))t2 = Thread(target = io_bound, args =(SLEEP, ))t1.start()t2.start()t1.join()t2.join() Here, let’s use threading in Python to speed up the execution of the functions. The threads Thread-1 and Thread-2 are started by our MainProcess, each of which calls our function, at almost the same time. Both the threads complete their job of sleeping for 10 seconds, concurrently. This reduced the total execution time of our whole program by a significant 50%. Hence, multithreading is the go-to solution for executing tasks wherein the idle time of our CPU can be utilized to perform other tasks. Hence, saving time by making use of the wait time. Part 3: Running CPU-bound task twice, one after the other... # Code snippet for Part 3cpu_bound(COUNT)cpu_bound(COUNT) Here, we shall call our function cpu_bound(), which takes in a big number (200000000, here) as a parameter and decrements it at each step until it is zero. Our CPU is asked to do the countdown at each function call, which roughly takes around 12 seconds (this number might differ on your machine). Hence, the execution of the whole program took me about 26 seconds to complete. Note that it is once again our MainProcess calling the function twice, one after the other, in its default thread, MainThread. Part 4: Can threading speed up our CPU-bound tasks? # Code snippet for Part 4t1 = Thread(target = cpu_bound, args =(COUNT, ))t2 = Thread(target = cpu_bound, args =(COUNT, ))t1.start()t2.start()t1.join()t2.join() Okay, we just proved that threading worked amazingly well for multiple IO-bound tasks. Let’s use the same approach for executing our CPU-bound tasks. Well, it did kick off our threads at the same time initially, but in the end, we see that the whole program execution took about a whopping 40 seconds! What just happened? This is because when Thread-1 started, it acquired the Global Interpreter Lock (GIL) which prevented Thread-2 to make use of the CPU. Hence, Thread-2 had to wait for Thread-1 to finish its task and release the lock so that it can acquire the lock and perform its task. This acquisition and release of the lock added overhead to the total execution time. Therefore, we can safely say that threading is not an ideal solution for tasks that requires CPU to work on something. Part 5: So, does splitting the tasks as separate processes work? # Code snippet for Part 5p1 = Process(target = cpu_bound, args =(COUNT, ))p2 = Process(target = cpu_bound, args =(COUNT, ))p1.start()p2.start()p1.join()p2.join() Let’s cut to the chase. Multiprocessing is the answer. Here the MainProcess spins up two subprocesses, having different PIDs, each of which does the job of decreasing the number to zero. Each process runs in parallel, making use of separate CPU core and its own instance of the Python interpreter, therefore the whole program execution took only 12 seconds. Note that the output might be printed in unordered fashion as the processes are independent of each other. Each process executes the function in its own default thread, MainThread. Open your Task Manager during the execution of your program. You can see 3 instances of the Python interpreter, one each for MainProcess, Process-1, and Process-2. You can also see that during the program execution, the Power Usage of the two subprocesses is “Very High”, as the task they are performing is actually taking a toll on their own CPU cores, as shown by the spikes in the CPU Performance graph. Part 6: Hey, lets use multiprocessing for our IO-bound tasks... # Code snippet for Part 6p1 = Process(target = io_bound, args =(SLEEP, ))p2 = Process(target = io_bound, args =(SLEEP, ))p1.start()p2.start()p1.join()p2.join() Now that we got a fair idea about multiprocessing helping us achieve parallelism, we shall try to use this technique for running our IO-bound tasks. We do observe that the results are extraordinary, just as in the case of multithreading. Since the processes Process-1 and Process-2 are performing the task of asking their own CPU core to sit idle for a few seconds, we don’t find high Power Usage. But the creation of processes itself is a CPU heavy task and requires more time than the creation of threads. Also, processes require more resources than threads. Hence, it is always better to have multiprocessing as the second option for IO-bound tasks, with multithreading being the first. Well, that was quite a ride. We saw six different approaches to perform a task, that roughly took about 10 seconds, based on whether the task is light or heavy on the CPU. Bottomline: Multithreading for IO-bound tasks. Multiprocessing for CPU-bound tasks. Python-multithreading Difference Between Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 May, 2020" }, { "code": null, "e": 228, "s": 54, "text": "In this article, we will learn the what, why, and how of multithreading and multiprocessing in Python. Before we dive into the code, let us understand what these terms mean." }, { "code": null, "e": 373, "s": 228, "text": "A program is an executable file which consists of a set of instructions to perform some task and is usually stored on the disk of your computer." }, { "code": null, "e": 521, "s": 373, "text": "A process is what we call a program that has been loaded into memory along with all the resources it needs to operate. It has its own memory space." }, { "code": null, "e": 718, "s": 521, "text": "A thread is the unit of execution within a process. A process can have multiple threads running as a part of it, where each thread uses the process’s memory space and shares it with other threads." }, { "code": null, "e": 1084, "s": 718, "text": "Multithreading is a technique where multiple threads are spawned by a process to do different tasks, at about the same time, just one after the other. This gives you the illusion that the threads are running in parallel, but they are actually run in a concurrent manner. In Python, the Global Interpreter Lock (GIL) prevents the threads from running simultaneously." }, { "code": null, "e": 1444, "s": 1084, "text": "Multiprocessing is a technique where parallelism in its truest form is achieved. Multiple processes are run across multiple CPU cores, which do not share the resources among them. Each process can have many threads running in its own memory space. In Python, each process has its own instance of Python interpreter doing the job of executing the instructions." }, { "code": null, "e": 1748, "s": 1444, "text": "Now, let’s jump into the program where we try to execute two different types of functions: IO-bound and CPU-bound in six different ways. Inside the IO-bound function, we ask the CPU to sit idle and pass time whereas, inside the CPU-bound function, the CPU is going to be busy churning out a few numbers." }, { "code": null, "e": 1762, "s": 1748, "text": "Requirements:" }, { "code": null, "e": 1807, "s": 1762, "text": "A Windows computer (My machine has 6 cores)." }, { "code": null, "e": 1829, "s": 1807, "text": "Python 3.x installed." }, { "code": null, "e": 1906, "s": 1829, "text": "Any text editor/IDE to write Python programs (I am using Sublime Text here)." }, { "code": null, "e": 2116, "s": 1906, "text": "Note: Below is the structure of our program, which will be common across all the six parts. In the place where it is mentioned # YOUR CODE SNIPPET HERE, replace it with the code snippet of each part as you go." }, { "code": "import time, osfrom threading import Thread, current_threadfrom multiprocessing import Process, current_process COUNT = 200000000SLEEP = 10 def io_bound(sec): pid = os.getpid() threadName = current_thread().name processName = current_process().name print(f\"{pid} * {processName} * {threadName} \\ ---> Start sleeping...\") time.sleep(sec) print(f\"{pid} * {processName} * {threadName} \\ ---> Finished sleeping...\") def cpu_bound(n): pid = os.getpid() threadName = current_thread().name processName = current_process().name print(f\"{pid} * {processName} * {threadName} \\ ---> Start counting...\") while n>0: n -= 1 print(f\"{pid} * {processName} * {threadName} \\ ---> Finished counting...\") if __name__==\"__main__\": start = time.time() # YOUR CODE SNIPPET HERE end = time.time() print('Time taken in seconds -', end - start)", "e": 3040, "s": 2116, "text": null }, { "code": null, "e": 3100, "s": 3040, "text": "Part 1: Running IO-bound task twice, one after the other..." }, { "code": "# Code snippet for Part 1io_bound(SLEEP)io_bound(SLEEP)", "e": 3156, "s": 3100, "text": null }, { "code": null, "e": 3543, "s": 3156, "text": "Here, we ask our CPU to execute the function io_bound(), which takes in an integer (10, here) as a parameter and asks the CPU to sleep for that many seconds. This execution takes a total of 20 seconds, as each function execution takes 10 seconds to complete. Note that, it is the same MainProcess that calls our function twice, one after the other, using its default thread, MainThread." }, { "code": null, "e": 3596, "s": 3543, "text": "Part 2: Using threading to run the IO-bound tasks..." }, { "code": "# Code snippet for Part 2t1 = Thread(target = io_bound, args =(SLEEP, ))t2 = Thread(target = io_bound, args =(SLEEP, ))t1.start()t2.start()t1.join()t2.join()", "e": 3754, "s": 3596, "text": null }, { "code": null, "e": 4306, "s": 3754, "text": "Here, let’s use threading in Python to speed up the execution of the functions. The threads Thread-1 and Thread-2 are started by our MainProcess, each of which calls our function, at almost the same time. Both the threads complete their job of sleeping for 10 seconds, concurrently. This reduced the total execution time of our whole program by a significant 50%. Hence, multithreading is the go-to solution for executing tasks wherein the idle time of our CPU can be utilized to perform other tasks. Hence, saving time by making use of the wait time." }, { "code": null, "e": 4367, "s": 4306, "text": "Part 3: Running CPU-bound task twice, one after the other..." }, { "code": "# Code snippet for Part 3cpu_bound(COUNT)cpu_bound(COUNT)", "e": 4425, "s": 4367, "text": null }, { "code": null, "e": 4930, "s": 4425, "text": "Here, we shall call our function cpu_bound(), which takes in a big number (200000000, here) as a parameter and decrements it at each step until it is zero. Our CPU is asked to do the countdown at each function call, which roughly takes around 12 seconds (this number might differ on your machine). Hence, the execution of the whole program took me about 26 seconds to complete. Note that it is once again our MainProcess calling the function twice, one after the other, in its default thread, MainThread." }, { "code": null, "e": 4982, "s": 4930, "text": "Part 4: Can threading speed up our CPU-bound tasks?" }, { "code": "# Code snippet for Part 4t1 = Thread(target = cpu_bound, args =(COUNT, ))t2 = Thread(target = cpu_bound, args =(COUNT, ))t1.start()t2.start()t1.join()t2.join()", "e": 5142, "s": 4982, "text": null }, { "code": null, "e": 5937, "s": 5142, "text": "Okay, we just proved that threading worked amazingly well for multiple IO-bound tasks. Let’s use the same approach for executing our CPU-bound tasks. Well, it did kick off our threads at the same time initially, but in the end, we see that the whole program execution took about a whopping 40 seconds! What just happened? This is because when Thread-1 started, it acquired the Global Interpreter Lock (GIL) which prevented Thread-2 to make use of the CPU. Hence, Thread-2 had to wait for Thread-1 to finish its task and release the lock so that it can acquire the lock and perform its task. This acquisition and release of the lock added overhead to the total execution time. Therefore, we can safely say that threading is not an ideal solution for tasks that requires CPU to work on something." }, { "code": null, "e": 6002, "s": 5937, "text": "Part 5: So, does splitting the tasks as separate processes work?" }, { "code": "# Code snippet for Part 5p1 = Process(target = cpu_bound, args =(COUNT, ))p2 = Process(target = cpu_bound, args =(COUNT, ))p1.start()p2.start()p1.join()p2.join()", "e": 6164, "s": 6002, "text": null }, { "code": null, "e": 7110, "s": 6164, "text": "Let’s cut to the chase. Multiprocessing is the answer. Here the MainProcess spins up two subprocesses, having different PIDs, each of which does the job of decreasing the number to zero. Each process runs in parallel, making use of separate CPU core and its own instance of the Python interpreter, therefore the whole program execution took only 12 seconds. Note that the output might be printed in unordered fashion as the processes are independent of each other. Each process executes the function in its own default thread, MainThread. Open your Task Manager during the execution of your program. You can see 3 instances of the Python interpreter, one each for MainProcess, Process-1, and Process-2. You can also see that during the program execution, the Power Usage of the two subprocesses is “Very High”, as the task they are performing is actually taking a toll on their own CPU cores, as shown by the spikes in the CPU Performance graph." }, { "code": null, "e": 7174, "s": 7110, "text": "Part 6: Hey, lets use multiprocessing for our IO-bound tasks..." }, { "code": "# Code snippet for Part 6p1 = Process(target = io_bound, args =(SLEEP, ))p2 = Process(target = io_bound, args =(SLEEP, ))p1.start()p2.start()p1.join()p2.join()", "e": 7334, "s": 7174, "text": null }, { "code": null, "e": 8024, "s": 7334, "text": "Now that we got a fair idea about multiprocessing helping us achieve parallelism, we shall try to use this technique for running our IO-bound tasks. We do observe that the results are extraordinary, just as in the case of multithreading. Since the processes Process-1 and Process-2 are performing the task of asking their own CPU core to sit idle for a few seconds, we don’t find high Power Usage. But the creation of processes itself is a CPU heavy task and requires more time than the creation of threads. Also, processes require more resources than threads. Hence, it is always better to have multiprocessing as the second option for IO-bound tasks, with multithreading being the first." }, { "code": null, "e": 8196, "s": 8024, "text": "Well, that was quite a ride. We saw six different approaches to perform a task, that roughly took about 10 seconds, based on whether the task is light or heavy on the CPU." }, { "code": null, "e": 8280, "s": 8196, "text": "Bottomline: Multithreading for IO-bound tasks. Multiprocessing for CPU-bound tasks." }, { "code": null, "e": 8302, "s": 8280, "text": "Python-multithreading" }, { "code": null, "e": 8321, "s": 8302, "text": "Difference Between" }, { "code": null, "e": 8328, "s": 8321, "text": "Python" }, { "code": null, "e": 8344, "s": 8328, "text": "Write From Home" } ]
Looping Statements | Shell Script
11 Mar, 2022 Looping Statements in Shell Scripting: There are total 3 looping statements which can be used in bash programming while statementfor statementuntil statement while statement for statement until statement To alter the flow of loop statements, two commands are used they are, breakcontinue break continue Their descriptions and syntax are as follows: while statement Here command is evaluated and based on the result loop will executed, if command raise to false then loop will be terminated Syntax for statement The for loop operate on lists of items. It repeats a set of commands for every item in a list. Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN. Syntax until statement The until loop is executed as many as times the condition/command evaluates to false. The loop terminates when the condition/command becomes true. Syntax Example ProgramsExample 1: Implementing for loop with break statement php #Start of for loopfor a in 1 2 3 4 5 6 7 8 9 10do # if a is equal to 5 break the loop if [ $a == 5 ] then break fi # Print the value echo "Iteration no $a"done Output $bash -f main.sh Iteration no 1 Iteration no 2 Iteration no 3 Iteration no 4 Example 2: Implementing for loop with continue statement php for a in 1 2 3 4 5 6 7 8 9 10do # if a = 5 then continue the loop and # don't move to line 8 if [ $a == 5 ] then continue fi echo "Iteration no $a"done Output $bash -f main.sh Iteration no 1 Iteration no 2 Iteration no 3 Iteration no 4 Iteration no 6 Iteration no 7 Iteration no 8 Iteration no 9 Iteration no 10 Example 3: Implementing while loop php a=0# -lt is less than operator #Iterate the loop until a less than 10while [ $a -lt 10 ]do # Print the values echo $a # increment the value a=`expr $a + 1`done Output: $bash -f main.sh 0 1 2 3 4 5 6 7 8 9 Example 4: Implementing until loop php a=0# -gt is greater than operator #Iterate the loop until a is greater than 10until [ $a -gt 10 ]do # Print the values echo $a # increment the value a=`expr $a + 1`done Output: $bash -f main.sh 0 1 2 3 4 5 6 7 8 9 10 Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts. Example 5: PHP COLORS="red green blue" # the for loop continues until it reads all the values from the COLORS for COLOR in $COLORSdo echo "COLOR: $COLOR"done Output: $bash -f main.sh COLOR: red COLOR: green COLOR: blue Example 6: We can even access the positional parameters using loops We execute a shell script named sample.sh using three parameters Script Execution: main.sh sample1 sample2 sample3 We can access above three parameters using $@ PHP echo "Executing script" # the script is executed using the below command# main.sh sample1 sample2 sample# where sample1, sample2 and sample3 are the positional arguments# here $@ contains all the positional arguments. for SAMPLE in $@do echo "The given sample is: $SAMPLE"done Output: $bash -f main.sh sample1 sample2 sample3 Executing script The given sample is sample1 The given sample is sample2 The given sample is sample3 Example 7: Infinite loop PHP while truedo # Command to be executed # sleep 1 indicates it sleeps for 1 sec echo "Hi, I am infinity loop" sleep 1done Output: $bash -f main.sh Hi, I am infinity loop Hi, I am infinity loop Hi, I am infinity loop . . . . It continues Example 8: Checking for user input PHP CORRECT=nwhile [ "$CORRECT" == "n" ]do # loop discontinues when you enter y i.e.e, when your name is correct # -p stands for prompt asking for the input read -p "Enter your name:" NAME read -p "Is ${NAME} correct? " CORRECTdone Output: $bash -f main.sh Enter your name:Ironman Is Ironman correct? n Enter your name:Spiderman Is Spiderman correct? y ashutosh450 harikamaryala Shell Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Mar, 2022" }, { "code": null, "e": 170, "s": 54, "text": "Looping Statements in Shell Scripting: There are total 3 looping statements which can be used in bash programming " }, { "code": null, "e": 214, "s": 170, "text": "while statementfor statementuntil statement" }, { "code": null, "e": 230, "s": 214, "text": "while statement" }, { "code": null, "e": 244, "s": 230, "text": "for statement" }, { "code": null, "e": 260, "s": 244, "text": "until statement" }, { "code": null, "e": 332, "s": 260, "text": "To alter the flow of loop statements, two commands are used they are, " }, { "code": null, "e": 346, "s": 332, "text": "breakcontinue" }, { "code": null, "e": 352, "s": 346, "text": "break" }, { "code": null, "e": 361, "s": 352, "text": "continue" }, { "code": null, "e": 409, "s": 361, "text": "Their descriptions and syntax are as follows: " }, { "code": null, "e": 559, "s": 409, "text": "while statement Here command is evaluated and based on the result loop will executed, if command raise to false then loop will be terminated Syntax " }, { "code": null, "e": 917, "s": 563, "text": "for statement The for loop operate on lists of items. It repeats a set of commands for every item in a list. Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN. Syntax " }, { "code": null, "e": 1093, "s": 921, "text": "until statement The until loop is executed as many as times the condition/command evaluates to false. The loop terminates when the condition/command becomes true. Syntax " }, { "code": null, "e": 1169, "s": 1097, "text": "Example ProgramsExample 1: Implementing for loop with break statement " }, { "code": null, "e": 1173, "s": 1169, "text": "php" }, { "code": "#Start of for loopfor a in 1 2 3 4 5 6 7 8 9 10do # if a is equal to 5 break the loop if [ $a == 5 ] then break fi # Print the value echo \"Iteration no $a\"done", "e": 1358, "s": 1173, "text": null }, { "code": null, "e": 1367, "s": 1358, "text": "Output " }, { "code": null, "e": 1444, "s": 1367, "text": "$bash -f main.sh\nIteration no 1\nIteration no 2\nIteration no 3\nIteration no 4" }, { "code": null, "e": 1503, "s": 1444, "text": "Example 2: Implementing for loop with continue statement " }, { "code": null, "e": 1507, "s": 1503, "text": "php" }, { "code": "for a in 1 2 3 4 5 6 7 8 9 10do # if a = 5 then continue the loop and # don't move to line 8 if [ $a == 5 ] then continue fi echo \"Iteration no $a\"done", "e": 1684, "s": 1507, "text": null }, { "code": null, "e": 1693, "s": 1684, "text": "Output " }, { "code": null, "e": 1846, "s": 1693, "text": "$bash -f main.sh\nIteration no 1\nIteration no 2\nIteration no 3\nIteration no 4\nIteration no 6\nIteration no 7\nIteration no 8\nIteration no 9\nIteration no 10" }, { "code": null, "e": 1883, "s": 1846, "text": "Example 3: Implementing while loop " }, { "code": null, "e": 1887, "s": 1883, "text": "php" }, { "code": "a=0# -lt is less than operator #Iterate the loop until a less than 10while [ $a -lt 10 ]do # Print the values echo $a # increment the value a=`expr $a + 1`done", "e": 2064, "s": 1887, "text": null }, { "code": null, "e": 2074, "s": 2064, "text": "Output: " }, { "code": null, "e": 2111, "s": 2074, "text": "$bash -f main.sh\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9" }, { "code": null, "e": 2148, "s": 2111, "text": "Example 4: Implementing until loop " }, { "code": null, "e": 2152, "s": 2148, "text": "php" }, { "code": "a=0# -gt is greater than operator #Iterate the loop until a is greater than 10until [ $a -gt 10 ]do # Print the values echo $a # increment the value a=`expr $a + 1`done", "e": 2338, "s": 2152, "text": null }, { "code": null, "e": 2348, "s": 2338, "text": "Output: " }, { "code": null, "e": 2388, "s": 2348, "text": "$bash -f main.sh\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10" }, { "code": null, "e": 2513, "s": 2388, "text": "Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts. " }, { "code": null, "e": 2524, "s": 2513, "text": "Example 5:" }, { "code": null, "e": 2528, "s": 2524, "text": "PHP" }, { "code": "COLORS=\"red green blue\" # the for loop continues until it reads all the values from the COLORS for COLOR in $COLORSdo echo \"COLOR: $COLOR\"done", "e": 2676, "s": 2528, "text": null }, { "code": null, "e": 2684, "s": 2676, "text": "Output:" }, { "code": null, "e": 2737, "s": 2684, "text": "$bash -f main.sh\nCOLOR: red\nCOLOR: green\nCOLOR: blue" }, { "code": null, "e": 2748, "s": 2737, "text": "Example 6:" }, { "code": null, "e": 2805, "s": 2748, "text": "We can even access the positional parameters using loops" }, { "code": null, "e": 2870, "s": 2805, "text": "We execute a shell script named sample.sh using three parameters" }, { "code": null, "e": 2920, "s": 2870, "text": "Script Execution: main.sh sample1 sample2 sample3" }, { "code": null, "e": 2966, "s": 2920, "text": "We can access above three parameters using $@" }, { "code": null, "e": 2970, "s": 2966, "text": "PHP" }, { "code": "echo \"Executing script\" # the script is executed using the below command# main.sh sample1 sample2 sample# where sample1, sample2 and sample3 are the positional arguments# here $@ contains all the positional arguments. for SAMPLE in $@do echo \"The given sample is: $SAMPLE\"done", "e": 3252, "s": 2970, "text": null }, { "code": null, "e": 3260, "s": 3252, "text": "Output:" }, { "code": null, "e": 3402, "s": 3260, "text": "$bash -f main.sh sample1 sample2 sample3\nExecuting script\nThe given sample is sample1\nThe given sample is sample2\nThe given sample is sample3" }, { "code": null, "e": 3427, "s": 3402, "text": "Example 7: Infinite loop" }, { "code": null, "e": 3431, "s": 3427, "text": "PHP" }, { "code": "while truedo # Command to be executed # sleep 1 indicates it sleeps for 1 sec echo \"Hi, I am infinity loop\" sleep 1done", "e": 3555, "s": 3431, "text": null }, { "code": null, "e": 3563, "s": 3555, "text": "Output:" }, { "code": null, "e": 3670, "s": 3563, "text": "$bash -f main.sh\nHi, I am infinity loop\nHi, I am infinity loop\nHi, I am infinity loop\n.\n.\n.\n.\nIt continues" }, { "code": null, "e": 3705, "s": 3670, "text": "Example 8: Checking for user input" }, { "code": null, "e": 3709, "s": 3705, "text": "PHP" }, { "code": "CORRECT=nwhile [ \"$CORRECT\" == \"n\" ]do # loop discontinues when you enter y i.e.e, when your name is correct # -p stands for prompt asking for the input read -p \"Enter your name:\" NAME read -p \"Is ${NAME} correct? \" CORRECTdone", "e": 3941, "s": 3709, "text": null }, { "code": null, "e": 3949, "s": 3941, "text": "Output:" }, { "code": null, "e": 4062, "s": 3949, "text": "$bash -f main.sh\nEnter your name:Ironman\nIs Ironman correct? n\nEnter your name:Spiderman\nIs Spiderman correct? y" }, { "code": null, "e": 4074, "s": 4062, "text": "ashutosh450" }, { "code": null, "e": 4088, "s": 4074, "text": "harikamaryala" }, { "code": null, "e": 4094, "s": 4088, "text": "Shell" }, { "code": null, "e": 4107, "s": 4094, "text": "Shell Script" }, { "code": null, "e": 4118, "s": 4107, "text": "Linux-Unix" } ]
Tuples in Python
17 Jan, 2022 A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable. Creating Tuples # An empty tupleempty_tuple = ()print (empty_tuple) Output: () # Creating non-empty tuples # One way of creationtup = 'python', 'geeks'print(tup) # Another for doing the sametup = ('python', 'geeks')print(tup) Output ('python', 'geeks') ('python', 'geeks') Note: In case your generating a tuple with a single element, make sure to add a comma after the element. Concatenation of Tuples # Code for concatenating 2 tuples tuple1 = (0, 1, 2, 3)tuple2 = ('python', 'geek') # Concatenating above twoprint(tuple1 + tuple2) Output: (0, 1, 2, 3, 'python', 'geek') Nesting of Tuples # Code for creating nested tuples tuple1 = (0, 1, 2, 3)tuple2 = ('python', 'geek')tuple3 = (tuple1, tuple2)print(tuple3) Output : ((0, 1, 2, 3), ('python', 'geek')) Repetition in Tuples # Code to create a tuple with repetition tuple3 = ('python',)*3print(tuple3) Output ('python', 'python', 'python') Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’. Immutable Tuples #code to test that tuples are immutable tuple1 = (0, 1, 2, 3)tuple1[0] = 4print(tuple1) Output Traceback (most recent call last): File "e0eaddff843a8695575daec34506f126.py", line 3, in tuple1[0]=4 TypeError: 'tuple' object does not support item assignment Slicing in Tuples # code to test slicing tuple1 = (0 ,1, 2, 3)print(tuple1[1:])print(tuple1[::-1])print(tuple1[2:4]) Output (1, 2, 3) (3, 2, 1, 0) (2, 3) Deleting a Tuple # Code for deleting a tuple tuple3 = ( 0, 1)del tuple3print(tuple3) Error: Traceback (most recent call last): File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module> print(tuple3) NameError: name 'tuple3' is not defined Output: (0, 1) Finding Length of a Tuple # Code for printing the length of a tuple tuple2 = ('python', 'geek')print(len(tuple2)) Output 2 Converting list to a Tuple # Code for converting a list and a string into a tuple list1 = [0, 1, 2]print(tuple(list1))print(tuple('python')) # string 'python' Output (0, 1, 2) ('p', 'y', 't', 'h', 'o', 'n') Takes a single parameter which may be a list,string,set or even a dictionary( only keys are taken as elements) and converts them to a tuple. Tuples in a loop #python code for creating tuples in a loop tup = ('geek',)n = 5 #Number of time loop runsfor i in range(int(n)): tup = (tup,) print(tup) Output : (('geek',),) ((('geek',),),) (((('geek',),),),) ((((('geek',),),),),) (((((('geek',),),),),),) Using cmp(), max() , min() # A python program to demonstrate the use of# cmp(), max(), min() tuple1 = ('python', 'geek')tuple2 = ('coder', 1) if (cmp(tuple1, tuple2) != 0): # cmp() returns 0 if matched, 1 when not tuple1 # is longer and -1 when tuple1 is shorter print('Not the same')else: print('Same')print ('Maximum element in tuples 1,2: ' + str(max(tuple1)) + ',' + str(max(tuple2)))print ('Minimum element in tuples 1,2: ' + str(min(tuple1)) + ',' + str(min(tuple2))) Output Not the same Maximum element in tuples 1,2: python,coder Minimum element in tuples 1,2: geek,1 Note: max() and min() checks the based on ASCII values. If there are two strings in a tuple, then the first different character in the strings are checked. This article is contributed by Sri Sanketh Uppalapati. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 python-tuple Python School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jan, 2022" }, { "code": null, "e": 265, "s": 52, "text": "A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable." }, { "code": null, "e": 281, "s": 265, "text": "Creating Tuples" }, { "code": "# An empty tupleempty_tuple = ()print (empty_tuple)", "e": 333, "s": 281, "text": null }, { "code": null, "e": 341, "s": 333, "text": "Output:" }, { "code": null, "e": 345, "s": 341, "text": " ()" }, { "code": "# Creating non-empty tuples # One way of creationtup = 'python', 'geeks'print(tup) # Another for doing the sametup = ('python', 'geeks')print(tup)", "e": 492, "s": 345, "text": null }, { "code": null, "e": 499, "s": 492, "text": "Output" }, { "code": null, "e": 539, "s": 499, "text": "('python', 'geeks')\n('python', 'geeks')" }, { "code": null, "e": 644, "s": 539, "text": "Note: In case your generating a tuple with a single element, make sure to add a comma after the element." }, { "code": null, "e": 670, "s": 646, "text": "Concatenation of Tuples" }, { "code": "# Code for concatenating 2 tuples tuple1 = (0, 1, 2, 3)tuple2 = ('python', 'geek') # Concatenating above twoprint(tuple1 + tuple2)", "e": 801, "s": 670, "text": null }, { "code": null, "e": 809, "s": 801, "text": "Output:" }, { "code": null, "e": 840, "s": 809, "text": "(0, 1, 2, 3, 'python', 'geek')" }, { "code": null, "e": 860, "s": 842, "text": "Nesting of Tuples" }, { "code": "# Code for creating nested tuples tuple1 = (0, 1, 2, 3)tuple2 = ('python', 'geek')tuple3 = (tuple1, tuple2)print(tuple3)", "e": 981, "s": 860, "text": null }, { "code": null, "e": 990, "s": 981, "text": "Output :" }, { "code": null, "e": 1025, "s": 990, "text": "((0, 1, 2, 3), ('python', 'geek'))" }, { "code": null, "e": 1048, "s": 1027, "text": "Repetition in Tuples" }, { "code": "# Code to create a tuple with repetition tuple3 = ('python',)*3print(tuple3)", "e": 1125, "s": 1048, "text": null }, { "code": null, "e": 1132, "s": 1125, "text": "Output" }, { "code": null, "e": 1164, "s": 1132, "text": " ('python', 'python', 'python')" }, { "code": null, "e": 1259, "s": 1164, "text": "Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’." }, { "code": null, "e": 1278, "s": 1261, "text": "Immutable Tuples" }, { "code": "#code to test that tuples are immutable tuple1 = (0, 1, 2, 3)tuple1[0] = 4print(tuple1)", "e": 1366, "s": 1278, "text": null }, { "code": null, "e": 1373, "s": 1366, "text": "Output" }, { "code": null, "e": 1540, "s": 1373, "text": "Traceback (most recent call last):\n File \"e0eaddff843a8695575daec34506f126.py\", line 3, in\n tuple1[0]=4\nTypeError: 'tuple' object does not support item assignment" }, { "code": null, "e": 1560, "s": 1542, "text": "Slicing in Tuples" }, { "code": "# code to test slicing tuple1 = (0 ,1, 2, 3)print(tuple1[1:])print(tuple1[::-1])print(tuple1[2:4])", "e": 1659, "s": 1560, "text": null }, { "code": null, "e": 1666, "s": 1659, "text": "Output" }, { "code": null, "e": 1696, "s": 1666, "text": "(1, 2, 3)\n(3, 2, 1, 0)\n(2, 3)" }, { "code": null, "e": 1715, "s": 1698, "text": "Deleting a Tuple" }, { "code": "# Code for deleting a tuple tuple3 = ( 0, 1)del tuple3print(tuple3)", "e": 1783, "s": 1715, "text": null }, { "code": null, "e": 1790, "s": 1783, "text": "Error:" }, { "code": null, "e": 1949, "s": 1790, "text": "Traceback (most recent call last):\n File \"d92694727db1dc9118a5250bf04dafbd.py\", line 6, in <module>\n print(tuple3)\nNameError: name 'tuple3' is not defined" }, { "code": null, "e": 1957, "s": 1949, "text": "Output:" }, { "code": null, "e": 1964, "s": 1957, "text": "(0, 1)" }, { "code": null, "e": 1992, "s": 1966, "text": "Finding Length of a Tuple" }, { "code": "# Code for printing the length of a tuple tuple2 = ('python', 'geek')print(len(tuple2))", "e": 2080, "s": 1992, "text": null }, { "code": null, "e": 2087, "s": 2080, "text": "Output" }, { "code": null, "e": 2090, "s": 2087, "text": " 2" }, { "code": null, "e": 2119, "s": 2092, "text": "Converting list to a Tuple" }, { "code": "# Code for converting a list and a string into a tuple list1 = [0, 1, 2]print(tuple(list1))print(tuple('python')) # string 'python'", "e": 2251, "s": 2119, "text": null }, { "code": null, "e": 2258, "s": 2251, "text": "Output" }, { "code": null, "e": 2299, "s": 2258, "text": "(0, 1, 2)\n('p', 'y', 't', 'h', 'o', 'n')" }, { "code": null, "e": 2440, "s": 2299, "text": "Takes a single parameter which may be a list,string,set or even a dictionary( only keys are taken as elements) and converts them to a tuple." }, { "code": null, "e": 2459, "s": 2442, "text": "Tuples in a loop" }, { "code": "#python code for creating tuples in a loop tup = ('geek',)n = 5 #Number of time loop runsfor i in range(int(n)): tup = (tup,) print(tup)", "e": 2603, "s": 2459, "text": null }, { "code": null, "e": 2612, "s": 2603, "text": "Output :" }, { "code": null, "e": 2708, "s": 2612, "text": "(('geek',),)\n((('geek',),),)\n(((('geek',),),),)\n((((('geek',),),),),)\n(((((('geek',),),),),),)\n" }, { "code": null, "e": 2737, "s": 2710, "text": "Using cmp(), max() , min()" }, { "code": "# A python program to demonstrate the use of# cmp(), max(), min() tuple1 = ('python', 'geek')tuple2 = ('coder', 1) if (cmp(tuple1, tuple2) != 0): # cmp() returns 0 if matched, 1 when not tuple1 # is longer and -1 when tuple1 is shorter print('Not the same')else: print('Same')print ('Maximum element in tuples 1,2: ' + str(max(tuple1)) + ',' + str(max(tuple2)))print ('Minimum element in tuples 1,2: ' + str(min(tuple1)) + ',' + str(min(tuple2)))", "e": 3217, "s": 2737, "text": null }, { "code": null, "e": 3224, "s": 3217, "text": "Output" }, { "code": null, "e": 3320, "s": 3224, "text": "Not the same\nMaximum element in tuples 1,2: python,coder\nMinimum element in tuples 1,2: geek,1\n" }, { "code": null, "e": 3476, "s": 3320, "text": "Note: max() and min() checks the based on ASCII values. If there are two strings in a tuple, then the first different character in the strings are checked." }, { "code": null, "e": 3656, "s": 3476, "text": "This article is contributed by Sri Sanketh Uppalapati. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3669, "s": 3656, "text": "simmytarika5" }, { "code": null, "e": 3682, "s": 3669, "text": "python-tuple" }, { "code": null, "e": 3689, "s": 3682, "text": "Python" }, { "code": null, "e": 3708, "s": 3689, "text": "School Programming" } ]
Java Program to Get the File Extension
22 Oct, 2021 The extension of a file is the last part of its name after the period (.). For example, the Java source file extension is “java”, and you will notice that the file name always ends with “.java”. Getting the file extension in Java is done using the File class of Java, i.e., probeContentType() method. The File class is Java’s representation of a file or directory pathname. The File class contains several processes for working with the pathname, deleting and renaming files, creating new directories, listing the directory contents, and determining several common attributes of files and directories. The probeContentType() is a method that comes predefined in the Java File class. The parameter to this method is passed the path of the file. Parameters: A path of the file. Return value: It returns a string(extension). Syntax: In Java, we can get the filename by – File file = new File("/home/mayur/GFG.java"); String fileName = file.getName(); fileType = Files.probeContentType(f.toPath()); Below is the implementation of the problem statement: Java // Java Program to Get the File Extension import java.io.*;import java.nio.file.Files; public class GFG { public static void main(String[] args) { // File location File f = new File("/home/mayur/GFG.java"); // If file exists if (f.exists()) { String fileType = "Undetermined"; String fileName = f.getName(); String extension = ""; int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); } try { fileType = Files.probeContentType(f.toPath()); } catch (IOException ioException) { System.out.println( "Cannot determine file type of " + f.getName() + " due to following exception: " + ioException); } // Print Extension System.out.println( "Extension used for file is -> " + extension + " and is probably " + fileType); } else { System.out.println("File does not exist!"); } }} Output: In the above example, file.getName() – Returns the file’s name and store it in a String variable. fileName.lastIndexOf(‘.’) – Returns the last occurrence of character. Since all file extension starts with ‘.’, we use the character ‘.’. fileName.substring() – Returns the string after character ‘.’. nishkarshgandhi Java-File Class Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Oct, 2021" }, { "code": null, "e": 655, "s": 53, "text": "The extension of a file is the last part of its name after the period (.). For example, the Java source file extension is “java”, and you will notice that the file name always ends with “.java”. Getting the file extension in Java is done using the File class of Java, i.e., probeContentType() method. The File class is Java’s representation of a file or directory pathname. The File class contains several processes for working with the pathname, deleting and renaming files, creating new directories, listing the directory contents, and determining several common attributes of files and directories." }, { "code": null, "e": 797, "s": 655, "text": "The probeContentType() is a method that comes predefined in the Java File class. The parameter to this method is passed the path of the file." }, { "code": null, "e": 829, "s": 797, "text": "Parameters: A path of the file." }, { "code": null, "e": 875, "s": 829, "text": "Return value: It returns a string(extension)." }, { "code": null, "e": 922, "s": 875, "text": "Syntax: In Java, we can get the filename by – " }, { "code": null, "e": 1050, "s": 922, "text": "File file = new File(\"/home/mayur/GFG.java\");\nString fileName = file.getName();\n\nfileType = Files.probeContentType(f.toPath());" }, { "code": null, "e": 1105, "s": 1050, "text": "Below is the implementation of the problem statement: " }, { "code": null, "e": 1110, "s": 1105, "text": "Java" }, { "code": "// Java Program to Get the File Extension import java.io.*;import java.nio.file.Files; public class GFG { public static void main(String[] args) { // File location File f = new File(\"/home/mayur/GFG.java\"); // If file exists if (f.exists()) { String fileType = \"Undetermined\"; String fileName = f.getName(); String extension = \"\"; int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); } try { fileType = Files.probeContentType(f.toPath()); } catch (IOException ioException) { System.out.println( \"Cannot determine file type of \" + f.getName() + \" due to following exception: \" + ioException); } // Print Extension System.out.println( \"Extension used for file is -> \" + extension + \" and is probably \" + fileType); } else { System.out.println(\"File does not exist!\"); } }}", "e": 2294, "s": 1110, "text": null }, { "code": null, "e": 2303, "s": 2294, "text": "Output: " }, { "code": null, "e": 2325, "s": 2303, "text": "In the above example," }, { "code": null, "e": 2401, "s": 2325, "text": "file.getName() – Returns the file’s name and store it in a String variable." }, { "code": null, "e": 2539, "s": 2401, "text": "fileName.lastIndexOf(‘.’) – Returns the last occurrence of character. Since all file extension starts with ‘.’, we use the character ‘.’." }, { "code": null, "e": 2602, "s": 2539, "text": "fileName.substring() – Returns the string after character ‘.’." }, { "code": null, "e": 2618, "s": 2602, "text": "nishkarshgandhi" }, { "code": null, "e": 2634, "s": 2618, "text": "Java-File Class" }, { "code": null, "e": 2641, "s": 2634, "text": "Picked" }, { "code": null, "e": 2665, "s": 2641, "text": "Technical Scripter 2020" }, { "code": null, "e": 2670, "s": 2665, "text": "Java" }, { "code": null, "e": 2684, "s": 2670, "text": "Java Programs" }, { "code": null, "e": 2703, "s": 2684, "text": "Technical Scripter" }, { "code": null, "e": 2708, "s": 2703, "text": "Java" } ]
PostgreSQL – Timestamp Data Type
24 Jan, 2022 In PostgreSQL 2 temporal data types namely timestamp and timestamptz where one is without timezone and the later is with timezone respectively, are supported to store Time and Date to a column. Both timestamp and timestamptz uses 8 bytes for storing timestamp values. Syntax: TIMESTAMP; or TIMESTAMPTZ; Now let’s look into some example for better understanding. Example 1: First we create a table that has both timestamp and timestamptz columns using the below command: CREATE TABLE timestamp_demo (ts TIMESTAMP, tstz TIMESTAMPTZ); Then we will set the time zone of database server to Asia/Calcutta as below: SET timezone = 'Asia/Calcutta'; Now that our time zone is set, we will insert a new row into the timestamp_demo table using the below command: INSERT INTO timestamp_demo (ts, tstz) VALUES ( '2020-06-22 19:10:25-07', '2020-06-22 19:10:25-07' ); Now we will query data from the timestamp and timestamptz columns using the below command: SELECT ts, tstz FROM timestamp_demo; Output: Example 2: In this example we will convert Asia/Calcutta timezone into America/New_York timezone using the timezone(zone, timestamp) function. First we create a table that has both timestamp and timestamptz columns using the below command: CREATE TABLE timezone_conversion_demo ( tstz TIMESTAMPTZ); Then we will set the time zone of database server to Asia/Calcutta as below: SET timezone = 'Asia/Calcutta'; Now that our time zone is set, we will insert a new row into the timezone_conversion_demo table using the below command: INSERT INTO timezone_conversion_demo ( tstz) VALUES ( '2020-06-22 19:10:25-07' ); Now we will query data from the timestamp and timestamptz columns using the below command: SELECT timezone('America/New_York', '2020-06-22 19:10:25'); Output: sooda367 saurabh1990aror postgreSQL-dataTypes PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2022" }, { "code": null, "e": 297, "s": 28, "text": "In PostgreSQL 2 temporal data types namely timestamp and timestamptz where one is without timezone and the later is with timezone respectively, are supported to store Time and Date to a column. Both timestamp and timestamptz uses 8 bytes for storing timestamp values. " }, { "code": null, "e": 334, "s": 299, "text": "Syntax: TIMESTAMP; or TIMESTAMPTZ;" }, { "code": null, "e": 503, "s": 334, "text": "Now let’s look into some example for better understanding. Example 1: First we create a table that has both timestamp and timestamptz columns using the below command: " }, { "code": null, "e": 565, "s": 503, "text": "CREATE TABLE timestamp_demo (ts TIMESTAMP, tstz TIMESTAMPTZ);" }, { "code": null, "e": 644, "s": 565, "text": "Then we will set the time zone of database server to Asia/Calcutta as below: " }, { "code": null, "e": 676, "s": 644, "text": "SET timezone = 'Asia/Calcutta';" }, { "code": null, "e": 789, "s": 676, "text": "Now that our time zone is set, we will insert a new row into the timestamp_demo table using the below command: " }, { "code": null, "e": 914, "s": 789, "text": "INSERT INTO timestamp_demo (ts, tstz)\nVALUES\n (\n '2020-06-22 19:10:25-07',\n '2020-06-22 19:10:25-07'\n );" }, { "code": null, "e": 1007, "s": 914, "text": "Now we will query data from the timestamp and timestamptz columns using the below command: " }, { "code": null, "e": 1052, "s": 1007, "text": "SELECT\n ts, tstz\nFROM\n timestamp_demo;" }, { "code": null, "e": 1062, "s": 1052, "text": "Output: " }, { "code": null, "e": 1304, "s": 1062, "text": "Example 2: In this example we will convert Asia/Calcutta timezone into America/New_York timezone using the timezone(zone, timestamp) function. First we create a table that has both timestamp and timestamptz columns using the below command: " }, { "code": null, "e": 1363, "s": 1304, "text": "CREATE TABLE timezone_conversion_demo ( tstz TIMESTAMPTZ);" }, { "code": null, "e": 1442, "s": 1363, "text": "Then we will set the time zone of database server to Asia/Calcutta as below: " }, { "code": null, "e": 1474, "s": 1442, "text": "SET timezone = 'Asia/Calcutta';" }, { "code": null, "e": 1597, "s": 1474, "text": "Now that our time zone is set, we will insert a new row into the timezone_conversion_demo table using the below command: " }, { "code": null, "e": 1704, "s": 1597, "text": "INSERT INTO timezone_conversion_demo ( tstz)\nVALUES\n (\n \n '2020-06-22 19:10:25-07'\n );" }, { "code": null, "e": 1797, "s": 1704, "text": "Now we will query data from the timestamp and timestamptz columns using the below command: " }, { "code": null, "e": 1857, "s": 1797, "text": "SELECT timezone('America/New_York', '2020-06-22 19:10:25');" }, { "code": null, "e": 1867, "s": 1857, "text": "Output: " }, { "code": null, "e": 1878, "s": 1869, "text": "sooda367" }, { "code": null, "e": 1894, "s": 1878, "text": "saurabh1990aror" }, { "code": null, "e": 1915, "s": 1894, "text": "postgreSQL-dataTypes" }, { "code": null, "e": 1926, "s": 1915, "text": "PostgreSQL" } ]
Prototype - toArray() Method
This method splits the string character-by-character and returns an array with the result. string.toArray() ; Returns an array of characters. <html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"> </script> <script> function showResult() { var str = "a"; alert("a.toArray() : " + str.toArray()[0] ); var str = "hello world!"; var arr = str.toArray(); arr.each(function(alpha) { alert(alpha); }); } </script> </head> <body> <p>Click the button to see the result.</p> <br /> <br /> <input type = "button" value = "Result" onclick = "showResult();"/> </body> </html> Click the button to see the result. 127 Lectures 11.5 hours Aleksandar Cucukovic Print Add Notes Bookmark this page
[ { "code": null, "e": 2152, "s": 2061, "text": "This method splits the string character-by-character and returns an array with the result." }, { "code": null, "e": 2172, "s": 2152, "text": "string.toArray() ;\n" }, { "code": null, "e": 2204, "s": 2172, "text": "Returns an array of characters." }, { "code": null, "e": 2872, "s": 2204, "text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"> </script>\n \n <script>\n function showResult() {\n var str = \"a\";\n alert(\"a.toArray() : \" + str.toArray()[0] );\n \n var str = \"hello world!\";\n var arr = str.toArray();\n arr.each(function(alpha) {\n alert(alpha);\n });\n }\n </script>\n </head>\n\n <body>\n <p>Click the button to see the result.</p>\n <br />\n <br />\n <input type = \"button\" value = \"Result\" onclick = \"showResult();\"/>\n </body>\n</html>" }, { "code": null, "e": 2908, "s": 2872, "text": "Click the button to see the result." }, { "code": null, "e": 2945, "s": 2908, "text": "\n 127 Lectures \n 11.5 hours \n" }, { "code": null, "e": 2967, "s": 2945, "text": " Aleksandar Cucukovic" }, { "code": null, "e": 2974, "s": 2967, "text": " Print" }, { "code": null, "e": 2985, "s": 2974, "text": " Add Notes" } ]
How to use trim () in Android textview?
This example demonstrate about How to use trim () in Android textview. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter name" android:layout_height="wrap_content" /> <Button android:id="@+id/click" android:text="Click" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:textSize="25sp" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken name as Edit text, when user click on button it will take data and trim the data without spaces. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText name; Button button; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = findViewById(R.id.name); button = findViewById(R.id.click); text = findViewById(R.id.textview); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { if (name.getText().toString().length() >= 0) { String trim = name.getText().toString().trim(); text.setText(String.valueOf(trim)); } } else { name.setError("Plz enter name"); } } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, enter the string as “ krishna ” and it returned krishna without spaces. Click here to download the project code
[ { "code": null, "e": 1133, "s": 1062, "text": "This example demonstrate about How to use trim () in Android textview." }, { "code": null, "e": 1262, "s": 1133, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1327, "s": 1262, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2217, "s": 1327, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2347, "s": 2217, "text": "In the above code, we have taken name as Edit text, when user click on button it will take data and trim the data without spaces." }, { "code": null, "e": 2404, "s": 2347, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3505, "s": 2404, "text": "package com.example.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n String trim = name.getText().toString().trim();\n text.setText(String.valueOf(trim));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 3852, "s": 3505, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3945, "s": 3852, "text": "In the above result, enter the string as “ krishna ” and it returned krishna without spaces." }, { "code": null, "e": 3985, "s": 3945, "text": "Click here to download the project code" } ]
How to refresh a webpage using Python Selenium Webdriver?
We can refresh a webpage using Selenium webdriver in Python. This can be done with the help of the refresh method. First of all, we have to launch the application with the get method. Once a web page is loaded completely, we can then refresh the page with the help of the refresh method. This way the existing page gets refreshed. The refresh method is to be applied on the webdriver object. driver.get("https://www.tutorialspoint.com/tutor_connect/index.php") driver.refresh() from selenium import webdriver #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) #launch URL driver.get("https://www.google.com/") #identify text box m = driver.find_element_by_class_name("gLFyf") #send input m.send_keys("Java") #refresh page driver.refresh()
[ { "code": null, "e": 1246, "s": 1062, "text": "We can refresh a webpage using Selenium webdriver in Python. This can be done with the help of the refresh method. First of all, we have to launch the application with the get method." }, { "code": null, "e": 1454, "s": 1246, "text": "Once a web page is loaded completely, we can then refresh the page with the help of the refresh method. This way the existing page gets refreshed. The refresh method is to be applied on the webdriver object." }, { "code": null, "e": 1540, "s": 1454, "text": "driver.get(\"https://www.tutorialspoint.com/tutor_connect/index.php\")\ndriver.refresh()" }, { "code": null, "e": 1871, "s": 1540, "text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://www.google.com/\")\n#identify text box\nm = driver.find_element_by_class_name(\"gLFyf\")\n#send input\nm.send_keys(\"Java\")\n#refresh page\ndriver.refresh()" } ]
PHP - session_reset() Function
Sessions or session handling is a way to make the data available across various pages of a web application. The session_reset() function re-initializes the variables of a session with original values. session_reset(); This function does not accept any parameters. This function returns a boolean value which is TRUE if the session started successfully and FALSE if not. This function was first introduced in PHP Version 4 and works in all the later versions. Following example demonstrates the usage of the session_reset() function. <html> <head> <title>Setting up a PHP session</title> </head> <body> <?php //Starting the session session_start(); //Initializing the session array $_SESSION["A"] = "Hello"; print("Initial value: ".$_SESSION["A"]); echo "<br>"; ?> </body> </html> One executing the above html file it will display the following message − Initial value: Hello Then you need to execute the following file. <html> <head> <title>Setting up a PHP session</title> </head> <body> <?php //Starting a session session_start(); //Replacing the old value $_SESSION["A"] = "Welcome"; print("New value: ".$_SESSION["A"]); echo "<br>"; session_reset(); print("Value after the reset operation: ".$_SESSION["A"]); ?> </body> </html> This generates the following output. New value: Welcome Value after the reset operation: Hello Following is another example of this function, in here we have two pages from the same application in the same session − session_page1.htm <?php if(isset($_POST['SubmitButton'])){ //Starting the session session_start(); $_SESSION['name'] = $_POST['name']; $_SESSION['age'] = $_POST['age']; } ?> <html> <body> <form action="#" method="post"> <br> <label for="fname">Enter the values click Submit and click on Next</label> <br><br><label for="fname">Name:</label> <input type="text" id="name" name="name"><br><br> <label for="lname">Age:</label> <input type="text" id="age" name="age"><br><br> <input type="submit" name="SubmitButton"/> <?php echo '<br><br /><a href="session_page2.htm">Next</a>'; ?> </form> </body> </html> This will produce the following output − On clicking on Next the following file is executed. session_page2.htm <html> <head> <title>Second Page</title> </head> <body> <?php //Session started session_start(); print($_SESSION['name']); echo "<br>"; print($_SESSION['age']); ?> </body> </html> This will produce the following output − Radha 22 Values after the reset operation: krishna 30 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2958, "s": 2757, "text": "Sessions or session handling is a way to make the data available across various pages of a web application. The session_reset() function re-initializes the variables of a session with original values." }, { "code": null, "e": 2976, "s": 2958, "text": "session_reset();\n" }, { "code": null, "e": 3022, "s": 2976, "text": "This function does not accept any parameters." }, { "code": null, "e": 3128, "s": 3022, "text": "This function returns a boolean value which is TRUE if the session started successfully and FALSE if not." }, { "code": null, "e": 3217, "s": 3128, "text": "This function was first introduced in PHP Version 4 and works in all the later versions." }, { "code": null, "e": 3291, "s": 3217, "text": "Following example demonstrates the usage of the session_reset() function." }, { "code": null, "e": 3635, "s": 3291, "text": "<html> \n <head>\n <title>Setting up a PHP session</title>\n </head> \n <body>\n <?php\n //Starting the session\n session_start();\n //Initializing the session array\n $_SESSION[\"A\"] = \"Hello\";\n print(\"Initial value: \".$_SESSION[\"A\"]);\n echo \"<br>\";\t\t \n ?>\n </body> \n</html> " }, { "code": null, "e": 3709, "s": 3635, "text": "One executing the above html file it will display the following message −" }, { "code": null, "e": 3731, "s": 3709, "text": "Initial value: Hello\n" }, { "code": null, "e": 3776, "s": 3731, "text": "Then you need to execute the following file." }, { "code": null, "e": 4224, "s": 3776, "text": "<html> \n <head>\n <title>Setting up a PHP session</title>\n </head> \n <body>\n <?php \t\n //Starting a session\t \n session_start(); \n \n //Replacing the old value\n $_SESSION[\"A\"] = \"Welcome\"; \n print(\"New value: \".$_SESSION[\"A\"]);\n echo \"<br>\";\t\t \n session_reset(); \n print(\"Value after the reset operation: \".$_SESSION[\"A\"]);\n ?>\n </body> \n</html>" }, { "code": null, "e": 4261, "s": 4224, "text": "This generates the following output." }, { "code": null, "e": 4320, "s": 4261, "text": "New value: Welcome\nValue after the reset operation: Hello\n" }, { "code": null, "e": 4441, "s": 4320, "text": "Following is another example of this function, in here we have two pages from the same application in the same session −" }, { "code": null, "e": 4459, "s": 4441, "text": "session_page1.htm" }, { "code": null, "e": 5177, "s": 4459, "text": "<?php\n if(isset($_POST['SubmitButton'])){ \n //Starting the session\t\n session_start();\n $_SESSION['name'] = $_POST['name'];\n $_SESSION['age'] = $_POST['age'];\n }\n?>\n<html>\n <body>\n <form action=\"#\" method=\"post\">\n <br>\n <label for=\"fname\">Enter the values click Submit and click on Next</label>\n <br><br><label for=\"fname\">Name:</label>\n <input type=\"text\" id=\"name\" name=\"name\"><br><br>\n <label for=\"lname\">Age:</label>\n <input type=\"text\" id=\"age\" name=\"age\"><br><br> \n <input type=\"submit\" name=\"SubmitButton\"/>\n <?php echo '<br><br /><a href=\"session_page2.htm\">Next</a>'; ?>\n </form>\n </body>\n</html>" }, { "code": null, "e": 5218, "s": 5177, "text": "This will produce the following output −" }, { "code": null, "e": 5270, "s": 5218, "text": "On clicking on Next the following file is executed." }, { "code": null, "e": 5288, "s": 5270, "text": "session_page2.htm" }, { "code": null, "e": 5554, "s": 5288, "text": "<html> \n <head>\n <title>Second Page</title>\n </head>\n <body>\n <?php\n //Session started\n session_start();\n print($_SESSION['name']); \n echo \"<br>\";\n print($_SESSION['age']);\n ?> \n </body> \n</html>\n" }, { "code": null, "e": 5595, "s": 5554, "text": "This will produce the following output −" }, { "code": null, "e": 5651, "s": 5595, "text": "Radha\n22\nValues after the reset operation:\nkrishna\n30 \n" }, { "code": null, "e": 5684, "s": 5651, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5700, "s": 5684, "text": " Malhar Lathkar" }, { "code": null, "e": 5733, "s": 5700, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5744, "s": 5733, "text": " Syed Raza" }, { "code": null, "e": 5779, "s": 5744, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5796, "s": 5779, "text": " Frahaan Hussain" }, { "code": null, "e": 5829, "s": 5796, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5844, "s": 5829, "text": " Nivedita Jain" }, { "code": null, "e": 5879, "s": 5844, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5891, "s": 5879, "text": " Azaz Patel" }, { "code": null, "e": 5926, "s": 5891, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5954, "s": 5926, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5961, "s": 5954, "text": " Print" }, { "code": null, "e": 5972, "s": 5961, "text": " Add Notes" } ]
eval - Unix, Linux Command
eval - Eval is a built in linux or unix command. eval [arg ..] eval is a built in linux or unix command. The eval command is used to execute the arguments as a shell command on unix or linux system. Eval command comes in handy when you have a unix or linux command stored in a variable and you want to execute that command stored in the string. The eval command first evaluates the argument and then runs the command stored in the argument. Example-1: To execute that command stored in the string: $ COMMAND="ls -lrt" $ eval $COMMAND output: total 16 -rw-rw-r-- 1 user group 11 Oct 4 01:06 sample.sh-rw-rw-r-- 1 user group 0 Oct 4 01:06 test.bat -rw-rw-r-- 1 user group 0 Oct 4 01:06 xyz_ip Example-2: To print the value of variable which is again variable with value assigned to it $ a=10 $ b=a $ c='$'$b ( note: The dollar sign must be escaped with '$') $ echo $c output: $a $ eval c='$'$b $ echo $c output: 10 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10626, "s": 10577, "text": "eval - Eval is a built in linux or unix command." }, { "code": null, "e": 10640, "s": 10626, "text": "eval [arg ..]" }, { "code": null, "e": 11018, "s": 10640, "text": "eval is a built in linux or unix command. The eval command is used to execute the arguments as a shell command on unix or linux system. Eval command comes in handy when you have a unix or linux command stored in a variable and you want to execute that command stored in the string. The eval command first evaluates the argument and then runs the command stored in the argument." }, { "code": null, "e": 11029, "s": 11018, "text": "Example-1:" }, { "code": null, "e": 11075, "s": 11029, "text": "To execute that command stored in the string:" }, { "code": null, "e": 11095, "s": 11075, "text": "$ COMMAND=\"ls -lrt\"" }, { "code": null, "e": 11111, "s": 11095, "text": "$ eval $COMMAND" }, { "code": null, "e": 11121, "s": 11111, "text": " output: " }, { "code": null, "e": 11278, "s": 11121, "text": "total 16\n-rw-rw-r-- 1 user group 11 Oct 4 01:06 sample.sh-rw-rw-r-- 1 user group 0 Oct 4 01:06 test.bat\n-rw-rw-r-- 1 user group 0 Oct 4 01:06 xyz_ip" }, { "code": null, "e": 11289, "s": 11278, "text": "Example-2:" }, { "code": null, "e": 11370, "s": 11289, "text": "To print the value of variable which is again variable with value assigned to it" }, { "code": null, "e": 11377, "s": 11370, "text": "$ a=10" }, { "code": null, "e": 11383, "s": 11377, "text": "$ b=a" }, { "code": null, "e": 11443, "s": 11383, "text": "$ c='$'$b ( note: The dollar sign must be escaped with '$')" }, { "code": null, "e": 11453, "s": 11443, "text": "$ echo $c" }, { "code": null, "e": 11461, "s": 11453, "text": "output:" }, { "code": null, "e": 11464, "s": 11461, "text": "$a" }, { "code": null, "e": 11479, "s": 11464, "text": "$ eval c='$'$b" }, { "code": null, "e": 11489, "s": 11479, "text": "$ echo $c" }, { "code": null, "e": 11497, "s": 11489, "text": "output:" }, { "code": null, "e": 11500, "s": 11497, "text": "10" }, { "code": null, "e": 11535, "s": 11500, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11563, "s": 11535, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11597, "s": 11563, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11614, "s": 11597, "text": " Frahaan Hussain" }, { "code": null, "e": 11647, "s": 11614, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11658, "s": 11647, "text": " Pradeep D" }, { "code": null, "e": 11693, "s": 11658, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11709, "s": 11693, "text": " Musab Zayadneh" }, { "code": null, "e": 11742, "s": 11709, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11754, "s": 11742, "text": " GUHARAJANM" }, { "code": null, "e": 11786, "s": 11754, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11794, "s": 11786, "text": " Uplatz" }, { "code": null, "e": 11801, "s": 11794, "text": " Print" }, { "code": null, "e": 11812, "s": 11801, "text": " Add Notes" } ]
Transfer Learning in Action: From ImageNet to Tiny-ImageNet | by Thushan Ganegedara | Towards Data Science
Transfer learning is an important topic. As a civilization, we have been passing on the knowledge from one generation to the other, enabling the technological advancement that we enjoy today. It’s the edifice that supports most of the state-of-the-art models that are blowing steam, empowering many services that we take for granted. Transfer learning is about having a good starting point for the downstream task we’re interested in solving. In this article, we’re going to discuss how to piggyback on transfer learning to get a warm start to solve an image classification task. The content of this article is based on “TensorFlow 2 in Action” by Manning and on TensorFlow 2.2. Code for this exercise: Here. In this tutorial we’re going to cover, What is Transfer Learning? Understanding the dataset Learning the nitty-gritties of InceptionNet-Resnet-v2 Download a ImageNet pretrained InceptionNet-Resnet-v2 and use it to learn the classification task (Tiny-ImageNet) at hand quickly Transfer learning itself is a very simple yet powerful concept. It is about solving a bespoke task by leveraging the knowledge impregnated in a model that’s already good at solving a similar task. Following the long-standing tradition of “a picture worth a thousand words”, here’s a depiction of transfer learning process. For example, if you develop a segmentation model for self-driving cars and you use a pretrained image classification model to start with or, if you download BERT and build a spam classifier on top of features provided by BERT, that is essentially transfer learning. However to understand the idiosyncratic methods that enables us achieve transfer learning will take time. Different ways you achieve transfer learning through, will have different advantages or effects. If you are interested, here’s a good guide/portfolio of different methods. The dataset we’re going to use is Tiny-ImageNet. It is a smaller version derived from the monolith ImageNet challenge. The dataset is pretty straight-forward. There’s 100,000 training and 10,000 validation (will be used as the testing data) samples. Then each record has, A RGB image of size 64x64x3 A label indicating the object present in the image Here’s a few examples from the dataset. I’m going to skim through the details of data extraction. However, if you are interested in the details, please refer the code. To feed this data we will first download the dataset (the code is provided). It has two datasets; training data and testing data. We will split the train dataset to two subsets, Training data Validation data Note that the testing data is called “validation” data when you download it, as the Tiny-ImageNet has an undisclosed test dataset that. But we’re going to consider that as the test set. First we will define two tensorflow.keras.preprocessing.image.ImageDataGenerator objects. # For train and validation dataimage_gen_aug = ImageDataGenerator( samplewise_center=False, rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, brightness_range=(0.5,1.5), shear_range=5, zoom_range=0.2, horizontal_flip=True, fill_mode='reflect', validation_split=0.1 )# For the testing data (No augmentation)image_gen = ImageDataGenerator(samplewise_center=False) We’re going to augment the training data so that we can reach a higher accuracy than using the original data as it is. Data augmentation is when you create different variants of your inputs (e.g. change brightness/contrast, translate, rotate, etc.) so that you generate more data for your model. You can learn more about data augmentation in Chapter 7 of TensorFlow 2 in Action by Manning. Another important observation is how we use the validation_split argument to take out a chunk of data (10%) as validation data. Then we are going to use, # Get training data generatortrain_gen = image_gen_aug.flow_from_directory(..., subset='training')# Get valid data generatorvalid_gen = image_gen_aug.flow_from_directory(..., subset='validation')# Get test data generatortest_gen = image_gen.flow_from_dataframe(...) to obtain three data generators (i.e. Python generators); training, validation and testing data generators. Note how samplewise_center is set to False. It is a normalization step that is commonly used for image process. I’ve set it to False because I’m going to introduce few more custom augmentation steps as follows. def data_gen_augmented(gen, random_gamma=False, random_occlude=False): for x,y in gen: if random_gamma: # Gamma correction # Doing this in the image process fn doesn't help improve performance rand_gamma = np.random.uniform(0.9, 1.08, (x.shape[0],1,1,1)) x = x**rand_gamma if random_occlude: # Randomly occluding sections in the image occ_size = 10 occ_h, occ_w = np.random.randint(0, x.shape[0]-occ_size), np.random.randint(0, x.shape[0]-occ_size) x[::2,occ_h:occ_h+occ_size,occ_w:occ_w+occ_size,:] = np.random.choice([0.,128.,255.]) # Image centering x -= np.mean(x, axis=(1,2,3), keepdims=True) # Making sure we replicate the target (y) three times yield x,(y,y,y) Basically, we do, Random Gamma correction Introduce random occlusions in the images Then samplewise_center is performed manually with the line, x -= np.mean(x, axis=(1,2,3), keepdims=True) in the above code. Finally, we define the data generators that uses both built-in data augmentation steps as well as the custom augmentation steps. train_gen_aux = data_gen_augmented_inception_resnet_v2(train_gen, random_gamma=True, random_occlude=True)# We do not augment data in the validation/test datasetsvalid_gen_aux = data_gen_augmented_inception_resnet_v2(valid_gen)test_gen_aux = data_gen_augmented_inception_resnet_v2(test_gen) These data generators will be used to fit the model once it’s defined. Again if you would like to see the full code related to data download and creating training/validation/testing data pipelines, refer to the code. At the first glance, Inception-Resnet-v2 architecture might look like the Pandora box. Because Inception-Resnet-v2 evolved to become what it is, while going through many iterations. Specifically, Inception net has the following models. Inception-Net-v1 (Paper) Inception-Net-v2 (Paper) Inception-Net-v3 (Paper) Inception-Net-v4 (Paper) Inception-Resnet-v1 (Paper) Inception-Resnet-v2 (Paper) Xception (Paper) If you would like more information about these different models, the motivation behind the design principles they are built upon, read Chapter 6 of TensorFlow 2 in Action by Manning. The Inception-Resnet-v2 model has the following building blocks. A stem (White) — Stem stands as the back bone of the image classification model. It is followed by several repeated convolution blocks and then a prediction layer. Inception Resnet blocks (Type A/B) (Red) — These is the most notable contribution of Inception Resnet-v2. These blocks uses multiple streams of convolution paths as well as residual connections. Reduction blocks (Green) — Primary purpose of these blocks is to reduce the height and width dimensions in a controlled fashion. Final prediction layer (Blue)— Outputs the probability distribution over the available classes for a given input/ batch of inputs. Now it’s important to understand that InceptionNet models are not just about a random configuration of a CNN that works! They are actually based on some strong foundational principles. Inception Net models are designed to make CNNs parameter efficient, without sacrificing performance too much Introducing sparsity (i.e. less parameters) within the CNN by using different kernel sizes in convolution layers Factorizing large convolution filters to smaller ones Using residual connections and batch normalization to make the model training smooth If you would like to learn these concepts in detail, Chapter 6 and 7 of “TensorFlow 2 in Action” by Manning goes into great lengths explaining these concepts. Here we’re going to download the pretrained Inception-Resnet-v2 model. You can download this model through the sub-API tensorflow.keras.applications . from tensorflow.keras.applications import InceptionResNetV2from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Input, Dense, DropoutK.clear_session()# We're going to download the InceptionResNetv2 model, remove the top layer and wrap it around an input layer and a prediction layer (with 200 classes)model = Sequential([ Input(shape=(224,224,3)), InceptionResNetV2(include_top=False, pooling='avg'), Dropout(0.4), Dense(200, activation='softmax')])# Defining the lossloss = tf.keras.losses.CategoricalCrossentropy()# Defining the optimizeradam = tf.keras.optimizers.Adam(learning_rate=0.0001)# Compiling the modelmodel.compile(loss=loss, optimizer=adam, metrics=['accuracy'])model.summary() Here, we are going to create a tf.keras.models.Model by wrapping, An Input layer having the size 224x224x3 the downloaded Inception Resnet v2 model (without the top prediction layer and an average pooling layer on top) A dropout layer with 40% dropout rate A final prediction layer Note that the input layer expects a 224x224x3 sized image. However the images we have are of size 64x64x3. To solve this problem, we can easily resize the images through the ImageDataGenerator. We’re also using a smaller learning rate (Adam has a default learning rate of 0.001). This is because a higher learning rate is unnecessary (as we’re not starting out with a random initialization) and can even corrupt the knowledge embedded in the model. Now the fun begins! We’re about to train the model. from tensorflow.keras.callbacks import EarlyStopping, CSVLogger, ReduceLROnPlateau# Defining callbackses_callback = EarlyStopping(monitor='val_loss', patience=10)csv_logger = CSVLogger(os.path.join('eval','4_eval_resnet_pretrained.log'))n_epochs=50lr_callback = ReduceLROnPlateau( monitor='val_loss', factor=0.1, patience=5, verbose=1, mode='auto')# Training the modelhistory = model.fit( train_gen_aux, validation_data=valid_gen_aux, steps_per_epoch=get_steps_per_epoch(int(0.9*(500*200)), batch_size), validation_steps=get_steps_per_epoch(int(0.1*(500*200)), batch_size), epochs=n_epochs, callbacks=[es_callback, csv_logger, lr_callback]) There’s a lot going on here. Let’s break things down and understand what’s going on here. First we are defining a bunch of callbacks. These callbacks, when passed to the model.fit(...) are called at the end of the epoch. For example, es_callback — Perform early stopping. For example in this example, it will monitor val_loss and if it has not gone down within 10 epochs, the training will stop. csv_logger — Logs the monitored metrics/loss to a CSV file lr_callback — Reduces the learning rate of the optimizer by a factor of 0.1 if the val_loss does not go down within 5 epochs. Finally, model.fit() is called with train_gen_aux as the training data, valid_gen as the validation data. The function get_steps_per_epochcomputes the number of steps given the size of the dataset and the batch size. And then we can evaluate the model on test data using, # Evaluate the modeltest_res = model.evaluate(test_gen_aux, steps=get_steps_per_epoch(500*50, batch_size)) If you run the training, you should get an output similar to the one below. Epoch 1/502813/2813 [==============================] - 1465s 521ms/step - loss: 2.0031 - accuracy: 0.5557 - val_loss: 1.5206 - val_accuracy: 0.6418Epoch 2/502813/2813 [==============================] - 1456s 517ms/step - loss: 1.3250 - accuracy: 0.6777 - val_loss: 1.4021 - val_accuracy: 0.6622...Epoch 23/502813/2813 [==============================] - ETA: 0s - loss: 0.1268 - accuracy: 0.9644Epoch 00023: ReduceLROnPlateau reducing learning rate to 9.999999974752428e-08.2813/2813 [==============================] - 1456s 518ms/step - loss: 0.1268 - accuracy: 0.9644 - val_loss: 1.2681 - val_accuracy: 0.7420 and on test data, 782/782 [==============================] - 84s 107ms/step - loss: 1.0672 - accuracy: 0.7874 The model has reached around ~75% accuracy on the validation data and ~78% on the test set. This accuracy is a very respectable accuracy compared to state of the art performance (which is around 85%). The content of this article is based on my latest upcoming book “TensorFlow 2 in Action” by Manning. Don’t be disheartened, if you don’t want to check the book out, the code for the book is available for free on Github and can be accessed here. Here’s how this compares to some of the other attempts discussed in the book. Specifically, inception-net-v1 data-aug + early-stop — An Inception Net v1 model (with data augmentation and early stopping) Minception-net — A modified version of Inception Resnet v2 (trained from the scratch) Inception-Resnet-v2 transfer-learn — Inception Resnet v2 model pretrained on ImageNet That was a very quick hands-on guide as to how you can use Transfer Learning with TensorFlow to quickly get a model up and running. Transfer Learning enables you to transfer the knowledge of a pretrained model for a downstream task you’re interested in solving. This can be really handy in some situations. For example, if you are working on a computer vision product you might save weeks or even months by starting out with a pretrained model. So this is a very important concept to be familiar with. In this guide we, Learned what Transfer Learning is Understood the dataset Learned the nitty-gritties of InceptionNet-Resnet-v2 Downloaded a ImageNet pretrained InceptionNet-Resnet-v2 Used the downloaded model to define a new model and solve the classification task (Tiny-ImageNet) at hand quickly If you would like to learn more about, Data augmentation and creating data pipelines in TensorFlow, Mechanics of convolution neural networks, Inception net models and various design principles behind them, Techniques like batch normalization, residual connections and, Using Transfer Learning for image classifcation, checkout Chapter 6 and 7 of “TensorFlow 2 in Action” by Manning (provided as an affiliate link). Happy learning! If you enjoy the stories I share about data science and machine learning, consider becoming a member!
[ { "code": null, "e": 506, "s": 172, "text": "Transfer learning is an important topic. As a civilization, we have been passing on the knowledge from one generation to the other, enabling the technological advancement that we enjoy today. It’s the edifice that supports most of the state-of-the-art models that are blowing steam, empowering many services that we take for granted." }, { "code": null, "e": 615, "s": 506, "text": "Transfer learning is about having a good starting point for the downstream task we’re interested in solving." }, { "code": null, "e": 851, "s": 615, "text": "In this article, we’re going to discuss how to piggyback on transfer learning to get a warm start to solve an image classification task. The content of this article is based on “TensorFlow 2 in Action” by Manning and on TensorFlow 2.2." }, { "code": null, "e": 881, "s": 851, "text": "Code for this exercise: Here." }, { "code": null, "e": 920, "s": 881, "text": "In this tutorial we’re going to cover," }, { "code": null, "e": 947, "s": 920, "text": "What is Transfer Learning?" }, { "code": null, "e": 973, "s": 947, "text": "Understanding the dataset" }, { "code": null, "e": 1027, "s": 973, "text": "Learning the nitty-gritties of InceptionNet-Resnet-v2" }, { "code": null, "e": 1157, "s": 1027, "text": "Download a ImageNet pretrained InceptionNet-Resnet-v2 and use it to learn the classification task (Tiny-ImageNet) at hand quickly" }, { "code": null, "e": 1480, "s": 1157, "text": "Transfer learning itself is a very simple yet powerful concept. It is about solving a bespoke task by leveraging the knowledge impregnated in a model that’s already good at solving a similar task. Following the long-standing tradition of “a picture worth a thousand words”, here’s a depiction of transfer learning process." }, { "code": null, "e": 1493, "s": 1480, "text": "For example," }, { "code": null, "e": 1621, "s": 1493, "text": "if you develop a segmentation model for self-driving cars and you use a pretrained image classification model to start with or," }, { "code": null, "e": 1707, "s": 1621, "text": "if you download BERT and build a spam classifier on top of features provided by BERT," }, { "code": null, "e": 2024, "s": 1707, "text": "that is essentially transfer learning. However to understand the idiosyncratic methods that enables us achieve transfer learning will take time. Different ways you achieve transfer learning through, will have different advantages or effects. If you are interested, here’s a good guide/portfolio of different methods." }, { "code": null, "e": 2296, "s": 2024, "text": "The dataset we’re going to use is Tiny-ImageNet. It is a smaller version derived from the monolith ImageNet challenge. The dataset is pretty straight-forward. There’s 100,000 training and 10,000 validation (will be used as the testing data) samples. Then each record has," }, { "code": null, "e": 2324, "s": 2296, "text": "A RGB image of size 64x64x3" }, { "code": null, "e": 2375, "s": 2324, "text": "A label indicating the object present in the image" }, { "code": null, "e": 2415, "s": 2375, "text": "Here’s a few examples from the dataset." }, { "code": null, "e": 2721, "s": 2415, "text": "I’m going to skim through the details of data extraction. However, if you are interested in the details, please refer the code. To feed this data we will first download the dataset (the code is provided). It has two datasets; training data and testing data. We will split the train dataset to two subsets," }, { "code": null, "e": 2735, "s": 2721, "text": "Training data" }, { "code": null, "e": 2751, "s": 2735, "text": "Validation data" }, { "code": null, "e": 3027, "s": 2751, "text": "Note that the testing data is called “validation” data when you download it, as the Tiny-ImageNet has an undisclosed test dataset that. But we’re going to consider that as the test set. First we will define two tensorflow.keras.preprocessing.image.ImageDataGenerator objects." }, { "code": null, "e": 3921, "s": 3027, "text": "# For train and validation dataimage_gen_aug = ImageDataGenerator( samplewise_center=False, rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, brightness_range=(0.5,1.5), shear_range=5, zoom_range=0.2, horizontal_flip=True, fill_mode='reflect', validation_split=0.1 )# For the testing data (No augmentation)image_gen = ImageDataGenerator(samplewise_center=False)" }, { "code": null, "e": 4465, "s": 3921, "text": "We’re going to augment the training data so that we can reach a higher accuracy than using the original data as it is. Data augmentation is when you create different variants of your inputs (e.g. change brightness/contrast, translate, rotate, etc.) so that you generate more data for your model. You can learn more about data augmentation in Chapter 7 of TensorFlow 2 in Action by Manning. Another important observation is how we use the validation_split argument to take out a chunk of data (10%) as validation data. Then we are going to use," }, { "code": null, "e": 4731, "s": 4465, "text": "# Get training data generatortrain_gen = image_gen_aug.flow_from_directory(..., subset='training')# Get valid data generatorvalid_gen = image_gen_aug.flow_from_directory(..., subset='validation')# Get test data generatortest_gen = image_gen.flow_from_dataframe(...)" }, { "code": null, "e": 5050, "s": 4731, "text": "to obtain three data generators (i.e. Python generators); training, validation and testing data generators. Note how samplewise_center is set to False. It is a normalization step that is commonly used for image process. I’ve set it to False because I’m going to introduce few more custom augmentation steps as follows." }, { "code": null, "e": 5880, "s": 5050, "text": "def data_gen_augmented(gen, random_gamma=False, random_occlude=False): for x,y in gen: if random_gamma: # Gamma correction # Doing this in the image process fn doesn't help improve performance rand_gamma = np.random.uniform(0.9, 1.08, (x.shape[0],1,1,1)) x = x**rand_gamma if random_occlude: # Randomly occluding sections in the image occ_size = 10 occ_h, occ_w = np.random.randint(0, x.shape[0]-occ_size), np.random.randint(0, x.shape[0]-occ_size) x[::2,occ_h:occ_h+occ_size,occ_w:occ_w+occ_size,:] = np.random.choice([0.,128.,255.]) # Image centering x -= np.mean(x, axis=(1,2,3), keepdims=True) # Making sure we replicate the target (y) three times yield x,(y,y,y)" }, { "code": null, "e": 5898, "s": 5880, "text": "Basically, we do," }, { "code": null, "e": 5922, "s": 5898, "text": "Random Gamma correction" }, { "code": null, "e": 5964, "s": 5922, "text": "Introduce random occlusions in the images" }, { "code": null, "e": 6024, "s": 5964, "text": "Then samplewise_center is performed manually with the line," }, { "code": null, "e": 6069, "s": 6024, "text": "x -= np.mean(x, axis=(1,2,3), keepdims=True)" }, { "code": null, "e": 6217, "s": 6069, "text": "in the above code. Finally, we define the data generators that uses both built-in data augmentation steps as well as the custom augmentation steps." }, { "code": null, "e": 6507, "s": 6217, "text": "train_gen_aux = data_gen_augmented_inception_resnet_v2(train_gen, random_gamma=True, random_occlude=True)# We do not augment data in the validation/test datasetsvalid_gen_aux = data_gen_augmented_inception_resnet_v2(valid_gen)test_gen_aux = data_gen_augmented_inception_resnet_v2(test_gen)" }, { "code": null, "e": 6724, "s": 6507, "text": "These data generators will be used to fit the model once it’s defined. Again if you would like to see the full code related to data download and creating training/validation/testing data pipelines, refer to the code." }, { "code": null, "e": 6960, "s": 6724, "text": "At the first glance, Inception-Resnet-v2 architecture might look like the Pandora box. Because Inception-Resnet-v2 evolved to become what it is, while going through many iterations. Specifically, Inception net has the following models." }, { "code": null, "e": 6985, "s": 6960, "text": "Inception-Net-v1 (Paper)" }, { "code": null, "e": 7010, "s": 6985, "text": "Inception-Net-v2 (Paper)" }, { "code": null, "e": 7035, "s": 7010, "text": "Inception-Net-v3 (Paper)" }, { "code": null, "e": 7060, "s": 7035, "text": "Inception-Net-v4 (Paper)" }, { "code": null, "e": 7088, "s": 7060, "text": "Inception-Resnet-v1 (Paper)" }, { "code": null, "e": 7116, "s": 7088, "text": "Inception-Resnet-v2 (Paper)" }, { "code": null, "e": 7133, "s": 7116, "text": "Xception (Paper)" }, { "code": null, "e": 7381, "s": 7133, "text": "If you would like more information about these different models, the motivation behind the design principles they are built upon, read Chapter 6 of TensorFlow 2 in Action by Manning. The Inception-Resnet-v2 model has the following building blocks." }, { "code": null, "e": 7545, "s": 7381, "text": "A stem (White) — Stem stands as the back bone of the image classification model. It is followed by several repeated convolution blocks and then a prediction layer." }, { "code": null, "e": 7740, "s": 7545, "text": "Inception Resnet blocks (Type A/B) (Red) — These is the most notable contribution of Inception Resnet-v2. These blocks uses multiple streams of convolution paths as well as residual connections." }, { "code": null, "e": 7869, "s": 7740, "text": "Reduction blocks (Green) — Primary purpose of these blocks is to reduce the height and width dimensions in a controlled fashion." }, { "code": null, "e": 8000, "s": 7869, "text": "Final prediction layer (Blue)— Outputs the probability distribution over the available classes for a given input/ batch of inputs." }, { "code": null, "e": 8185, "s": 8000, "text": "Now it’s important to understand that InceptionNet models are not just about a random configuration of a CNN that works! They are actually based on some strong foundational principles." }, { "code": null, "e": 8294, "s": 8185, "text": "Inception Net models are designed to make CNNs parameter efficient, without sacrificing performance too much" }, { "code": null, "e": 8407, "s": 8294, "text": "Introducing sparsity (i.e. less parameters) within the CNN by using different kernel sizes in convolution layers" }, { "code": null, "e": 8461, "s": 8407, "text": "Factorizing large convolution filters to smaller ones" }, { "code": null, "e": 8546, "s": 8461, "text": "Using residual connections and batch normalization to make the model training smooth" }, { "code": null, "e": 8705, "s": 8546, "text": "If you would like to learn these concepts in detail, Chapter 6 and 7 of “TensorFlow 2 in Action” by Manning goes into great lengths explaining these concepts." }, { "code": null, "e": 8856, "s": 8705, "text": "Here we’re going to download the pretrained Inception-Resnet-v2 model. You can download this model through the sub-API tensorflow.keras.applications ." }, { "code": null, "e": 9589, "s": 8856, "text": "from tensorflow.keras.applications import InceptionResNetV2from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Input, Dense, DropoutK.clear_session()# We're going to download the InceptionResNetv2 model, remove the top layer and wrap it around an input layer and a prediction layer (with 200 classes)model = Sequential([ Input(shape=(224,224,3)), InceptionResNetV2(include_top=False, pooling='avg'), Dropout(0.4), Dense(200, activation='softmax')])# Defining the lossloss = tf.keras.losses.CategoricalCrossentropy()# Defining the optimizeradam = tf.keras.optimizers.Adam(learning_rate=0.0001)# Compiling the modelmodel.compile(loss=loss, optimizer=adam, metrics=['accuracy'])model.summary()" }, { "code": null, "e": 9655, "s": 9589, "text": "Here, we are going to create a tf.keras.models.Model by wrapping," }, { "code": null, "e": 9696, "s": 9655, "text": "An Input layer having the size 224x224x3" }, { "code": null, "e": 9808, "s": 9696, "text": "the downloaded Inception Resnet v2 model (without the top prediction layer and an average pooling layer on top)" }, { "code": null, "e": 9846, "s": 9808, "text": "A dropout layer with 40% dropout rate" }, { "code": null, "e": 9871, "s": 9846, "text": "A final prediction layer" }, { "code": null, "e": 10320, "s": 9871, "text": "Note that the input layer expects a 224x224x3 sized image. However the images we have are of size 64x64x3. To solve this problem, we can easily resize the images through the ImageDataGenerator. We’re also using a smaller learning rate (Adam has a default learning rate of 0.001). This is because a higher learning rate is unnecessary (as we’re not starting out with a random initialization) and can even corrupt the knowledge embedded in the model." }, { "code": null, "e": 10372, "s": 10320, "text": "Now the fun begins! We’re about to train the model." }, { "code": null, "e": 11038, "s": 10372, "text": "from tensorflow.keras.callbacks import EarlyStopping, CSVLogger, ReduceLROnPlateau# Defining callbackses_callback = EarlyStopping(monitor='val_loss', patience=10)csv_logger = CSVLogger(os.path.join('eval','4_eval_resnet_pretrained.log'))n_epochs=50lr_callback = ReduceLROnPlateau( monitor='val_loss', factor=0.1, patience=5, verbose=1, mode='auto')# Training the modelhistory = model.fit( train_gen_aux, validation_data=valid_gen_aux, steps_per_epoch=get_steps_per_epoch(int(0.9*(500*200)), batch_size), validation_steps=get_steps_per_epoch(int(0.1*(500*200)), batch_size), epochs=n_epochs, callbacks=[es_callback, csv_logger, lr_callback])" }, { "code": null, "e": 11272, "s": 11038, "text": "There’s a lot going on here. Let’s break things down and understand what’s going on here. First we are defining a bunch of callbacks. These callbacks, when passed to the model.fit(...) are called at the end of the epoch. For example," }, { "code": null, "e": 11434, "s": 11272, "text": "es_callback — Perform early stopping. For example in this example, it will monitor val_loss and if it has not gone down within 10 epochs, the training will stop." }, { "code": null, "e": 11493, "s": 11434, "text": "csv_logger — Logs the monitored metrics/loss to a CSV file" }, { "code": null, "e": 11619, "s": 11493, "text": "lr_callback — Reduces the learning rate of the optimizer by a factor of 0.1 if the val_loss does not go down within 5 epochs." }, { "code": null, "e": 11836, "s": 11619, "text": "Finally, model.fit() is called with train_gen_aux as the training data, valid_gen as the validation data. The function get_steps_per_epochcomputes the number of steps given the size of the dataset and the batch size." }, { "code": null, "e": 11891, "s": 11836, "text": "And then we can evaluate the model on test data using," }, { "code": null, "e": 11998, "s": 11891, "text": "# Evaluate the modeltest_res = model.evaluate(test_gen_aux, steps=get_steps_per_epoch(500*50, batch_size))" }, { "code": null, "e": 12074, "s": 11998, "text": "If you run the training, you should get an output similar to the one below." }, { "code": null, "e": 12685, "s": 12074, "text": "Epoch 1/502813/2813 [==============================] - 1465s 521ms/step - loss: 2.0031 - accuracy: 0.5557 - val_loss: 1.5206 - val_accuracy: 0.6418Epoch 2/502813/2813 [==============================] - 1456s 517ms/step - loss: 1.3250 - accuracy: 0.6777 - val_loss: 1.4021 - val_accuracy: 0.6622...Epoch 23/502813/2813 [==============================] - ETA: 0s - loss: 0.1268 - accuracy: 0.9644Epoch 00023: ReduceLROnPlateau reducing learning rate to 9.999999974752428e-08.2813/2813 [==============================] - 1456s 518ms/step - loss: 0.1268 - accuracy: 0.9644 - val_loss: 1.2681 - val_accuracy: 0.7420" }, { "code": null, "e": 12703, "s": 12685, "text": "and on test data," }, { "code": null, "e": 12795, "s": 12703, "text": "782/782 [==============================] - 84s 107ms/step - loss: 1.0672 - accuracy: 0.7874" }, { "code": null, "e": 12996, "s": 12795, "text": "The model has reached around ~75% accuracy on the validation data and ~78% on the test set. This accuracy is a very respectable accuracy compared to state of the art performance (which is around 85%)." }, { "code": null, "e": 13241, "s": 12996, "text": "The content of this article is based on my latest upcoming book “TensorFlow 2 in Action” by Manning. Don’t be disheartened, if you don’t want to check the book out, the code for the book is available for free on Github and can be accessed here." }, { "code": null, "e": 13333, "s": 13241, "text": "Here’s how this compares to some of the other attempts discussed in the book. Specifically," }, { "code": null, "e": 13444, "s": 13333, "text": "inception-net-v1 data-aug + early-stop — An Inception Net v1 model (with data augmentation and early stopping)" }, { "code": null, "e": 13530, "s": 13444, "text": "Minception-net — A modified version of Inception Resnet v2 (trained from the scratch)" }, { "code": null, "e": 13616, "s": 13530, "text": "Inception-Resnet-v2 transfer-learn — Inception Resnet v2 model pretrained on ImageNet" }, { "code": null, "e": 14118, "s": 13616, "text": "That was a very quick hands-on guide as to how you can use Transfer Learning with TensorFlow to quickly get a model up and running. Transfer Learning enables you to transfer the knowledge of a pretrained model for a downstream task you’re interested in solving. This can be really handy in some situations. For example, if you are working on a computer vision product you might save weeks or even months by starting out with a pretrained model. So this is a very important concept to be familiar with." }, { "code": null, "e": 14136, "s": 14118, "text": "In this guide we," }, { "code": null, "e": 14170, "s": 14136, "text": "Learned what Transfer Learning is" }, { "code": null, "e": 14193, "s": 14170, "text": "Understood the dataset" }, { "code": null, "e": 14246, "s": 14193, "text": "Learned the nitty-gritties of InceptionNet-Resnet-v2" }, { "code": null, "e": 14302, "s": 14246, "text": "Downloaded a ImageNet pretrained InceptionNet-Resnet-v2" }, { "code": null, "e": 14416, "s": 14302, "text": "Used the downloaded model to define a new model and solve the classification task (Tiny-ImageNet) at hand quickly" }, { "code": null, "e": 14455, "s": 14416, "text": "If you would like to learn more about," }, { "code": null, "e": 14516, "s": 14455, "text": "Data augmentation and creating data pipelines in TensorFlow," }, { "code": null, "e": 14558, "s": 14516, "text": "Mechanics of convolution neural networks," }, { "code": null, "e": 14622, "s": 14558, "text": "Inception net models and various design principles behind them," }, { "code": null, "e": 14685, "s": 14622, "text": "Techniques like batch normalization, residual connections and," }, { "code": null, "e": 14734, "s": 14685, "text": "Using Transfer Learning for image classifcation," }, { "code": null, "e": 14831, "s": 14734, "text": "checkout Chapter 6 and 7 of “TensorFlow 2 in Action” by Manning (provided as an affiliate link)." }, { "code": null, "e": 14847, "s": 14831, "text": "Happy learning!" } ]
C Program for product of array
Given an array arr[n] of n number of elements, the task is to find the product of all the elements of that array. Like we have an array arr[7] of 7 elements so its product will be like Input: arr[] = { 10, 20, 3, 4, 8 } Output: 19200 Explanation: 10 x 20 x 3 x 4 x 8 = 19200 Input: arr[] = { 1, 2, 3, 4, 3, 2, 1 } Output: 144 The approach used below is as follows − Take array input. Find its size. Iterate the array and Multiply each element of that array Show result Start In function int prod_mat(int arr[], int n) Step 1-> Declare and initialize result = 1 Step 2-> Loop for i = 0 and i < n and i++ result = result * arr[i]; Step 3-> Return result int main() Step 1-> Declare an array arr[] step 2-> Declare a variable for size of array Step 3-> Print the result Live Demo #include <stdio.h> int prod_arr(int arr[], int n) { int result = 1; //Wil multiply each element and store it in result for (int i = 0; i < n; i++) result = result * arr[i]; return result; } int main() { int arr[] = { 10, 20, 3, 4, 8 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", prod_arr(arr, n)); return 0; } If run the above code it will generate the following output − 19200
[ { "code": null, "e": 1176, "s": 1062, "text": "Given an array arr[n] of n number of elements, the task is to find the product of all the elements of that array." }, { "code": null, "e": 1247, "s": 1176, "text": "Like we have an array arr[7] of 7 elements so its product will be like" }, { "code": null, "e": 1388, "s": 1247, "text": "Input: arr[] = { 10, 20, 3, 4, 8 }\nOutput: 19200\nExplanation: 10 x 20 x 3 x 4 x 8 = 19200\nInput: arr[] = { 1, 2, 3, 4, 3, 2, 1 }\nOutput: 144" }, { "code": null, "e": 1428, "s": 1388, "text": "The approach used below is as follows −" }, { "code": null, "e": 1446, "s": 1428, "text": "Take array input." }, { "code": null, "e": 1461, "s": 1446, "text": "Find its size." }, { "code": null, "e": 1519, "s": 1461, "text": "Iterate the array and Multiply each element of that array" }, { "code": null, "e": 1531, "s": 1519, "text": "Show result" }, { "code": null, "e": 1853, "s": 1531, "text": "Start\nIn function int prod_mat(int arr[], int n)\n Step 1-> Declare and initialize result = 1\n Step 2-> Loop for i = 0 and i < n and i++\n result = result * arr[i];\n Step 3-> Return result\nint main()\n Step 1-> Declare an array arr[]\n step 2-> Declare a variable for size of array\n Step 3-> Print the result" }, { "code": null, "e": 1864, "s": 1853, "text": " Live Demo" }, { "code": null, "e": 2209, "s": 1864, "text": "#include <stdio.h>\nint prod_arr(int arr[], int n) {\n int result = 1;\n //Wil multiply each element and store it in result\n for (int i = 0; i < n; i++)\n result = result * arr[i];\n return result;\n}\nint main() {\n int arr[] = { 10, 20, 3, 4, 8 };\n int n = sizeof(arr) / sizeof(arr[0]);\n printf(\"%d\", prod_arr(arr, n));\n return 0;\n}" }, { "code": null, "e": 2271, "s": 2209, "text": "If run the above code it will generate the following output −" }, { "code": null, "e": 2277, "s": 2271, "text": "19200" } ]
Toggle all even bits of a number - GeeksforGeeks
07 Sep, 2021 Given a number, the task is to Toggle all even bit of a numberExamples: Input : 10 Output : 0 binary representation 1 0 1 0 after toggle 0 0 0 0 Input : 20 Output : 30 binary representation 1 0 1 0 0 after toggle 1 1 1 1 0 1. First generate a number that contains even position bits. 2. Take XOR with the original number. Note that 1 ^ 1 = 0 and 1 ^ 0 = 1.Let’s understand this approach with below code. C++ Java Python3 C# PHP Javascript // CPP code to Toggle all even// bit of a number#include <iostream>using namespace std; // Returns a number which has all even// bits of n toggled.int evenbittogglenumber(int n){ // Generate number form of 101010 // ..till of same order as n int res = 0, count = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res;} // Driver codeint main(){ int n = 11; cout << evenbittogglenumber(n); return 0;} // Java code to Toggle all// even bit of a numberimport java.io.*; class GFG { // Returns a number which has // all even bits of n toggled. static int evenbittogglenumber(int n) { // Generate number form of 101010 // ..till of same order as n int res = 0, count = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res; } // Driver code public static void main(String args[]) { int n = 11; System.out.println(evenbittogglenumber(n)); }} // This code is contributed by Nikita Tiwari. # Python code to Toggle all# even bit of a number # Returns a number which has all even# bits of n toggled.def evenbittogglenumber(n) : # Generate number form of 101010 # ..till of same order as n res = 0 count = 0 temp = n while (temp > 0) : # if bit is even then generate # number and or with res if (count % 2 == 1) : res = res | (1 << count) count = count + 1 temp >>= 1 # return toggled number return n ^ res # Driver coden = 11print(evenbittogglenumber(n)) #This code is contributed by Nikita Tiwari. // C# code to Toggle all// even bit of a numberusing System; class GFG { // Returns a number which has // all even bits of n toggled. static int evenbittogglenumber(int n) { // Generate number form of 101010 // ..till of same order as n int res = 0, count = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res; } // Driver code public static void Main() { int n = 11; Console.WriteLine(evenbittogglenumber(n)); }} // This code is contributed by Anant Agarwal. <?php// php code to Toggle all// even bit of a number // Returns a number which has// all even bits of n toggled.function evenbittogglenumber($n){ // Generate number form of 101010 // ..till of same order as n $res = 0; $count = 0; for ($temp = $n; $temp > 0; $temp >>= 1) { // if bit is even then generate // number and or with res if ($count % 2 == 1) $res |= (1 << $count); $count++; } // return toggled number return $n ^ $res;} // Driver code $n = 11; echo evenbittogglenumber($n); // This code is contributed by mits?> <script> // JavaScript program to Toggle all// even bit of a number // Returns a number which has // all even bits of n toggled. function evenbittogglenumber(n) { // Generate number form of 101010 // ..till of same order as n let res = 0, count = 0; for (let temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res; } // Driver code let n = 11; document.write(evenbittogglenumber(n)); </script> Output: 1 Mithun Kumar susmitakundugoaldanga anikaseth98 Bitwise-XOR Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Program to find whether a given number is power of 2 Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Find the element that appears once Bits manipulation (Important tactics)
[ { "code": null, "e": 26001, "s": 25973, "text": "\n07 Sep, 2021" }, { "code": null, "e": 26075, "s": 26001, "text": "Given a number, the task is to Toggle all even bit of a numberExamples: " }, { "code": null, "e": 26247, "s": 26075, "text": "Input : 10\nOutput : 0\nbinary representation 1 0 1 0\nafter toggle 0 0 0 0 \n\n\nInput : 20\nOutput : 30\nbinary representation 1 0 1 0 0\nafter toggle 1 1 1 1 0" }, { "code": null, "e": 26432, "s": 26249, "text": "1. First generate a number that contains even position bits. 2. Take XOR with the original number. Note that 1 ^ 1 = 0 and 1 ^ 0 = 1.Let’s understand this approach with below code. " }, { "code": null, "e": 26436, "s": 26432, "text": "C++" }, { "code": null, "e": 26441, "s": 26436, "text": "Java" }, { "code": null, "e": 26449, "s": 26441, "text": "Python3" }, { "code": null, "e": 26452, "s": 26449, "text": "C#" }, { "code": null, "e": 26456, "s": 26452, "text": "PHP" }, { "code": null, "e": 26467, "s": 26456, "text": "Javascript" }, { "code": "// CPP code to Toggle all even// bit of a number#include <iostream>using namespace std; // Returns a number which has all even// bits of n toggled.int evenbittogglenumber(int n){ // Generate number form of 101010 // ..till of same order as n int res = 0, count = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res;} // Driver codeint main(){ int n = 11; cout << evenbittogglenumber(n); return 0;}", "e": 27086, "s": 26467, "text": null }, { "code": "// Java code to Toggle all// even bit of a numberimport java.io.*; class GFG { // Returns a number which has // all even bits of n toggled. static int evenbittogglenumber(int n) { // Generate number form of 101010 // ..till of same order as n int res = 0, count = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res; } // Driver code public static void main(String args[]) { int n = 11; System.out.println(evenbittogglenumber(n)); }} // This code is contributed by Nikita Tiwari.", "e": 27924, "s": 27086, "text": null }, { "code": "# Python code to Toggle all# even bit of a number # Returns a number which has all even# bits of n toggled.def evenbittogglenumber(n) : # Generate number form of 101010 # ..till of same order as n res = 0 count = 0 temp = n while (temp > 0) : # if bit is even then generate # number and or with res if (count % 2 == 1) : res = res | (1 << count) count = count + 1 temp >>= 1 # return toggled number return n ^ res # Driver coden = 11print(evenbittogglenumber(n)) #This code is contributed by Nikita Tiwari.", "e": 28530, "s": 27924, "text": null }, { "code": "// C# code to Toggle all// even bit of a numberusing System; class GFG { // Returns a number which has // all even bits of n toggled. static int evenbittogglenumber(int n) { // Generate number form of 101010 // ..till of same order as n int res = 0, count = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res; } // Driver code public static void Main() { int n = 11; Console.WriteLine(evenbittogglenumber(n)); }} // This code is contributed by Anant Agarwal.", "e": 29381, "s": 28530, "text": null }, { "code": "<?php// php code to Toggle all// even bit of a number // Returns a number which has// all even bits of n toggled.function evenbittogglenumber($n){ // Generate number form of 101010 // ..till of same order as n $res = 0; $count = 0; for ($temp = $n; $temp > 0; $temp >>= 1) { // if bit is even then generate // number and or with res if ($count % 2 == 1) $res |= (1 << $count); $count++; } // return toggled number return $n ^ $res;} // Driver code $n = 11; echo evenbittogglenumber($n); // This code is contributed by mits?>", "e": 29994, "s": 29381, "text": null }, { "code": "<script> // JavaScript program to Toggle all// even bit of a number // Returns a number which has // all even bits of n toggled. function evenbittogglenumber(n) { // Generate number form of 101010 // ..till of same order as n let res = 0, count = 0; for (let temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return toggled number return n ^ res; } // Driver code let n = 11; document.write(evenbittogglenumber(n)); </script>", "e": 30735, "s": 29994, "text": null }, { "code": null, "e": 30744, "s": 30735, "text": "Output: " }, { "code": null, "e": 30746, "s": 30744, "text": "1" }, { "code": null, "e": 30761, "s": 30748, "text": "Mithun Kumar" }, { "code": null, "e": 30783, "s": 30761, "text": "susmitakundugoaldanga" }, { "code": null, "e": 30795, "s": 30783, "text": "anikaseth98" }, { "code": null, "e": 30807, "s": 30795, "text": "Bitwise-XOR" }, { "code": null, "e": 30817, "s": 30807, "text": "Bit Magic" }, { "code": null, "e": 30827, "s": 30817, "text": "Bit Magic" }, { "code": null, "e": 30925, "s": 30827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30955, "s": 30925, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 31001, "s": 30955, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 31041, "s": 31001, "text": "Binary representation of a given number" }, { "code": null, "e": 31094, "s": 31041, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 31145, "s": 31094, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 31196, "s": 31145, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 31239, "s": 31196, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 31255, "s": 31239, "text": "Bit Fields in C" }, { "code": null, "e": 31290, "s": 31255, "text": "Find the element that appears once" } ]
Maximum number of threads that can be created within a process in C - GeeksforGeeks
26 Sep, 2017 Thread of execution is the smallest sequence of programmed instructions that can be managed independently by scheduler. Thread is a component of process and so multiple threads can be associated in a process. Linux doesn’t have a separate threads per process limit, but has a limit on the total number of processes on the system (as threads just processes with a shared address space on Linux). Our task is to find out maximum number of thread that can be created within a single process (maximum number of thread that pthread_create can create). Maximum number of threads can be seen is ubuntu by using command: cat /proc/sys/kernel/threads-max This thread limit for linux can be modified at runtime by writing desired limit to /proc/sys/kernel/threads-max. Compile the following program on ubuntu operating system, to check maximum number of threads that can be created within a process in C. cc filename.c -pthread where filename.c is the name with which file is saved. // C program to find maximum number of thread within// a process#include<stdio.h>#include<pthread.h> // This function demonstrates the work of thread// which is of no use here, So left blankvoid *thread ( void *vargp){ } int main(){ int err = 0, count = 0; pthread_t tid; // on success, pthread_create returns 0 and // on Error, it returns error number // So, while loop is iterated until return value is 0 while (err == 0) { err = pthread_create (&tid, NULL, thread, NULL); count++; } printf("Maximum number of thread within a Process" " is : %d\n", count);} Output: Maximum number of thread within a Process is : 32754 This article is contributed by Aditya Kumar. 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. Processes & Threads C Language Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples TCP Server-Client implementation in C
[ { "code": null, "e": 24232, "s": 24204, "text": "\n26 Sep, 2017" }, { "code": null, "e": 24627, "s": 24232, "text": "Thread of execution is the smallest sequence of programmed instructions that can be managed independently by scheduler. Thread is a component of process and so multiple threads can be associated in a process. Linux doesn’t have a separate threads per process limit, but has a limit on the total number of processes on the system (as threads just processes with a shared address space on Linux)." }, { "code": null, "e": 24845, "s": 24627, "text": "Our task is to find out maximum number of thread that can be created within a single process (maximum number of thread that pthread_create can create). Maximum number of threads can be seen is ubuntu by using command:" }, { "code": null, "e": 24878, "s": 24845, "text": "cat /proc/sys/kernel/threads-max" }, { "code": null, "e": 24991, "s": 24878, "text": "This thread limit for linux can be modified at runtime by writing desired limit to /proc/sys/kernel/threads-max." }, { "code": null, "e": 25127, "s": 24991, "text": "Compile the following program on ubuntu operating system, to check maximum number of threads that can be created within a process in C." }, { "code": null, "e": 25206, "s": 25127, "text": "cc filename.c -pthread where filename.c \nis the name with which file is saved." }, { "code": "// C program to find maximum number of thread within// a process#include<stdio.h>#include<pthread.h> // This function demonstrates the work of thread// which is of no use here, So left blankvoid *thread ( void *vargp){ } int main(){ int err = 0, count = 0; pthread_t tid; // on success, pthread_create returns 0 and // on Error, it returns error number // So, while loop is iterated until return value is 0 while (err == 0) { err = pthread_create (&tid, NULL, thread, NULL); count++; } printf(\"Maximum number of thread within a Process\" \" is : %d\\n\", count);}", "e": 25854, "s": 25206, "text": null }, { "code": null, "e": 25862, "s": 25854, "text": "Output:" }, { "code": null, "e": 25916, "s": 25862, "text": "Maximum number of thread within a Process is : 32754\n" }, { "code": null, "e": 26216, "s": 25916, "text": "This article is contributed by Aditya Kumar. 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." }, { "code": null, "e": 26341, "s": 26216, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26361, "s": 26341, "text": "Processes & Threads" }, { "code": null, "e": 26372, "s": 26361, "text": "C Language" }, { "code": null, "e": 26383, "s": 26372, "text": "Linux-Unix" }, { "code": null, "e": 26481, "s": 26383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26490, "s": 26481, "text": "Comments" }, { "code": null, "e": 26503, "s": 26490, "text": "Old Comments" }, { "code": null, "e": 26541, "s": 26503, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26567, "s": 26541, "text": "Exception Handling in C++" }, { "code": null, "e": 26587, "s": 26567, "text": "Multithreading in C" }, { "code": null, "e": 26609, "s": 26587, "text": "'this' pointer in C++" }, { "code": null, "e": 26647, "s": 26609, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26687, "s": 26647, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 26727, "s": 26687, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 26754, "s": 26727, "text": "grep command in Unix/Linux" }, { "code": null, "e": 26789, "s": 26754, "text": "cut command in Linux with examples" } ]
Image Augmentation for Deep Learning using Keras and Histogram Equalization | by Ryan Allred | Towards Data Science
In this post we’ll go over: Image Augmentation: What is it? Why is it important? Keras: How to use it for basic Image Augmentation. Histogram Equalization: What is it? How is it useful? Implementing Histogram Equalization Techniques: one way to modify the keras.preprocessing image.py file. Deep Neural Networks, particularly Convolutional Neural Networks (CNNs), are particularly proficient at image classification tasks. State-of-the-art CNNs have even been shown to exceed human performance in image recognition. However, as we learn from Mr. Jian-Yang’s “Hot Dog, Not Hot Dog” food recognition app in the popular TV show, Silicon Valley, (the app is now available on the app store) gathering images as training data can be both costly and time consuming. If you aren’t familiar with the TV show Silicon Valley, be warned that the language in the following clip is NSFW: In order to combat the high expense of collecting thousands of training images, image augmentation has been developed in order to generate training data from an existing dataset. Image Augmentation is the process of taking images that are already in a training dataset and manipulating them to create many altered versions of the same image. This both provides more images to train on, but can also help expose our classifier to a wider variety of lighting and coloring situations so as to make our classifier more robust. Here are some examples of different augmentations from the imgaug library. There are many ways to pre-process images. In this post we will go over some of the most common out-of-the-box methods that the keras deep learning library provides for augmenting images, then we will show how to alter the keras.preprocessing image.py file in order to enable histogram equalization methods. We will use the cifar10 dataset that comes with keras. However, we will only be using the images of cats and dogs from the dataset in order to keep the task small enough to be performed on a CPU — in case you want to follow along. You can view an IPython notebook of the source code from this post. The first thing that we will do is load the cifar10 dataset and format the images to prepare them for the CNN. We’ll also take a peek at a few of the images just to make sure the data has loaded properly. The cifar10 images are only 32 x 32 pixels, so they look grainy when magnified here, but the CNN doesn’t know it’s grainy, all it sees is DATA. Augmenting our image data with keras is dead simple. A shoutout to Jason Brownlee who provides a great tutorial on this. First we need to create an image generator by calling the ImageDataGenerator() function and pass it a list of parameters describing the alterations that we want it to perform on the images. We will then call the fit() function on our image generator which will apply the changes to the images batch by batch. By default, the modifications will be applied randomly, so not every image will be changed every time. You can also use keras.preprocessing to export augmented image files to a folder in order to build up a giant dataset of altered images should you desire to do so. We’ll look at some of the more visually interesting augmentations here. A description of the all of the possible ImageDataGenerator() parameters as well as a list of the other methods available in keras.preprocessing can be seen in the keras documentation. Flipping images horizontally is also one of the classic ways of generating more data for a classifier. It is just as easy to do and probably makes more sense with this dataset, however, I’ve left out the code and images because there’s no way of knowing whether a dog or cat image has been flipped horizontally without seeing the original. Histogram Equalization is the process taking a low contrast image and increasing the contrast between the image’s relative highs and lows in order to bring out subtle differences in shade and create a higher contrast image. The results can be striking, especially for grayscale images. Here are some examples: In this post we’ll be looking at three image augmentation techniques for improving contrast in images. These approaches are sometimes also referred to as “Histogram Stretching” because they take the distribution of pixel intensities and stretch the distribution to fit a wider range of values thereby increasing the level of contrast between the lightest and darkest portions of an image. Histogram Equalization increases contrast in images by detecting the distribution of pixel densities in an image and plotting these pixel densities on a histogram. The distribution of this histogram is then analyzed and if there are ranges of pixel brightnesses that aren’t currently being utilized, the histogram is then “stretched” to cover those ranges, and then is “back projected” onto the image to increase the overall contrast of the image. Contrast Stretching takes the approach of analyzing the distribution of pixel densities in an image and then “rescales the image to include all intensities that fall within the 2nd and 98th percentiles.” Adaptive Equalization differs from regular histogram equalization in that several different histograms are computed, each corresponding to a different section of the image; however, it has a tendency to over-amplify noise in otherwise uninteresting sections. The following code comes from the sci-kit image library’s docs and has been altered to perform the three above augmentations on the first image of our cifar10 dataset. First we will import the necessary modules from the sci-kit image (skimage) library and then modify the code from the sci-kit image documentation to view the augmentations on the first image of our dataset. Here are the modified images of a low contrast cat from the cifar10 dataset. As you can see, the results are not as striking as they might be with a low contrast grayscale image, but still help improve the quality of the images. Now that we have successfully modified one image from the cifar10 dataset, we will demonstrate how to alter the keras.preprocessing image.py file in order to execute these different histogram modification techniques just as we did the out-of-the-box keras augmentations using ImageDataGenerator(). Here are the general steps that we will follow in order to implement this functionality: Find the keras.preprocessing image.py file on your own machine. Copy the image.py file into your file or notebook. Add one attribute for each equalization technique to the DataImageGenerator() init function. Add IF statement clauses to the random_transform method so that augmentations get implemented when we call datagen.fit(). One of the simplest ways to make alterations to keras.preprocessing’s image.py file is simply to copy and paste its contents into our code. This will then remove the need to import it. You can view the contents of the image.py file on github here. However, in order to be sure that you’re grabbing the same version of the file that you were importing previously, it’s better to grab the image.py file that is already on your machine. Running print(keras.__file__) will print out the path to the keras library that is on your machine. The path (for mac users) may look something like: /usr/local/lib/python3.5/dist-packages/keras/__init__.pyc This gives us the path to keras on our local machine. Go ahead and navigate there and then into the preprocessing folder. Inside preprocessing you will see the image.py file. You can then copy its contents into your code. The file is long, but for beginners this is probably one of the easiest ways to go about making alterations to it. At the top of image.py you can comment out the line: from ..import backend as K if you have already included it above. At this point, also double-check to make sure that you’re importing the necessary scikit-image modules so that the copied image.py can see them. from skimage import data, img_as_floatfrom skimage import exposure We now need to add six lines to the ImageDataGenerator class’s __init__ method so that it has the three properties that represent the types of augmentation that we’re going to be adding. The code below is copied from my current image.py. The lines with ##### to the side are lines that I have added. The random_transform() function (below) responds to the arguments we have been passed into the ImageDataGenerator() function. If we have set the contrast_stretching, adaptive_equalization, or histogram_equalization parameters to True, when we call ImageDataGenerator(), (just like we would for the other image augmentations) random_transform()will then apply the desired image augmentation. Now we have all of the necessary code in place and can call ImageDataGenerator() to perform our histogram modification techniques. Here’s what a few images look like if we set all three of the values to True. I don’t recommend setting more than one of them to True for any given dataset. Make sure you experiment with your particular dataset in order to see what helps improve your classifier’s accuracy. For colored images, I’ve found that contrast stretching often obtains better results than histogram modification or adaptive equalization. The final step is to train our CNN and validate the model using model.fit_generator() in order to train and validate our neural network on the augmented images.
[ { "code": null, "e": 200, "s": 172, "text": "In this post we’ll go over:" }, { "code": null, "e": 253, "s": 200, "text": "Image Augmentation: What is it? Why is it important?" }, { "code": null, "e": 304, "s": 253, "text": "Keras: How to use it for basic Image Augmentation." }, { "code": null, "e": 358, "s": 304, "text": "Histogram Equalization: What is it? How is it useful?" }, { "code": null, "e": 463, "s": 358, "text": "Implementing Histogram Equalization Techniques: one way to modify the keras.preprocessing image.py file." }, { "code": null, "e": 688, "s": 463, "text": "Deep Neural Networks, particularly Convolutional Neural Networks (CNNs), are particularly proficient at image classification tasks. State-of-the-art CNNs have even been shown to exceed human performance in image recognition." }, { "code": null, "e": 931, "s": 688, "text": "However, as we learn from Mr. Jian-Yang’s “Hot Dog, Not Hot Dog” food recognition app in the popular TV show, Silicon Valley, (the app is now available on the app store) gathering images as training data can be both costly and time consuming." }, { "code": null, "e": 1046, "s": 931, "text": "If you aren’t familiar with the TV show Silicon Valley, be warned that the language in the following clip is NSFW:" }, { "code": null, "e": 1644, "s": 1046, "text": "In order to combat the high expense of collecting thousands of training images, image augmentation has been developed in order to generate training data from an existing dataset. Image Augmentation is the process of taking images that are already in a training dataset and manipulating them to create many altered versions of the same image. This both provides more images to train on, but can also help expose our classifier to a wider variety of lighting and coloring situations so as to make our classifier more robust. Here are some examples of different augmentations from the imgaug library." }, { "code": null, "e": 2251, "s": 1644, "text": "There are many ways to pre-process images. In this post we will go over some of the most common out-of-the-box methods that the keras deep learning library provides for augmenting images, then we will show how to alter the keras.preprocessing image.py file in order to enable histogram equalization methods. We will use the cifar10 dataset that comes with keras. However, we will only be using the images of cats and dogs from the dataset in order to keep the task small enough to be performed on a CPU — in case you want to follow along. You can view an IPython notebook of the source code from this post." }, { "code": null, "e": 2456, "s": 2251, "text": "The first thing that we will do is load the cifar10 dataset and format the images to prepare them for the CNN. We’ll also take a peek at a few of the images just to make sure the data has loaded properly." }, { "code": null, "e": 2600, "s": 2456, "text": "The cifar10 images are only 32 x 32 pixels, so they look grainy when magnified here, but the CNN doesn’t know it’s grainy, all it sees is DATA." }, { "code": null, "e": 3297, "s": 2600, "text": "Augmenting our image data with keras is dead simple. A shoutout to Jason Brownlee who provides a great tutorial on this. First we need to create an image generator by calling the ImageDataGenerator() function and pass it a list of parameters describing the alterations that we want it to perform on the images. We will then call the fit() function on our image generator which will apply the changes to the images batch by batch. By default, the modifications will be applied randomly, so not every image will be changed every time. You can also use keras.preprocessing to export augmented image files to a folder in order to build up a giant dataset of altered images should you desire to do so." }, { "code": null, "e": 3554, "s": 3297, "text": "We’ll look at some of the more visually interesting augmentations here. A description of the all of the possible ImageDataGenerator() parameters as well as a list of the other methods available in keras.preprocessing can be seen in the keras documentation." }, { "code": null, "e": 3894, "s": 3554, "text": "Flipping images horizontally is also one of the classic ways of generating more data for a classifier. It is just as easy to do and probably makes more sense with this dataset, however, I’ve left out the code and images because there’s no way of knowing whether a dog or cat image has been flipped horizontally without seeing the original." }, { "code": null, "e": 4204, "s": 3894, "text": "Histogram Equalization is the process taking a low contrast image and increasing the contrast between the image’s relative highs and lows in order to bring out subtle differences in shade and create a higher contrast image. The results can be striking, especially for grayscale images. Here are some examples:" }, { "code": null, "e": 4593, "s": 4204, "text": "In this post we’ll be looking at three image augmentation techniques for improving contrast in images. These approaches are sometimes also referred to as “Histogram Stretching” because they take the distribution of pixel intensities and stretch the distribution to fit a wider range of values thereby increasing the level of contrast between the lightest and darkest portions of an image." }, { "code": null, "e": 5041, "s": 4593, "text": "Histogram Equalization increases contrast in images by detecting the distribution of pixel densities in an image and plotting these pixel densities on a histogram. The distribution of this histogram is then analyzed and if there are ranges of pixel brightnesses that aren’t currently being utilized, the histogram is then “stretched” to cover those ranges, and then is “back projected” onto the image to increase the overall contrast of the image." }, { "code": null, "e": 5245, "s": 5041, "text": "Contrast Stretching takes the approach of analyzing the distribution of pixel densities in an image and then “rescales the image to include all intensities that fall within the 2nd and 98th percentiles.”" }, { "code": null, "e": 5504, "s": 5245, "text": "Adaptive Equalization differs from regular histogram equalization in that several different histograms are computed, each corresponding to a different section of the image; however, it has a tendency to over-amplify noise in otherwise uninteresting sections." }, { "code": null, "e": 5879, "s": 5504, "text": "The following code comes from the sci-kit image library’s docs and has been altered to perform the three above augmentations on the first image of our cifar10 dataset. First we will import the necessary modules from the sci-kit image (skimage) library and then modify the code from the sci-kit image documentation to view the augmentations on the first image of our dataset." }, { "code": null, "e": 6108, "s": 5879, "text": "Here are the modified images of a low contrast cat from the cifar10 dataset. As you can see, the results are not as striking as they might be with a low contrast grayscale image, but still help improve the quality of the images." }, { "code": null, "e": 6495, "s": 6108, "text": "Now that we have successfully modified one image from the cifar10 dataset, we will demonstrate how to alter the keras.preprocessing image.py file in order to execute these different histogram modification techniques just as we did the out-of-the-box keras augmentations using ImageDataGenerator(). Here are the general steps that we will follow in order to implement this functionality:" }, { "code": null, "e": 6559, "s": 6495, "text": "Find the keras.preprocessing image.py file on your own machine." }, { "code": null, "e": 6610, "s": 6559, "text": "Copy the image.py file into your file or notebook." }, { "code": null, "e": 6703, "s": 6610, "text": "Add one attribute for each equalization technique to the DataImageGenerator() init function." }, { "code": null, "e": 6825, "s": 6703, "text": "Add IF statement clauses to the random_transform method so that augmentations get implemented when we call datagen.fit()." }, { "code": null, "e": 7409, "s": 6825, "text": "One of the simplest ways to make alterations to keras.preprocessing’s image.py file is simply to copy and paste its contents into our code. This will then remove the need to import it. You can view the contents of the image.py file on github here. However, in order to be sure that you’re grabbing the same version of the file that you were importing previously, it’s better to grab the image.py file that is already on your machine. Running print(keras.__file__) will print out the path to the keras library that is on your machine. The path (for mac users) may look something like:" }, { "code": null, "e": 7467, "s": 7409, "text": "/usr/local/lib/python3.5/dist-packages/keras/__init__.pyc" }, { "code": null, "e": 7804, "s": 7467, "text": "This gives us the path to keras on our local machine. Go ahead and navigate there and then into the preprocessing folder. Inside preprocessing you will see the image.py file. You can then copy its contents into your code. The file is long, but for beginners this is probably one of the easiest ways to go about making alterations to it." }, { "code": null, "e": 7923, "s": 7804, "text": "At the top of image.py you can comment out the line: from ..import backend as K if you have already included it above." }, { "code": null, "e": 8068, "s": 7923, "text": "At this point, also double-check to make sure that you’re importing the necessary scikit-image modules so that the copied image.py can see them." }, { "code": null, "e": 8135, "s": 8068, "text": "from skimage import data, img_as_floatfrom skimage import exposure" }, { "code": null, "e": 8435, "s": 8135, "text": "We now need to add six lines to the ImageDataGenerator class’s __init__ method so that it has the three properties that represent the types of augmentation that we’re going to be adding. The code below is copied from my current image.py. The lines with ##### to the side are lines that I have added." }, { "code": null, "e": 8826, "s": 8435, "text": "The random_transform() function (below) responds to the arguments we have been passed into the ImageDataGenerator() function. If we have set the contrast_stretching, adaptive_equalization, or histogram_equalization parameters to True, when we call ImageDataGenerator(), (just like we would for the other image augmentations) random_transform()will then apply the desired image augmentation." }, { "code": null, "e": 9035, "s": 8826, "text": "Now we have all of the necessary code in place and can call ImageDataGenerator() to perform our histogram modification techniques. Here’s what a few images look like if we set all three of the values to True." }, { "code": null, "e": 9370, "s": 9035, "text": "I don’t recommend setting more than one of them to True for any given dataset. Make sure you experiment with your particular dataset in order to see what helps improve your classifier’s accuracy. For colored images, I’ve found that contrast stretching often obtains better results than histogram modification or adaptive equalization." } ]
How to uninstall the PowerShell Module?
To uninstall the PowerShell module, we can directly use the Uninstall-Module command but the module should not be in use, otherwise, it will throw an error. When we use the Uninstall-Module command, it can uninstall the module from the current user profile or from the all users profile. Uninstall-Module 7Zip4PowerShell -Force -Verbose Another method, Get-InstalledModule 7Zip4Powershell | Uninstall-Module -Force -Verbose If you have multiple versions of the same module installed in the PowerShell, and if you want to uninstall all of them then use the -AllVersions Parameter. Uninstall-Module 7Zip4PowerShell -AllVersions -Force -Verbose If you want to uninstall the specific version, we can use -RequiredVersion. Uninstall-Module 7Zip4PowerShell -RequiredVersion 1.5.0 -Force -Verbose To uninstall on the remote computer, use the Invoke-Command method. Invoke-Command -ComputerName RemoteComputer1 -ScriptBlock { Uninstall-Module 7Zip4PowerShell -RequiredVersion 1.5.0 -Force -Verbose }
[ { "code": null, "e": 1219, "s": 1062, "text": "To uninstall the PowerShell module, we can directly use the Uninstall-Module command but the module should not be in use, otherwise, it will throw an error." }, { "code": null, "e": 1350, "s": 1219, "text": "When we use the Uninstall-Module command, it can uninstall the module from the current user profile or from the all users profile." }, { "code": null, "e": 1399, "s": 1350, "text": "Uninstall-Module 7Zip4PowerShell -Force -Verbose" }, { "code": null, "e": 1415, "s": 1399, "text": "Another method," }, { "code": null, "e": 1486, "s": 1415, "text": "Get-InstalledModule 7Zip4Powershell | Uninstall-Module -Force -Verbose" }, { "code": null, "e": 1642, "s": 1486, "text": "If you have multiple versions of the same module installed in the PowerShell, and if you want to uninstall all of them then use the -AllVersions Parameter." }, { "code": null, "e": 1704, "s": 1642, "text": "Uninstall-Module 7Zip4PowerShell -AllVersions -Force -Verbose" }, { "code": null, "e": 1780, "s": 1704, "text": "If you want to uninstall the specific version, we can use -RequiredVersion." }, { "code": null, "e": 1852, "s": 1780, "text": "Uninstall-Module 7Zip4PowerShell -RequiredVersion 1.5.0 -Force -Verbose" }, { "code": null, "e": 1920, "s": 1852, "text": "To uninstall on the remote computer, use the Invoke-Command method." }, { "code": null, "e": 2057, "s": 1920, "text": "Invoke-Command -ComputerName RemoteComputer1 -ScriptBlock {\n Uninstall-Module 7Zip4PowerShell -RequiredVersion 1.5.0 -Force -Verbose\n}" } ]
Python | Pandas DataFrame.dropna()
05 Jul, 2018 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. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Pandas dropna() method allows the user to analyze and drop Rows/Columns with Null values in different ways. Syntax: DataFrameName.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False) Parameters: axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and ‘index’ or ‘columns’ for String.how: how takes string value of two kinds only (‘any’ or ‘all’). ‘any’ drops the row/column if ANY value is Null and ‘all’ drops only if ALL values are null.thresh: thresh takes integer value which tells minimum amount of na values to drop.subset: It’s an array which limits the dropping process to passed rows/columns through list.inplace: It is a boolean which makes the changes in data frame itself if True. For link to CSV file Used in Code, click here. Example #1: Dropping Rows with at least 1 null value. Data frame is read and all rows with any Null values are dropped. The size of old and new data frames is compared to see how many rows had at least 1 Null value. # importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # making new data frame with dropped NA valuesnew_data = data.dropna(axis = 0, how ='any') # comparing sizes of data framesprint("Old data frame length:", len(data), "\nNew data frame length:", len(new_data), "\nNumber of rows with at least 1 NA value: ", (len(data)-len(new_data))) Output: Old data frame length: 458 New data frame length: 364 Number of rows with at least 1 NA value: 94 Since the difference is 94, there were 94 rows which had at least 1 Null value in any column. Example #2: Changing axis and using how and inplace Parameters Two data frames are made. A column with all values = none is added to the new Data frame. Column names are verified to see if the Null column was inserted properly. Then Number of columns is compared before and after dropping NaN values. # importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # making a copy of old data framenew = pd.read_csv("nba.csv") # creating a value with all null values in new data framenew["Null Column"]= None # checking if column is inserted properly print(data.columns.values, "\n", new.columns.values) # comparing values before dropping null columnprint("\nColumn number before dropping Null column\n", len(data.dtypes), len(new.dtypes)) # dropping column with all null valuesnew.dropna(axis = 1, how ='all', inplace = True) # comparing values after dropping null columnprint("\nColumn number after dropping Null column\n", len(data.dtypes), len(new.dtypes)) Output: ['Name' 'Team' 'Number' 'Position' 'Age' 'Height' 'Weight' 'College' 'Salary'] ['Name' 'Team' 'Number' 'Position' 'Age' 'Height' 'Weight' 'College' 'Salary' 'Null Column'] Column number before dropping Null column 9 10 Column number after dropping Null column 9 9 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jul, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 434, "s": 242, "text": "Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Pandas dropna() method allows the user to analyze and drop Rows/Columns with Null values in different ways." }, { "code": null, "e": 442, "s": 434, "text": "Syntax:" }, { "code": null, "e": 523, "s": 442, "text": "DataFrameName.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)" }, { "code": null, "e": 535, "s": 523, "text": "Parameters:" }, { "code": null, "e": 1068, "s": 535, "text": "axis: axis takes int or string value for rows/columns. Input can be 0 or 1 for Integer and ‘index’ or ‘columns’ for String.how: how takes string value of two kinds only (‘any’ or ‘all’). ‘any’ drops the row/column if ANY value is Null and ‘all’ drops only if ALL values are null.thresh: thresh takes integer value which tells minimum amount of na values to drop.subset: It’s an array which limits the dropping process to passed rows/columns through list.inplace: It is a boolean which makes the changes in data frame itself if True." }, { "code": null, "e": 1115, "s": 1068, "text": "For link to CSV file Used in Code, click here." }, { "code": null, "e": 1169, "s": 1115, "text": "Example #1: Dropping Rows with at least 1 null value." }, { "code": null, "e": 1331, "s": 1169, "text": "Data frame is read and all rows with any Null values are dropped. The size of old and new data frames is compared to see how many rows had at least 1 Null value." }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # making new data frame with dropped NA valuesnew_data = data.dropna(axis = 0, how ='any') # comparing sizes of data framesprint(\"Old data frame length:\", len(data), \"\\nNew data frame length:\", len(new_data), \"\\nNumber of rows with at least 1 NA value: \", (len(data)-len(new_data)))", "e": 1738, "s": 1331, "text": null }, { "code": null, "e": 1746, "s": 1738, "text": "Output:" }, { "code": null, "e": 1850, "s": 1746, "text": "Old data frame length: 458 \nNew data frame length: 364 \nNumber of rows with at least 1 NA value: 94\n" }, { "code": null, "e": 1945, "s": 1850, "text": "Since the difference is 94, there were 94 rows which had at least 1 Null value in any column. " }, { "code": null, "e": 2008, "s": 1945, "text": "Example #2: Changing axis and using how and inplace Parameters" }, { "code": null, "e": 2246, "s": 2008, "text": "Two data frames are made. A column with all values = none is added to the new Data frame. Column names are verified to see if the Null column was inserted properly. Then Number of columns is compared before and after dropping NaN values." }, { "code": "# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # making a copy of old data framenew = pd.read_csv(\"nba.csv\") # creating a value with all null values in new data framenew[\"Null Column\"]= None # checking if column is inserted properly print(data.columns.values, \"\\n\", new.columns.values) # comparing values before dropping null columnprint(\"\\nColumn number before dropping Null column\\n\", len(data.dtypes), len(new.dtypes)) # dropping column with all null valuesnew.dropna(axis = 1, how ='all', inplace = True) # comparing values after dropping null columnprint(\"\\nColumn number after dropping Null column\\n\", len(data.dtypes), len(new.dtypes))", "e": 2968, "s": 2246, "text": null }, { "code": null, "e": 2976, "s": 2968, "text": "Output:" }, { "code": null, "e": 3249, "s": 2976, "text": "['Name' 'Team' 'Number' 'Position' 'Age' 'Height' 'Weight' 'College'\n 'Salary'] \n ['Name' 'Team' 'Number' 'Position' 'Age' 'Height' 'Weight' 'College'\n 'Salary' 'Null Column']\n\nColumn number before dropping Null column\n 9 10\n\nColumn number after dropping Null column\n 9 9\n" }, { "code": null, "e": 3264, "s": 3249, "text": "python-modules" }, { "code": null, "e": 3271, "s": 3264, "text": "Python" } ]
External Sorting - GeeksforGeeks
17 Sep, 2021 External sorting is a term for a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead, they must reside in the slower external memory (usually a hard drive). External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are read, sorted, and written out to a temporary file. In the merge phase, the sorted sub-files are combined into a single larger file.One example of external sorting is the external merge sort algorithm, which sorts chunks that each fit in RAM, then merges the sorted chunks together. We first divide the file into runs such that the size of a run is small enough to fit into main memory. Then sort each run in main memory using merge sort sorting algorithm. Finally merge the resulting runs together into successively bigger runs, until the file is sorted. Prerequisite for the algorithm/code: MergeSort: Used for sort individual runs (a run is part of file that is small enough to fit in main memory) Merge K Sorted Arrays: Used to merge sorted runs.Below are the steps used in C++ implementation. Inputs: input_file : Name of input file. input.txt output_file : Name of output file, output.txt run_size : Size of a run (can fit in RAM) num_ways : Number of runs to be merged Solution: The idea is very simple, All the elements cannot be sorted at once as the size is very large. So the data is divided into chunks and then sorted using merge sort. The sorted data is then dumped into files. As such huge amount of data cannot be handled altogether. Now After sorting the individual chunks. Sort the whole array by using the idea of merge k sorted arrays.Algorithm: Read input_file such that at most ‘run_size’ elements are read at a time. Do following for the every run read in an array.Sort the run using MergeSort.Store the sorted array in a file. Lets say ‘i’ for ith file.Merge the sorted files using the approach discussed merge k sorted arrays Read input_file such that at most ‘run_size’ elements are read at a time. Do following for the every run read in an array. Sort the run using MergeSort. Store the sorted array in a file. Lets say ‘i’ for ith file. Merge the sorted files using the approach discussed merge k sorted arrays Following is C++ implementation of the above steps. CPP // C++ program to implement// external sorting using// merge sort#include <bits/stdc++.h>using namespace std; struct MinHeapNode { // The element to be stored int element; // index of the array from which // the element is taken int i;}; // Prototype of a utility function// to swap two min heap nodesvoid swap(MinHeapNode* x, MinHeapNode* y); // A class for Min Heapclass MinHeap { // pointer to array of elements in heap MinHeapNode* harr; // size of min heap int heap_size; public: // Constructor: creates a min // heap of given size MinHeap(MinHeapNode a[], int size); // to heapify a subtree with // root at given index void MinHeapify(int); // to get index of left child // of node at index i int left(int i) { return (2 * i + 1); } // to get index of right child // of node at index i int right(int i) { return (2 * i + 2); } // to get the root MinHeapNode getMin() { return harr[0]; } // to replace root with new node // x and heapify() new root void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); }}; // Constructor: Builds a heap from// a given array a[] of given sizeMinHeap::MinHeap(MinHeapNode a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; }} // A recursive method to heapify// a subtree with root// at given index. This method// assumes that the// subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l].element < harr[i].element) smallest = l; if (r < heap_size && harr[r].element < harr[smallest].element) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(MinHeapNode* x, MinHeapNode* y){ MinHeapNode temp = *x; *x = *y; *y = temp;} // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ // Initial index of first subarray i = 0; // Initial index of second subarray j = 0; // Initial index of merged subarray k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) arr[k++] = L[i++]; else arr[k++] = R[j++]; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) arr[k++] = L[i++]; /* Copy the remaining elements of R[], if there are any */ while (j < n2) arr[k++] = R[j++];} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} FILE* openFile(char* fileName, char* mode){ FILE* fp = fopen(fileName, mode); if (fp == NULL) { perror("Error while opening the file.\n"); exit(EXIT_FAILURE); } return fp;} // Merges k sorted files. Names of files are assumed// to be 1, 2, 3, ... kvoid mergeFiles(char* output_file, int n, int k){ FILE* in[k]; for (int i = 0; i < k; i++) { char fileName[2]; // convert i to string snprintf(fileName, sizeof(fileName), "%d", i); // Open output files in read mode. in[i] = openFile(fileName, "r"); } // FINAL OUTPUT FILE FILE* out = openFile(output_file, "w"); // Create a min heap with k heap // nodes. Every heap node // has first element of scratch // output file MinHeapNode* harr = new MinHeapNode[k]; int i; for (i = 0; i < k; i++) { // break if no output file is empty and // index i will be no. of input files if (fscanf(in[i], "%d ", &harr[i].element) != 1) break; // Index of scratch output file harr[i].i = i; } // Create the heap MinHeap hp(harr, i); int count = 0; // Now one by one get the // minimum element from min // heap and replace it with // next element. // run till all filled input // files reach EOF while (count != i) { // Get the minimum element // and store it in output file MinHeapNode root = hp.getMin(); fprintf(out, "%d ", root.element); // Find the next element that // will replace current // root of heap. The next element // belongs to same // input file as the current min element. if (fscanf(in[root.i], "%d ", &root.element) != 1) { root.element = INT_MAX; count++; } // Replace root with next // element of input file hp.replaceMin(root); } // close input and output files for (int i = 0; i < k; i++) fclose(in[i]); fclose(out);} // Using a merge-sort algorithm,// create the initial runs// and divide them evenly among// the output filesvoid createInitialRuns( char* input_file, int run_size, int num_ways){ // For big input file FILE* in = openFile(input_file, "r"); // output scratch files FILE* out[num_ways]; char fileName[2]; for (int i = 0; i < num_ways; i++) { // convert i to string snprintf(fileName, sizeof(fileName), "%d", i); // Open output files in write mode. out[i] = openFile(fileName, "w"); } // allocate a dynamic array large enough // to accommodate runs of size run_size int* arr = (int*)malloc( run_size * sizeof(int)); bool more_input = true; int next_output_file = 0; int i; while (more_input) { // write run_size elements // into arr from input file for (i = 0; i < run_size; i++) { if (fscanf(in, "%d ", &arr[i]) != 1) { more_input = false; break; } } // sort array using merge sort mergeSort(arr, 0, i - 1); // write the records to the // appropriate scratch output file // can't assume that the loop // runs to run_size // since the last run's length // may be less than run_size for (int j = 0; j < i; j++) fprintf(out[next_output_file], "%d ", arr[j]); next_output_file++; } // close input and output files for (int i = 0; i < num_ways; i++) fclose(out[i]); fclose(in);} // For sorting data stored on diskvoid externalSort( char* input_file, char* output_file, int num_ways, int run_size){ // read the input file, // create the initial runs, // and assign the runs to // the scratch output files createInitialRuns(input_file, run_size, num_ways); // Merge the runs using // the K-way merging mergeFiles(output_file, run_size, num_ways);} // Driver program to test aboveint main(){ // No. of Partitions of input file. int num_ways = 10; // The size of each partition int run_size = 1000; char input_file[] = "input.txt"; char output_file[] = "output.txt"; FILE* in = openFile(input_file, "w"); srand(time(NULL)); // generate input for (int i = 0; i < num_ways * run_size; i++) fprintf(in, "%d ", rand()); fclose(in); externalSort(input_file, output_file, num_ways, run_size); return 0;} Complexity Analysis: Time Complexity: O(n * log n). Time taken for merge sort is O(runs * run_size * log run_size), which is equal to O(n log run_size). To merge the sorted arrays the time complexity is O(n * log runs). Therefore, the overall time complexity is O(n * log run_size + n * log runs). Since log run_size + log runs = log run_size*runs = log n, the result time complexity will be O(n * log n). Auxiliary space:O(run_size). run_size is the space needed to store the array. Note: This code won’t work on online compiler as it requires file creation permissions. When run local machine, it produces sample input file “input.txt” with 10000 random numbers. It sorts the numbers and puts the sorted numbers in a file “output.txt”. It also generates files with names 1, 2, .. to store sorted runs.References: https://en.wikipedia.org/wiki/External_sorting http://web.eecs.utk.edu/~leparker/Courses/CS302-Fall06/Notes/external-sorting2.html This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above andrew1234 smirnovpaxa Merge Sort Sorting Sorting Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort Quick Sort vs Merge Sort Stability in sorting algorithms Segregate 0s and 1s in an array Quickselect Algorithm Sorting in Java QuickSort using Random Pivoting Binary Insertion Sort Find whether an array is subset of another array | Added Method 5 Recursive Bubble Sort
[ { "code": null, "e": 24076, "s": 24048, "text": "\n17 Sep, 2021" }, { "code": null, "e": 25080, "s": 24076, "text": "External sorting is a term for a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead, they must reside in the slower external memory (usually a hard drive). External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are read, sorted, and written out to a temporary file. In the merge phase, the sorted sub-files are combined into a single larger file.One example of external sorting is the external merge sort algorithm, which sorts chunks that each fit in RAM, then merges the sorted chunks together. We first divide the file into runs such that the size of a run is small enough to fit into main memory. Then sort each run in main memory using merge sort sorting algorithm. Finally merge the resulting runs together into successively bigger runs, until the file is sorted. " }, { "code": null, "e": 25332, "s": 25080, "text": "Prerequisite for the algorithm/code: MergeSort: Used for sort individual runs (a run is part of file that is small enough to fit in main memory) Merge K Sorted Arrays: Used to merge sorted runs.Below are the steps used in C++ implementation. Inputs: " }, { "code": null, "e": 25503, "s": 25332, "text": "input_file : Name of input file. input.txt\noutput_file : Name of output file, output.txt\nrun_size : Size of a run (can fit in RAM)\nnum_ways : Number of runs to be merged" }, { "code": null, "e": 25895, "s": 25503, "text": "Solution: The idea is very simple, All the elements cannot be sorted at once as the size is very large. So the data is divided into chunks and then sorted using merge sort. The sorted data is then dumped into files. As such huge amount of data cannot be handled altogether. Now After sorting the individual chunks. Sort the whole array by using the idea of merge k sorted arrays.Algorithm: " }, { "code": null, "e": 26180, "s": 25895, "text": "Read input_file such that at most ‘run_size’ elements are read at a time. Do following for the every run read in an array.Sort the run using MergeSort.Store the sorted array in a file. Lets say ‘i’ for ith file.Merge the sorted files using the approach discussed merge k sorted arrays" }, { "code": null, "e": 26303, "s": 26180, "text": "Read input_file such that at most ‘run_size’ elements are read at a time. Do following for the every run read in an array." }, { "code": null, "e": 26333, "s": 26303, "text": "Sort the run using MergeSort." }, { "code": null, "e": 26394, "s": 26333, "text": "Store the sorted array in a file. Lets say ‘i’ for ith file." }, { "code": null, "e": 26468, "s": 26394, "text": "Merge the sorted files using the approach discussed merge k sorted arrays" }, { "code": null, "e": 26522, "s": 26468, "text": "Following is C++ implementation of the above steps. " }, { "code": null, "e": 26526, "s": 26522, "text": "CPP" }, { "code": "// C++ program to implement// external sorting using// merge sort#include <bits/stdc++.h>using namespace std; struct MinHeapNode { // The element to be stored int element; // index of the array from which // the element is taken int i;}; // Prototype of a utility function// to swap two min heap nodesvoid swap(MinHeapNode* x, MinHeapNode* y); // A class for Min Heapclass MinHeap { // pointer to array of elements in heap MinHeapNode* harr; // size of min heap int heap_size; public: // Constructor: creates a min // heap of given size MinHeap(MinHeapNode a[], int size); // to heapify a subtree with // root at given index void MinHeapify(int); // to get index of left child // of node at index i int left(int i) { return (2 * i + 1); } // to get index of right child // of node at index i int right(int i) { return (2 * i + 2); } // to get the root MinHeapNode getMin() { return harr[0]; } // to replace root with new node // x and heapify() new root void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); }}; // Constructor: Builds a heap from// a given array a[] of given sizeMinHeap::MinHeap(MinHeapNode a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; }} // A recursive method to heapify// a subtree with root// at given index. This method// assumes that the// subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l].element < harr[i].element) smallest = l; if (r < heap_size && harr[r].element < harr[smallest].element) smallest = r; if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); }} // A utility function to swap two elementsvoid swap(MinHeapNode* x, MinHeapNode* y){ MinHeapNode temp = *x; *x = *y; *y = temp;} // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ // Initial index of first subarray i = 0; // Initial index of second subarray j = 0; // Initial index of merged subarray k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) arr[k++] = L[i++]; else arr[k++] = R[j++]; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) arr[k++] = L[i++]; /* Copy the remaining elements of R[], if there are any */ while (j < n2) arr[k++] = R[j++];} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} FILE* openFile(char* fileName, char* mode){ FILE* fp = fopen(fileName, mode); if (fp == NULL) { perror(\"Error while opening the file.\\n\"); exit(EXIT_FAILURE); } return fp;} // Merges k sorted files. Names of files are assumed// to be 1, 2, 3, ... kvoid mergeFiles(char* output_file, int n, int k){ FILE* in[k]; for (int i = 0; i < k; i++) { char fileName[2]; // convert i to string snprintf(fileName, sizeof(fileName), \"%d\", i); // Open output files in read mode. in[i] = openFile(fileName, \"r\"); } // FINAL OUTPUT FILE FILE* out = openFile(output_file, \"w\"); // Create a min heap with k heap // nodes. Every heap node // has first element of scratch // output file MinHeapNode* harr = new MinHeapNode[k]; int i; for (i = 0; i < k; i++) { // break if no output file is empty and // index i will be no. of input files if (fscanf(in[i], \"%d \", &harr[i].element) != 1) break; // Index of scratch output file harr[i].i = i; } // Create the heap MinHeap hp(harr, i); int count = 0; // Now one by one get the // minimum element from min // heap and replace it with // next element. // run till all filled input // files reach EOF while (count != i) { // Get the minimum element // and store it in output file MinHeapNode root = hp.getMin(); fprintf(out, \"%d \", root.element); // Find the next element that // will replace current // root of heap. The next element // belongs to same // input file as the current min element. if (fscanf(in[root.i], \"%d \", &root.element) != 1) { root.element = INT_MAX; count++; } // Replace root with next // element of input file hp.replaceMin(root); } // close input and output files for (int i = 0; i < k; i++) fclose(in[i]); fclose(out);} // Using a merge-sort algorithm,// create the initial runs// and divide them evenly among// the output filesvoid createInitialRuns( char* input_file, int run_size, int num_ways){ // For big input file FILE* in = openFile(input_file, \"r\"); // output scratch files FILE* out[num_ways]; char fileName[2]; for (int i = 0; i < num_ways; i++) { // convert i to string snprintf(fileName, sizeof(fileName), \"%d\", i); // Open output files in write mode. out[i] = openFile(fileName, \"w\"); } // allocate a dynamic array large enough // to accommodate runs of size run_size int* arr = (int*)malloc( run_size * sizeof(int)); bool more_input = true; int next_output_file = 0; int i; while (more_input) { // write run_size elements // into arr from input file for (i = 0; i < run_size; i++) { if (fscanf(in, \"%d \", &arr[i]) != 1) { more_input = false; break; } } // sort array using merge sort mergeSort(arr, 0, i - 1); // write the records to the // appropriate scratch output file // can't assume that the loop // runs to run_size // since the last run's length // may be less than run_size for (int j = 0; j < i; j++) fprintf(out[next_output_file], \"%d \", arr[j]); next_output_file++; } // close input and output files for (int i = 0; i < num_ways; i++) fclose(out[i]); fclose(in);} // For sorting data stored on diskvoid externalSort( char* input_file, char* output_file, int num_ways, int run_size){ // read the input file, // create the initial runs, // and assign the runs to // the scratch output files createInitialRuns(input_file, run_size, num_ways); // Merge the runs using // the K-way merging mergeFiles(output_file, run_size, num_ways);} // Driver program to test aboveint main(){ // No. of Partitions of input file. int num_ways = 10; // The size of each partition int run_size = 1000; char input_file[] = \"input.txt\"; char output_file[] = \"output.txt\"; FILE* in = openFile(input_file, \"w\"); srand(time(NULL)); // generate input for (int i = 0; i < num_ways * run_size; i++) fprintf(in, \"%d \", rand()); fclose(in); externalSort(input_file, output_file, num_ways, run_size); return 0;}", "e": 34460, "s": 26526, "text": null }, { "code": null, "e": 34483, "s": 34460, "text": "Complexity Analysis: " }, { "code": null, "e": 34868, "s": 34483, "text": "Time Complexity: O(n * log n). Time taken for merge sort is O(runs * run_size * log run_size), which is equal to O(n log run_size). To merge the sorted arrays the time complexity is O(n * log runs). Therefore, the overall time complexity is O(n * log run_size + n * log runs). Since log run_size + log runs = log run_size*runs = log n, the result time complexity will be O(n * log n)." }, { "code": null, "e": 34946, "s": 34868, "text": "Auxiliary space:O(run_size). run_size is the space needed to store the array." }, { "code": null, "e": 35279, "s": 34946, "text": "Note: This code won’t work on online compiler as it requires file creation permissions. When run local machine, it produces sample input file “input.txt” with 10000 random numbers. It sorts the numbers and puts the sorted numbers in a file “output.txt”. It also generates files with names 1, 2, .. to store sorted runs.References: " }, { "code": null, "e": 35326, "s": 35279, "text": "https://en.wikipedia.org/wiki/External_sorting" }, { "code": null, "e": 35410, "s": 35326, "text": "http://web.eecs.utk.edu/~leparker/Courses/CS302-Fall06/Notes/external-sorting2.html" }, { "code": null, "e": 35579, "s": 35410, "text": "This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 35590, "s": 35579, "text": "andrew1234" }, { "code": null, "e": 35602, "s": 35590, "text": "smirnovpaxa" }, { "code": null, "e": 35613, "s": 35602, "text": "Merge Sort" }, { "code": null, "e": 35621, "s": 35613, "text": "Sorting" }, { "code": null, "e": 35629, "s": 35621, "text": "Sorting" }, { "code": null, "e": 35640, "s": 35629, "text": "Merge Sort" }, { "code": null, "e": 35738, "s": 35640, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35764, "s": 35738, "text": "C++ Program for QuickSort" }, { "code": null, "e": 35789, "s": 35764, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 35821, "s": 35789, "text": "Stability in sorting algorithms" }, { "code": null, "e": 35853, "s": 35821, "text": "Segregate 0s and 1s in an array" }, { "code": null, "e": 35875, "s": 35853, "text": "Quickselect Algorithm" }, { "code": null, "e": 35891, "s": 35875, "text": "Sorting in Java" }, { "code": null, "e": 35923, "s": 35891, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 35945, "s": 35923, "text": "Binary Insertion Sort" }, { "code": null, "e": 36011, "s": 35945, "text": "Find whether an array is subset of another array | Added Method 5" } ]
How do I view the auto_increment value for a table in MySQL?
In order to view the auto_increment value for a table, you can use SHOW TABLE command. The syntax is as follows SHOW TABLE STATUS LIKE 'yourTableName'\G The syntax is as follows SELECT `AUTO_INCREMENT` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = ‘yourDatabaseName’ AND `TABLE_NAME` =’yourTableName'; To understand the above syntaxes, let us create a table. The query to create a table is as follows mysql> create table viewAutoIncrementDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(20) -> ); Query OK, 0 rows affected (0.59 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into viewAutoIncrementDemo(UserName) values('John'); Query OK, 1 row affected (0.18 sec) mysql> insert into viewAutoIncrementDemo(UserName) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into viewAutoIncrementDemo(UserName) values('Bob'); Query OK, 1 row affected (0.08 sec) mysql> insert into viewAutoIncrementDemo(UserName) values('Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into viewAutoIncrementDemo(UserName) values('Mike'); Query OK, 1 row affected (0.14 sec) mysql> insert into viewAutoIncrementDemo(UserName) values('David'); Query OK, 1 row affected (0.16 sec) mysql> insert into viewAutoIncrementDemo(UserName) values('Larry'); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from viewAutoIncrementDemo; The following is the output +--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Sam | | 5 | Mike | | 6 | David | | 7 | Larry | +--------+----------+ 7 rows in set (0.00 sec) Here is the query to view the auto_increment value for a table mysql> SHOW TABLE STATUS LIKE 'viewAutoIncrementDemo'\G The following is the output *************************** 1. row *************************** Name: viewautoincrementdemo Engine: InnoDB Version: 10 Row_format: Dynamic Rows: 7 Avg_row_length: 2340 Data_length: 16384 Max_data_length: 0 Index_length: 0 Data_free: 0 Auto_increment: 8 Create_time: 2019-03-02 04:05:20 Update_time: 2019-03-02 04:06:11 Check_time: NULL Collation: utf8_general_ci Checksum: NULL Create_options: Comment: 1 row in set (0.08 sec) The following is the second query mysql> SELECT `AUTO_INCREMENT` -> FROM `information_schema`.`TABLES` -> WHERE `TABLE_SCHEMA` = 'sample' -> AND `TABLE_NAME` = 'viewAutoIncrementDemo'; The following is the output +----------------+ | AUTO_INCREMENT | +----------------+ | 8 | +----------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1149, "s": 1062, "text": "In order to view the auto_increment value for a table, you can use SHOW TABLE command." }, { "code": null, "e": 1174, "s": 1149, "text": "The syntax is as follows" }, { "code": null, "e": 1215, "s": 1174, "text": "SHOW TABLE STATUS LIKE 'yourTableName'\\G" }, { "code": null, "e": 1240, "s": 1215, "text": "The syntax is as follows" }, { "code": null, "e": 1385, "s": 1240, "text": "SELECT `AUTO_INCREMENT`\n FROM `information_schema`.`TABLES`\n WHERE `TABLE_SCHEMA` = ‘yourDatabaseName’\n AND `TABLE_NAME` =’yourTableName';" }, { "code": null, "e": 1484, "s": 1385, "text": "To understand the above syntaxes, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1661, "s": 1484, "text": "mysql> create table viewAutoIncrementDemo\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1754, "s": 1661, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2476, "s": 1754, "text": "mysql> insert into viewAutoIncrementDemo(UserName) values('John');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into viewAutoIncrementDemo(UserName) values('Carol');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into viewAutoIncrementDemo(UserName) values('Bob');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into viewAutoIncrementDemo(UserName) values('Sam');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into viewAutoIncrementDemo(UserName) values('Mike');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into viewAutoIncrementDemo(UserName) values('David');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into viewAutoIncrementDemo(UserName) values('Larry');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2561, "s": 2476, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2604, "s": 2561, "text": "mysql> select *from viewAutoIncrementDemo;" }, { "code": null, "e": 2632, "s": 2604, "text": "The following is the output" }, { "code": null, "e": 2899, "s": 2632, "text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n| 4 | Sam |\n| 5 | Mike |\n| 6 | David |\n| 7 | Larry |\n+--------+----------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 2962, "s": 2899, "text": "Here is the query to view the auto_increment value for a table" }, { "code": null, "e": 3018, "s": 2962, "text": "mysql> SHOW TABLE STATUS LIKE 'viewAutoIncrementDemo'\\G" }, { "code": null, "e": 3046, "s": 3018, "text": "The following is the output" }, { "code": null, "e": 3566, "s": 3046, "text": "*************************** 1. row ***************************\n Name: viewautoincrementdemo\n Engine: InnoDB\n Version: 10\n Row_format: Dynamic\n Rows: 7\n Avg_row_length: 2340\n Data_length: 16384\nMax_data_length: 0\n Index_length: 0\n Data_free: 0\n Auto_increment: 8\n Create_time: 2019-03-02 04:05:20\n Update_time: 2019-03-02 04:06:11\n Check_time: NULL\n Collation: utf8_general_ci\n Checksum: NULL\n Create_options:\n Comment:\n1 row in set (0.08 sec)" }, { "code": null, "e": 3600, "s": 3566, "text": "The following is the second query" }, { "code": null, "e": 3760, "s": 3600, "text": "mysql> SELECT `AUTO_INCREMENT`\n -> FROM `information_schema`.`TABLES`\n -> WHERE `TABLE_SCHEMA` = 'sample'\n -> AND `TABLE_NAME` = 'viewAutoIncrementDemo';" }, { "code": null, "e": 3788, "s": 3760, "text": "The following is the output" }, { "code": null, "e": 3907, "s": 3788, "text": "+----------------+\n| AUTO_INCREMENT |\n+----------------+\n| 8 |\n+----------------+\n1 row in set (0.00 sec)" } ]
Compare only day and month with date field in MySQL?
You can compare only day and month with date field in MySQL with the help of DATE_FORMAT(). The syntax is as follows select *from yourTableName WHERE DATE_FORMAT(yourColumnName, '%m-%d') = DATE_FORMAT('yourValue', '%m-%d') and yourCondition; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table compareDayAndMonthDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> compareDayAndTime date -> ); Query OK, 0 rows affected (0.49 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-01-31'); Query OK, 1 row affected (0.20 sec) mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-10-11'); Query OK, 1 row affected (0.16 sec) mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2016-09-12'); Query OK, 1 row affected (0.08 sec) mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2017-04-25'); Query OK, 1 row affected (0.08 sec) mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2018-12-25'); Query OK, 1 row affected (0.08 sec) mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2019-02-27'); Query OK, 1 row affected (0.07 sec) Display all records from the table using select statement. The query is as follows mysql> select *from compareDayAndMonthDemo; The following is the output +----+-------------------+ | Id | compareDayAndTime | +----+-------------------+ | 1 | 2014-01-31 | | 2 | 2014-10-11 | | 3 | 2016-09-12 | | 4 | 2017-04-25 | | 5 | 2018-12-25 | | 6 | 2019-02-27 | +----+-------------------+ 6 rows in set (0.00 sec) Here is the query to compare only day and month mysql> select *from compareDayAndMonthDemo -> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1; The following is the output +----+-------------------+ | Id | compareDayAndTime | +----+-------------------+ | 1 | 2014-01-31 | +----+-------------------+ 1 row in set (0.00 sec) If you want only day and month, then use the below query mysql> select DATE_FORMAT(compareDayAndTime, '%m-%d') AS DayAndMonthOnly from compareDayAndMonthDemo -> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1; The following is the output +-----------------+ | DayAndMonthOnly | +-----------------+ | 01-31 | +-----------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1154, "s": 1062, "text": "You can compare only day and month with date field in MySQL with the help of DATE_FORMAT()." }, { "code": null, "e": 1179, "s": 1154, "text": "The syntax is as follows" }, { "code": null, "e": 1304, "s": 1179, "text": "select *from yourTableName\nWHERE DATE_FORMAT(yourColumnName, '%m-%d') = DATE_FORMAT('yourValue', '%m-%d') and yourCondition;" }, { "code": null, "e": 1401, "s": 1304, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1577, "s": 1401, "text": "mysql> create table compareDayAndMonthDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> compareDayAndTime date\n -> );\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 1632, "s": 1577, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1656, "s": 1632, "text": "The query is as follows" }, { "code": null, "e": 2370, "s": 1656, "text": "mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-01-31');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-10-11');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2016-09-12');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2017-04-25');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2018-12-25');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2019-02-27');\nQuery OK, 1 row affected (0.07 sec)" }, { "code": null, "e": 2429, "s": 2370, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2453, "s": 2429, "text": "The query is as follows" }, { "code": null, "e": 2497, "s": 2453, "text": "mysql> select *from compareDayAndMonthDemo;" }, { "code": null, "e": 2525, "s": 2497, "text": "The following is the output" }, { "code": null, "e": 2820, "s": 2525, "text": "+----+-------------------+\n| Id | compareDayAndTime |\n+----+-------------------+\n| 1 | 2014-01-31 |\n| 2 | 2014-10-11 |\n| 3 | 2016-09-12 |\n| 4 | 2017-04-25 |\n| 5 | 2018-12-25 |\n| 6 | 2019-02-27 |\n+----+-------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2868, "s": 2820, "text": "Here is the query to compare only day and month" }, { "code": null, "e": 3007, "s": 2868, "text": "mysql> select *from compareDayAndMonthDemo\n-> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1;" }, { "code": null, "e": 3035, "s": 3007, "text": "The following is the output" }, { "code": null, "e": 3194, "s": 3035, "text": "+----+-------------------+\n| Id | compareDayAndTime |\n+----+-------------------+\n| 1 | 2014-01-31 |\n+----+-------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3251, "s": 3194, "text": "If you want only day and month, then use the below query" }, { "code": null, "e": 3448, "s": 3251, "text": "mysql> select DATE_FORMAT(compareDayAndTime, '%m-%d') AS DayAndMonthOnly from compareDayAndMonthDemo\n-> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1;" }, { "code": null, "e": 3476, "s": 3448, "text": "The following is the output" }, { "code": null, "e": 3600, "s": 3476, "text": "+-----------------+\n| DayAndMonthOnly |\n+-----------------+\n| 01-31 |\n+-----------------+\n1 row in set (0.00 sec)" } ]
Two Pointers Approach — Python Code | by Amit Singh Rathore | Towards Data Science
Two are better than one if they act as one. Two pointer algorithm is one of the most commonly asked questions in any programming interview. This approach optimizes the runtime by utilizing some order (not necessarily sorting) of the data. It is generally applied on lists (arrays) and linked lists. This is generally used to search pairs in a sorted array. This approach works in constant space. In this technique pointers represent either index or an iteration attribute like node’s next. As in the above pic, the two-pointer approach has three main steps: Pointer Initialization — Starting points. Pointers can be at any place depending upon what we are trying to achieve. In the left part of the pic, we have both pointers starting at the same position i.e. start of the linked list. In the right part of the pic, we have pointers at extreme ends one at starting index and another one at the last index. Pointer movement — This will decide how we converge towards the solution. Pointer can move in the same direction (left in above pic) or they can move in the opposite direction (right in the above pic). Also in the left part of the pic, we have different increments for the pointers(top (slow) with 1 unit bottom (fast) with 2 units). Stop condition — This decides when do we stop. In the left part, we continue till we reach a node whose next element is None. In the right one, we continue till our start is less than the end (i <j). Note: Sliding window is another variant of two pointer approach. Let see how we use the above logic by solving some problems. Reverse an array in place. Implementation in Python: def reverseArray(array): start, end = 0, len(array)-1 while start< end: array[start], array[end] = array[end] , array[start] start += 1 end -= 1 array = [10, 20, 30, 40, 50] reverseArray(array)print(array) Given an integer array sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Implementation in Python: def sortedSquares(nums): n = len(nums) start, end = 0, n-1 res = [0]*n idx = n-1 while end > -1 and idx >-1: if abs(nums[start]) > abs(nums[end]): res[idx] = nums[start] * nums[start] start +=1 else: res[idx] = nums[end] * nums[end] end -= 1 idx -= 1 return res Finding cycle in Linked list: Implementation in Python: class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): return str(self.val)def hasCycle(head): if not head or not head.next: return False p1 = head p2 = head.next while p2: p2 = p2.next if p2: p2 = p2.next if not p2: return False p1 = p1.next if p1==p2: return Truelt = [ListNode(item) for item in [3,2,0,-4]]head = lt[0]head.next = lt[1]lt[1].next= lt[2]lt[2].next = lt[3]lt[3].next = lt[1] print(hasCycle(head)) Note: In the above problem there was no sorting of nodes. Given a string s, find the length of the longest substring without repeating characters. Implementation in Python: def lengthOfLongestSubstring(s): seen, n = set(), len(s) right, res = -1, 0 for left in range(n): print(left, right, s[left: right+1], seen) while right + 1 < n and s[right+1] not in seen: right += 1 seen.add(s[right]) res = max(res, right - left + 1) print( s[left: right+1]) if right == n - 1: break seen.discard(s[left]) return res print(lengthOfLongestSubstring("abcabcbb")) Given three sorted arrays A, B, and C of not necessarily the same sizes. Calculate the minimum absolute difference between the maximum and minimum number of any triplet A[i], B[j], C[k] such that they belong to arrays A, B and C respectively, i.e., minimize (max(A[i], B[j], C[k]) — min(A[i], B[j], C[k])) Implementation in Python: def solve(A, B, C): i , j, k = 0, 0, 0 m, n, p = len(A), len(B), len(C) min_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) while i < m and j < n and k < p: curr_diff = abs(max(A[i],B[j],C[k])-min(A[i],B[j],C[k])) if curr_diff < min_diff: min_diff = curr_diff min_term = min(A[i], B[j], C[k]) if A[i] == min_term: i += 1 elif B[j] == min_term: j += 1 else: k += 1 return min_diffA = [1,4,5,8,10]B = [6,9,15]C = [2,3,6,6]print(solve(A, B, C)) Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Implementation in Python: def maxArea(height): l, r, max_area = 0, len(height)-1, 0 while l<r: base = r-l if height[r] >= height[l]: h = height[l] l+=1 else: h = height[r] r-=1 print(l,r) if h * base > max_area: max_area = h * base return max_area Note: In the last problem, the array was not sorted but still two pointer approach was applicable. Hope this helped and encourages you to try out this technique if not done already. See below for Further practice problems: Same direction movement problems: Find max of any contiguous subarray size kRemove duplicates from sorted arrayMerge sorted array Opposite direction movement problems: Two Sum IIValid PalindromeMove zerosRemove duplicate element in sorted array
[ { "code": null, "e": 216, "s": 172, "text": "Two are better than one if they act as one." }, { "code": null, "e": 568, "s": 216, "text": "Two pointer algorithm is one of the most commonly asked questions in any programming interview. This approach optimizes the runtime by utilizing some order (not necessarily sorting) of the data. It is generally applied on lists (arrays) and linked lists. This is generally used to search pairs in a sorted array. This approach works in constant space." }, { "code": null, "e": 662, "s": 568, "text": "In this technique pointers represent either index or an iteration attribute like node’s next." }, { "code": null, "e": 730, "s": 662, "text": "As in the above pic, the two-pointer approach has three main steps:" }, { "code": null, "e": 1079, "s": 730, "text": "Pointer Initialization — Starting points. Pointers can be at any place depending upon what we are trying to achieve. In the left part of the pic, we have both pointers starting at the same position i.e. start of the linked list. In the right part of the pic, we have pointers at extreme ends one at starting index and another one at the last index." }, { "code": null, "e": 1413, "s": 1079, "text": "Pointer movement — This will decide how we converge towards the solution. Pointer can move in the same direction (left in above pic) or they can move in the opposite direction (right in the above pic). Also in the left part of the pic, we have different increments for the pointers(top (slow) with 1 unit bottom (fast) with 2 units)." }, { "code": null, "e": 1613, "s": 1413, "text": "Stop condition — This decides when do we stop. In the left part, we continue till we reach a node whose next element is None. In the right one, we continue till our start is less than the end (i <j)." }, { "code": null, "e": 1678, "s": 1613, "text": "Note: Sliding window is another variant of two pointer approach." }, { "code": null, "e": 1739, "s": 1678, "text": "Let see how we use the above logic by solving some problems." }, { "code": null, "e": 1766, "s": 1739, "text": "Reverse an array in place." }, { "code": null, "e": 1792, "s": 1766, "text": "Implementation in Python:" }, { "code": null, "e": 2031, "s": 1792, "text": "def reverseArray(array): start, end = 0, len(array)-1 while start< end: array[start], array[end] = array[end] , array[start] start += 1 end -= 1 array = [10, 20, 30, 40, 50] reverseArray(array)print(array)" }, { "code": null, "e": 2164, "s": 2031, "text": "Given an integer array sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order." }, { "code": null, "e": 2190, "s": 2164, "text": "Implementation in Python:" }, { "code": null, "e": 2543, "s": 2190, "text": "def sortedSquares(nums): n = len(nums) start, end = 0, n-1 res = [0]*n idx = n-1 while end > -1 and idx >-1: if abs(nums[start]) > abs(nums[end]): res[idx] = nums[start] * nums[start] start +=1 else: res[idx] = nums[end] * nums[end] end -= 1 idx -= 1 return res" }, { "code": null, "e": 2573, "s": 2543, "text": "Finding cycle in Linked list:" }, { "code": null, "e": 2599, "s": 2573, "text": "Implementation in Python:" }, { "code": null, "e": 3198, "s": 2599, "text": "class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): return str(self.val)def hasCycle(head): if not head or not head.next: return False p1 = head p2 = head.next while p2: p2 = p2.next if p2: p2 = p2.next if not p2: return False p1 = p1.next if p1==p2: return Truelt = [ListNode(item) for item in [3,2,0,-4]]head = lt[0]head.next = lt[1]lt[1].next= lt[2]lt[2].next = lt[3]lt[3].next = lt[1] print(hasCycle(head))" }, { "code": null, "e": 3256, "s": 3198, "text": "Note: In the above problem there was no sorting of nodes." }, { "code": null, "e": 3345, "s": 3256, "text": "Given a string s, find the length of the longest substring without repeating characters." }, { "code": null, "e": 3371, "s": 3345, "text": "Implementation in Python:" }, { "code": null, "e": 3840, "s": 3371, "text": "def lengthOfLongestSubstring(s): seen, n = set(), len(s) right, res = -1, 0 for left in range(n): print(left, right, s[left: right+1], seen) while right + 1 < n and s[right+1] not in seen: right += 1 seen.add(s[right]) res = max(res, right - left + 1) print( s[left: right+1]) if right == n - 1: break seen.discard(s[left]) return res print(lengthOfLongestSubstring(\"abcabcbb\"))" }, { "code": null, "e": 4146, "s": 3840, "text": "Given three sorted arrays A, B, and C of not necessarily the same sizes. Calculate the minimum absolute difference between the maximum and minimum number of any triplet A[i], B[j], C[k] such that they belong to arrays A, B and C respectively, i.e., minimize (max(A[i], B[j], C[k]) — min(A[i], B[j], C[k]))" }, { "code": null, "e": 4172, "s": 4146, "text": "Implementation in Python:" }, { "code": null, "e": 4725, "s": 4172, "text": "def solve(A, B, C): i , j, k = 0, 0, 0 m, n, p = len(A), len(B), len(C) min_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) while i < m and j < n and k < p: curr_diff = abs(max(A[i],B[j],C[k])-min(A[i],B[j],C[k])) if curr_diff < min_diff: min_diff = curr_diff min_term = min(A[i], B[j], C[k]) if A[i] == min_term: i += 1 elif B[j] == min_term: j += 1 else: k += 1 return min_diffA = [1,4,5,8,10]B = [6,9,15]C = [2,3,6,6]print(solve(A, B, C))" }, { "code": null, "e": 5037, "s": 4725, "text": "Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water." }, { "code": null, "e": 5063, "s": 5037, "text": "Implementation in Python:" }, { "code": null, "e": 5385, "s": 5063, "text": "def maxArea(height): l, r, max_area = 0, len(height)-1, 0 while l<r: base = r-l if height[r] >= height[l]: h = height[l] l+=1 else: h = height[r] r-=1 print(l,r) if h * base > max_area: max_area = h * base return max_area" }, { "code": null, "e": 5484, "s": 5385, "text": "Note: In the last problem, the array was not sorted but still two pointer approach was applicable." }, { "code": null, "e": 5608, "s": 5484, "text": "Hope this helped and encourages you to try out this technique if not done already. See below for Further practice problems:" }, { "code": null, "e": 5642, "s": 5608, "text": "Same direction movement problems:" }, { "code": null, "e": 5738, "s": 5642, "text": "Find max of any contiguous subarray size kRemove duplicates from sorted arrayMerge sorted array" }, { "code": null, "e": 5776, "s": 5738, "text": "Opposite direction movement problems:" } ]
Write a program in Python to split the date column into day, month, year in multiple columns of a given dataframe
Assume, you have a dataframe and the result for a date, month, year column is, date day month year 0 17/05/2002 17 05 2002 1 16/02/1990 16 02 1990 2 25/09/1980 25 09 1980 3 11/05/2000 11 05 2000 4 17/09/1986 17 09 1986 To solve this, we will follow the steps given below − Create a list of dates and assign into dataframe. Create a list of dates and assign into dataframe. Apply str.split function inside ‘/’ delimiter to df[‘date’] column. Assign the result to df[[“day”, “month”, “year”]]. Apply str.split function inside ‘/’ delimiter to df[‘date’] column. Assign the result to df[[“day”, “month”, “year”]]. Let’s check the following code to get a better understanding − import pandas as pd df = pd.DataFrame({ 'date': ['17/05/2002','16/02/1990','25/09/1980','11/05/2000','17/09/1986'] }) print("Original DataFrame:") print(df) df[["day", "month", "year"]] = df["date"].str.split("/", expand = True) print("\nNew DataFrame:") print(df) Original DataFrame: date 0 17/05/2002 1 16/02/1990 2 25/09/1980 3 11/05/2000 4 17/09/1986 New DataFrame: date day month year 0 17/05/2002 17 05 2002 1 16/02/1990 16 02 1990 2 25/09/1980 25 09 1980 3 11/05/2000 11 05 2000 4 17/09/1986 17 09 1986
[ { "code": null, "e": 1141, "s": 1062, "text": "Assume, you have a dataframe and the result for a date, month, year column is," }, { "code": null, "e": 1315, "s": 1141, "text": " date day month year\n0 17/05/2002 17 05 2002\n1 16/02/1990 16 02 1990\n2 25/09/1980 25 09 1980\n3 11/05/2000 11 05 2000\n4 17/09/1986 17 09 1986" }, { "code": null, "e": 1369, "s": 1315, "text": "To solve this, we will follow the steps given below −" }, { "code": null, "e": 1419, "s": 1369, "text": "Create a list of dates and assign into dataframe." }, { "code": null, "e": 1469, "s": 1419, "text": "Create a list of dates and assign into dataframe." }, { "code": null, "e": 1588, "s": 1469, "text": "Apply str.split function inside ‘/’ delimiter to df[‘date’] column. Assign the result to df[[“day”, “month”, “year”]]." }, { "code": null, "e": 1707, "s": 1588, "text": "Apply str.split function inside ‘/’ delimiter to df[‘date’] column. Assign the result to df[[“day”, “month”, “year”]]." }, { "code": null, "e": 1770, "s": 1707, "text": "Let’s check the following code to get a better understanding −" }, { "code": null, "e": 2044, "s": 1770, "text": "import pandas as pd\ndf = pd.DataFrame({\n 'date': ['17/05/2002','16/02/1990','25/09/1980','11/05/2000','17/09/1986']\n })\nprint(\"Original DataFrame:\")\nprint(df)\ndf[[\"day\", \"month\", \"year\"]] = df[\"date\"].str.split(\"/\", expand = True)\nprint(\"\\nNew DataFrame:\")\nprint(df)" }, { "code": null, "e": 2317, "s": 2044, "text": "Original DataFrame:\n date\n0 17/05/2002\n1 16/02/1990\n2 25/09/1980\n3 11/05/2000\n4 17/09/1986\nNew DataFrame:\n date day month year\n0 17/05/2002 17 05 2002\n1 16/02/1990 16 02 1990\n2 25/09/1980 25 09 1980\n3 11/05/2000 11 05 2000\n4 17/09/1986 17 09 1986" } ]
Hashtable Implementation with equals and hashcode Method in Java - GeeksforGeeks
20 Sep, 2021 To implement a hash table, we should use the hash table class, which will map keys to the values. The key or values of the hash table should be a non-null object. In order to store and retrieve data from the hash table, the non-null objects, that are used as keys must implement the hashCode() method and the equals() method. Hashtable produces output in unordered and unsorted form. Example 1: In the following example, we are using Integer as keys, and Student object as values. To avoid duplicate keys, it has implemented hashCode() and equals() methods. In case, if we enter duplicate key then the hashtable eliminates the duplicate keys automatically. Java // Java Programs to implement hashtable with// equals() and hashcode() method // Importing hashtable and Scanner classes// from java.util packageimport java.util.Hashtable;import java.util.Scanner; // Class 1// Helper classclass Student { // Initializing the instance variables // of this class private int sid; private String name; private String mobno; // Constructor of student class // to initialize the variable values public Student(int sid, String name, String mobno) { // Super keyword refers to parent object super(); // This keyword refers to current object // in a constructor this.sid = sid; this.name = name; this.mobno = mobno; } // Method 1 // getter for Sid public int getSid() { return sid; } // Method 2 // setter for Sid public void setSid(int sid) { this.sid = sid; } // Method 3 // getter for name public String getName() { return name; } // Method 4 // setter for name public void setName(String name) { this.name = name; } // Method 5 // getter for mobno public String getMobno() { return mobno; } // Method 6 // setter for mobno public void setMobno(String mobno) { this.mobno = mobno; } // Now, overriding methods // Overriding of hashCode // @Override public int hashCode() { return this.getSid(); } // Overriding of equals // @Override public boolean equals(Object o) { if (o instanceof Student) { return (this.sid) == (((Student)o).sid); } return false; } // Overriding of toString() method // @Override public String toString() { return "id=" + sid + ", name=" + name + ", mobno=" + mobno; }} // Class 2// Main class for hashtableExamplepublic class GFG { // Main driver method public static void main(String a[]) { // Initializing the hashtable with // key as integer and value as Student object // Creating an Hashtable object // Declaring object of Integer and String type Hashtable<Integer, Student> list = new Hashtable<Integer, Student>(); // Adding elements to the hashtable // Custom inputs list.put(101, new Student(101, "Ram", "9876543201")); list.put(102, new Student(102, "Shyam", "8907685432")); list.put(103, new Student(103, "Mohan", "8907896785")); list.put(104, new Student(104, "Lakshman", "8909006524")); list.put(105, new Student(105, "Raman", "6789054321")); // Display message System.out.println("Traversing the hash table"); // Traversing hashtable using for-each loop for (Student i : list.values()) { System.out.println(i); } // New line System.out.println(); // Display message System.out.println( "Search the student by student id"); // New line System.out.println(); // Display message System.out.println("Enter the student id : "); // Custom value in a variable is assigned int temp = 104; // Display message System.out.println("104"); // Traversing hashtable using for-each loop for (Student s : list.values()) { if (s.getSid() == temp) { // If student found, simply print the // student details System.out.println("Student is : " + s); // Exit the program System.exit(0); } } // If student not found execute the command // Print the display message System.out.println("Student not found.."); }} Traversing the hash table id=105, name=Raman, mobno=6789054321 id=104, name=Lakshman, mobno=8909006524 id=103, name=Mohan, mobno=8907896785 id=102, name=Shyam, mobno=8907685432 id=101, name=Ram, mobno=9876543201 Search the student by student id Enter the student id : 104 Student is : id=104, name=Lakshman, mobno=8909006524 Example 2 Here in this hashtable, string as keys, and Student object as values. To avoid duplicate keys, it has implemented hashCode() and equals() methods. In case, if we enter the duplicate key then the hashtable eliminates the duplicate keys automatically Java // Main class import java.util.Hashtable;import java.util.Scanner; public class HashtableExample2 { public static void main(String a[]) { // Initializing the hashtable with // key as String and values as Student object Hashtable<String, Student> list = new Hashtable<String, Student>(); list.put("Ram", new Student(1, "Ram", "8907654321")); list.put("Sita", new Student(2, "Sita", "9809876543")); list.put("Mohan", new Student(3, "Mohan", "9098765421")); list.put("Soham", new Student(4, "Soham", "7898790678")); list.put("Lakhan", new Student(5, "Lakhan", "7890567845")); // Traversing the hashtable using for-each loop System.out.println("Traversing the hash table"); for (Student i : list.values()) { System.out.println(i); } System.out.println(); // Search the student using their names System.out.println( "Search the student by student id"); System.out.println(); System.out.println("Enter the student id : "); int temp = 3; System.out.println("3"); for (Student s : list.values()) { if (s.getRollno() == temp) { // If found, then print the student details System.out.println("Student is : " + s); // Terminate the program System.exit(0); } } // If student not found, print that there is no // student System.out.println("Student not found.."); }} // Student class class Student { // Initializing the instance variables private int rollno; private String name; private String mobno; // Constructor to initialize the values of variables public Student(int rollno, String name, String mobno) { super(); this.rollno = rollno; this.name = name; this.mobno = mobno; } // getter for roll no public int getRollno() { return rollno; } // setter for roll no public void setRollno(int rollno) { this.rollno = rollno; } // getter for name public String getName() { return name; } // setter for name public void setName(String name) { this.name = name; } // getter for mobno public String getMobno() { return mobno; } // setter for mobno public void setMobno(String mobno) { this.mobno = mobno; } // Overriding of hashCode @Override public int hashCode() { return this.getRollno(); } // Overriding of equals // @Override public boolean equals(Object o) { if (o instanceof Student) { return (this.rollno) == (((Student)o).rollno); } return false; } // Overriding of toString @Override public String toString() { return "Rollno=" + rollno + ", name=" + name + ", mobno=" + mobno; }} Traversing the hash table Rollno=2, name=Sita, mobno=9809876543 Rollno=3, name=Mohan, mobno=9098765421 Rollno=5, name=Lakhan, mobno=7890567845 Rollno=4, name=Soham, mobno=7898790678 Rollno=1, name=Ram, mobno=8907654321 Search the student by student id Enter the student id : 3 Student is : Rollno=3, name=Mohan, mobno=9098765421 gulshankumarar231 Java-Collections Java-HashTable Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Generics in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23948, "s": 23920, "text": "\n20 Sep, 2021" }, { "code": null, "e": 24332, "s": 23948, "text": "To implement a hash table, we should use the hash table class, which will map keys to the values. The key or values of the hash table should be a non-null object. In order to store and retrieve data from the hash table, the non-null objects, that are used as keys must implement the hashCode() method and the equals() method. Hashtable produces output in unordered and unsorted form." }, { "code": null, "e": 24344, "s": 24332, "text": "Example 1: " }, { "code": null, "e": 24606, "s": 24344, "text": "In the following example, we are using Integer as keys, and Student object as values. To avoid duplicate keys, it has implemented hashCode() and equals() methods. In case, if we enter duplicate key then the hashtable eliminates the duplicate keys automatically." }, { "code": null, "e": 24611, "s": 24606, "text": "Java" }, { "code": "// Java Programs to implement hashtable with// equals() and hashcode() method // Importing hashtable and Scanner classes// from java.util packageimport java.util.Hashtable;import java.util.Scanner; // Class 1// Helper classclass Student { // Initializing the instance variables // of this class private int sid; private String name; private String mobno; // Constructor of student class // to initialize the variable values public Student(int sid, String name, String mobno) { // Super keyword refers to parent object super(); // This keyword refers to current object // in a constructor this.sid = sid; this.name = name; this.mobno = mobno; } // Method 1 // getter for Sid public int getSid() { return sid; } // Method 2 // setter for Sid public void setSid(int sid) { this.sid = sid; } // Method 3 // getter for name public String getName() { return name; } // Method 4 // setter for name public void setName(String name) { this.name = name; } // Method 5 // getter for mobno public String getMobno() { return mobno; } // Method 6 // setter for mobno public void setMobno(String mobno) { this.mobno = mobno; } // Now, overriding methods // Overriding of hashCode // @Override public int hashCode() { return this.getSid(); } // Overriding of equals // @Override public boolean equals(Object o) { if (o instanceof Student) { return (this.sid) == (((Student)o).sid); } return false; } // Overriding of toString() method // @Override public String toString() { return \"id=\" + sid + \", name=\" + name + \", mobno=\" + mobno; }} // Class 2// Main class for hashtableExamplepublic class GFG { // Main driver method public static void main(String a[]) { // Initializing the hashtable with // key as integer and value as Student object // Creating an Hashtable object // Declaring object of Integer and String type Hashtable<Integer, Student> list = new Hashtable<Integer, Student>(); // Adding elements to the hashtable // Custom inputs list.put(101, new Student(101, \"Ram\", \"9876543201\")); list.put(102, new Student(102, \"Shyam\", \"8907685432\")); list.put(103, new Student(103, \"Mohan\", \"8907896785\")); list.put(104, new Student(104, \"Lakshman\", \"8909006524\")); list.put(105, new Student(105, \"Raman\", \"6789054321\")); // Display message System.out.println(\"Traversing the hash table\"); // Traversing hashtable using for-each loop for (Student i : list.values()) { System.out.println(i); } // New line System.out.println(); // Display message System.out.println( \"Search the student by student id\"); // New line System.out.println(); // Display message System.out.println(\"Enter the student id : \"); // Custom value in a variable is assigned int temp = 104; // Display message System.out.println(\"104\"); // Traversing hashtable using for-each loop for (Student s : list.values()) { if (s.getSid() == temp) { // If student found, simply print the // student details System.out.println(\"Student is : \" + s); // Exit the program System.exit(0); } } // If student not found execute the command // Print the display message System.out.println(\"Student not found..\"); }}", "e": 28413, "s": 24611, "text": null }, { "code": null, "e": 28741, "s": 28413, "text": "Traversing the hash table\nid=105, name=Raman, mobno=6789054321\nid=104, name=Lakshman, mobno=8909006524\nid=103, name=Mohan, mobno=8907896785\nid=102, name=Shyam, mobno=8907685432\nid=101, name=Ram, mobno=9876543201\n\nSearch the student by student id\n\nEnter the student id : \n104\nStudent is : id=104, name=Lakshman, mobno=8909006524" }, { "code": null, "e": 28752, "s": 28741, "text": "Example 2 " }, { "code": null, "e": 29001, "s": 28752, "text": "Here in this hashtable, string as keys, and Student object as values. To avoid duplicate keys, it has implemented hashCode() and equals() methods. In case, if we enter the duplicate key then the hashtable eliminates the duplicate keys automatically" }, { "code": null, "e": 29006, "s": 29001, "text": "Java" }, { "code": "// Main class import java.util.Hashtable;import java.util.Scanner; public class HashtableExample2 { public static void main(String a[]) { // Initializing the hashtable with // key as String and values as Student object Hashtable<String, Student> list = new Hashtable<String, Student>(); list.put(\"Ram\", new Student(1, \"Ram\", \"8907654321\")); list.put(\"Sita\", new Student(2, \"Sita\", \"9809876543\")); list.put(\"Mohan\", new Student(3, \"Mohan\", \"9098765421\")); list.put(\"Soham\", new Student(4, \"Soham\", \"7898790678\")); list.put(\"Lakhan\", new Student(5, \"Lakhan\", \"7890567845\")); // Traversing the hashtable using for-each loop System.out.println(\"Traversing the hash table\"); for (Student i : list.values()) { System.out.println(i); } System.out.println(); // Search the student using their names System.out.println( \"Search the student by student id\"); System.out.println(); System.out.println(\"Enter the student id : \"); int temp = 3; System.out.println(\"3\"); for (Student s : list.values()) { if (s.getRollno() == temp) { // If found, then print the student details System.out.println(\"Student is : \" + s); // Terminate the program System.exit(0); } } // If student not found, print that there is no // student System.out.println(\"Student not found..\"); }} // Student class class Student { // Initializing the instance variables private int rollno; private String name; private String mobno; // Constructor to initialize the values of variables public Student(int rollno, String name, String mobno) { super(); this.rollno = rollno; this.name = name; this.mobno = mobno; } // getter for roll no public int getRollno() { return rollno; } // setter for roll no public void setRollno(int rollno) { this.rollno = rollno; } // getter for name public String getName() { return name; } // setter for name public void setName(String name) { this.name = name; } // getter for mobno public String getMobno() { return mobno; } // setter for mobno public void setMobno(String mobno) { this.mobno = mobno; } // Overriding of hashCode @Override public int hashCode() { return this.getRollno(); } // Overriding of equals // @Override public boolean equals(Object o) { if (o instanceof Student) { return (this.rollno) == (((Student)o).rollno); } return false; } // Overriding of toString @Override public String toString() { return \"Rollno=\" + rollno + \", name=\" + name + \", mobno=\" + mobno; }}", "e": 31976, "s": 29006, "text": null }, { "code": null, "e": 32311, "s": 31979, "text": "Traversing the hash table\nRollno=2, name=Sita, mobno=9809876543\nRollno=3, name=Mohan, mobno=9098765421\nRollno=5, name=Lakhan, mobno=7890567845\nRollno=4, name=Soham, mobno=7898790678\nRollno=1, name=Ram, mobno=8907654321\n\nSearch the student by student id\n\nEnter the student id : \n3\nStudent is : Rollno=3, name=Mohan, mobno=9098765421" }, { "code": null, "e": 32331, "s": 32313, "text": "gulshankumarar231" }, { "code": null, "e": 32348, "s": 32331, "text": "Java-Collections" }, { "code": null, "e": 32363, "s": 32348, "text": "Java-HashTable" }, { "code": null, "e": 32370, "s": 32363, "text": "Picked" }, { "code": null, "e": 32375, "s": 32370, "text": "Java" }, { "code": null, "e": 32389, "s": 32375, "text": "Java Programs" }, { "code": null, "e": 32394, "s": 32389, "text": "Java" }, { "code": null, "e": 32411, "s": 32394, "text": "Java-Collections" }, { "code": null, "e": 32509, "s": 32411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32518, "s": 32509, "text": "Comments" }, { "code": null, "e": 32531, "s": 32518, "text": "Old Comments" }, { "code": null, "e": 32577, "s": 32531, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 32598, "s": 32577, "text": "Constructors in Java" }, { "code": null, "e": 32613, "s": 32598, "text": "Stream In Java" }, { "code": null, "e": 32630, "s": 32613, "text": "Generics in Java" }, { "code": null, "e": 32649, "s": 32630, "text": "Exceptions in Java" }, { "code": null, "e": 32693, "s": 32649, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 32719, "s": 32693, "text": "Java Programming Examples" }, { "code": null, "e": 32753, "s": 32719, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 32800, "s": 32753, "text": "Implementing a Linked List in Java using Class" } ]
JqueryUI - Tooltip
Tooltip widget of jQueryUI replaces the native tooltips. This widget adds new themes and allows for customization. First let us understand what tooltips are? Tooltips can be attached to any element. To display tooltips, just add title attribute to input elements and title attribute value will be used as tooltip. When you hover the element with your mouse, the title attribute is displayed in a little box next to the element. jQueryUI provides tooltip() method to add tooltip to any element on which you want to display tooltip. This gives a fade animation by default to show and hide the tooltip, compared to just toggling the visibility. The tooltip() method can be used in two forms − $(selector, context).tooltip (options) Method $(selector, context).tooltip (options) Method $(selector, context).tooltip ("action", [params]) Method $(selector, context).tooltip ("action", [params]) Method $(selector, context).tooltip(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).tooltip({option1: value1, option2: value2..... }); The following table lists the different options that can be used with this method − This option represents content of a tooltip. By default its value is function returning the title attribute. Option - content This option represents content of a tooltip. By default its value is function returning the title attribute. This can be of type − Function − The callback can either return the content directly, or call the first argument, passing in the content, eg. for ajax content. Function − The callback can either return the content directly, or call the first argument, passing in the content, eg. for ajax content. String − A string of HTML to use for the tooltip content. String − A string of HTML to use for the tooltip content. Syntax $(".selector").tooltip( { content: "Some content!" } ); This option when set to true disables the tooltip. By default its value is false. Option - disabled This option when set to true disables the tooltip. By default its value is false. Syntax $(".selector").tooltip( { disabled: true } ); This option represents the animation effect when hiding the tooltip. By default its value is true. Option - hide This option represents the animation effect when hiding the tooltip. By default its value is true. This can be of type − Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing. Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing. Number − The tooltip will fade out with the specified duration and the default easing. Number − The tooltip will fade out with the specified duration and the default easing. String − The tooltip will be hidden using the specified effect such as "slideUp", "fold". String − The tooltip will be hidden using the specified effect such as "slideUp", "fold". Object − Possible values are effect, delay, duration, and easing. Object − Possible values are effect, delay, duration, and easing. Syntax $(".selector").tooltip( { hide: { effect: "explode", duration: 1000 } } ); This option indicates which items can show tooltips. By default its value is [title]. Option - items This option indicates which items can show tooltips. By default its value is [title]. Syntax $(".selector").tooltip( { items: "img[alt]" } ); This option decides the position of the tooltip w.r.t the associated target element. By default its value is function returning the title attribute. Possible values are: my, at, of, collision, using, within. Option - position This option decides the position of the tooltip w.r.t the associated target element. By default its value is function returning the title attribute. Possible values are: my, at, of, collision, using, within. Syntax $(".selector").tooltip( { { my: "left top+15", at: "left bottom", collision: "flipfit" } } ); This option represents how to animate the showing of tooltip. By default its value is true. Option - show This option represents how to animate the showing of tooltip. By default its value is true. This can be of type − Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing. Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing. Number − The tooltip will fade out with the specified duration and the default easing. Number − The tooltip will fade out with the specified duration and the default easing. String − The tooltip will be hidden using the specified effect such as "slideUp", "fold". String − The tooltip will be hidden using the specified effect such as "slideUp", "fold". Object − Possible values are effect, delay, duration, and easing. Object − Possible values are effect, delay, duration, and easing. Syntax $(".selector").tooltip( { show: { effect: "blind", duration: 800 } } ); This option is a class which can be added to the tooltip widget for tooltips such as warning or errors. By default its value is null. Option - tooltipClass This option is a class which can be added to the tooltip widget for tooltips such as warning or errors. By default its value is null. Syntax $(".selector").tooltip( { tooltipClass: "custom-tooltip-styling" } } ); This option when set to true, the tooltip follows/tracks the mouse. By default its value is false. Option - track This option when set to true, the tooltip follows/tracks the mouse. By default its value is false. Syntax $(".selector").tooltip( { track: true } ); The following section will show you a few working examples of tooltip functionality. The following example demonstrates a simple example of tooltip functionality passing no parameters to the tooltip() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tooltip 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> <!-- Javascript --> <script> $(function() { $("#tooltip-1").tooltip(); $("#tooltip-2").tooltip(); }); </script> </head> <body> <!-- HTML --> <label for = "name">Name:</label> <input id = "tooltip-1" title = "Enter You name"> <p><a id = "tooltip-2" href = "#" title = "Nice tooltip"> I also have a tooltip</a></p> </body> </html> Let us save the above code in an HTML file tooltipexample.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 − I also have a tooltip In the above example, hover over the links above or use the tab key to cycle the focus on each element. The following example shows the usage of three important options (a) content (b) track and (c) disabled in the tooltip function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tooltip 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> <!-- Javascript --> <script> $(function() { $( "#tooltip-3" ).tooltip({ content: "<strong>Hi!</strong>", track:true }), $( "#tooltip-4" ).tooltip({ disabled: true }); }); </script> </head> <body> <!-- HTML --> <label for = "name">Message:</label> <input id = "tooltip-3" title = "tooltip"><br><br><br> <label for = "name">Tooltip disabled for me:</label> <input id = "tooltip-4" title = "tooltip"> </body> </html> Let us save the above code in an HTML file tooltipexample.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 − In the above example, the content of tooltip of first box is set using content option. You can also notice the tooltip follows the mouse. The tooltip for second input box is disabled. The following example shows the usage of option position in the tooltip function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tooltip 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> body { margin-top: 100px; } .ui-tooltip-content::after, .ui-tooltip-content::before { content: ""; position: absolute; border-style: solid; display: block; left: 90px; } .ui-tooltip-content::before { bottom: -10px; border-color: #AAA transparent; border-width: 10px 10px 0; } .ui-tooltip-content::after { bottom: -7px; border-color: white transparent; border-width: 10px 10px 0; } </style> <!-- Javascript --> <script> $(function() { $( "#tooltip-7" ).tooltip({ position: { my: "center bottom", at: "center top-10", collision: "none" } }); }); </script> </head> <body> <!-- HTML --> <label for = "name">Enter Date of Birth:</label> <input id = "tooltip-7" title = "Please use MM.DD.YY format."> </body> </html> Let us save the above code in an HTML file tooltipexample.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 − In the above example the tooltip position is set on top of the input box. The tooltip (action, params) method can perform an action on the tooltip elements, such as disabling the tooltip. The action is specified as a string in the first argument and optionally, one or more params can be provided based on the given action. $(selector, context).tooltip ("action", [params]); The following table lists the actions for this method − This action closes the tooltip. This method does not accept any arguments. Action - close() This action closes the tooltip. This method does not accept any arguments. Syntax $(".selector").tooltip("close"); This action removes the tooltip 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 the tooltip functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments. Syntax $(".selector").tooltip("destroy"); This action deactivates the tooltip. This method does not accept any arguments. Action - disable() This action deactivates the tooltip. This method does not accept any arguments. Syntax $(".selector").tooltip("disable"); This action activates the tooltip. This method does not accept any arguments. Action - enable() This action activates the tooltip. This method does not accept any arguments. Syntax $(".selector").tooltip("enable"); This action programmatically opens the tooltip. This method does not accept any arguments. Action - open() This action programmatically opens the tooltip. This method does not accept any arguments. Syntax $(".selector").tooltip("open"); This action gets the value associated with optionName for the tooltip. This method does not accept any arguments. Action - option( optionName ) This action gets the value associated with optionName for the tooltip. This method does not accept any arguments. Syntax var isDisabled = $( ".selector" ).tooltip( "option", "disabled" ); This action gets an object containing key/value pairs representing the current tooltip options hash. This method does not accept any arguments. Action - option() This action gets an object containing key/value pairs representing the current tooltip options hash. This method does not accept any arguments. Syntax $(".selector").tooltip("option"); This action sets the value of the tooltip option associated with the specified optionName. Action - option( optionName, value ) This action sets the value of the tooltip option associated with the specified optionName. Syntax $( ".selector" ).tooltip( "option", "disabled", true ); This action sets one or more options for tooltip. Action - option( options ) This action sets one or more options for tooltip. Syntax $( ".selector" ).tooltip( "option", { disabled: true } ); This action returns a jQuery object containing the original element. This method does not accept any arguments. Action - widget() This action returns a jQuery object containing the original element. This method does not accept any arguments. Syntax $(".selector").tooltip("widget"); Now let us see an example using the actions from the above table. The following example demonstrates the use of actions disable and enable. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tooltip 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> <!-- Javascript --> <script> $(function() { $("#tooltip-8").tooltip({ //use 'of' to link the tooltip to your specified input position: { of: '#myInput', my: 'left center', at: 'left center' }, }), $('#myBtn').click(function () { $('#tooltip-8').tooltip("open"); }); }); </script> </head> <body style = "padding:100px;"> <!-- HTML --> <a id = "tooltip-8" title = "Message" href = "#"></a> <input id = "myInput" type = "text" name = "myInput" value = "0" size = "7" /> <input id = "myBtn" type = "submit" name = "myBtn" value = "myBtn" class = "myBtn" /> </body> </html> Let us save the above code in an HTML file tooltipexample.htm and open it in a standard browser which supports javascript, you must also see the following output − In the above example, click on myBtn button and a tooltip pops up. In addition to the tooltip (options) method which we saw in the previous sections, JqueryUI provides event methods as which gets triggered for a particular event. These event methods are listed below − Triggered when the tooltip is created. Where event is of type Event, and ui is of type Object. Event - create(event, ui) Triggered when the tooltip is created. Where event is of type Event, and ui is of type Object. Syntax $(".selector").tooltip( create: function(event, ui) {} ); Triggered when the tooltip is closed. Usually triggers on focusout or mouseleave. Where event is of type Event, and ui is of type Object. Event - close(event, ui) Triggered when the tooltip is closed. Usually triggers on focusout or mouseleave. Where event is of type Event, and ui is of type Object. Possible values of ui are − tooltip − A generated tooltip element. tooltip − A generated tooltip element. Syntax $(".selector").tooltip( close: function(event, ui) {} ); Triggered when the tooltip is displayed or shown. Usually triggered on focusin or mouseover. Where event is of type Event, and ui is of type Object. Event - open(event, ui) Triggered when the tooltip is displayed or shown. Usually triggered on focusin or mouseover. Where event is of type Event, and ui is of type Object.Possible values of ui are − tooltip − A generated tooltip element. tooltip − A generated tooltip element. Syntax $(".selector").tooltip( open: function(event, ui) {} ); The following example demonstrates event method usage during tooltip functionality. This example demonstrates use of open and close events. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tooltip 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> <!-- Javascript --> <script> $(function() { $('.tooltip-9').tooltip({ items: 'a.tooltip-9', content: 'Hello welcome...', show: "slideDown", // show immediately open: function(event, ui) { ui.tooltip.hover( function () { $(this).fadeTo("slow", 0.5); }); } }); }); $(function() { $('.tooltip-10').tooltip({ items: 'a.tooltip-10', content: 'Welcome to TutorialsPoint...', show: "fold", close: function(event, ui) { ui.tooltip.hover(function() { $(this).stop(true).fadeTo(500, 1); }, function() { $(this).fadeOut('500', function() { $(this).remove(); }); }); } }); }); </script> </head> <body style = "padding:100px;"> <!-- HTML --> <div id = "target"> <a href = "#" class = "tooltip-9">Hover over me!</a> <a href = "#" class = "tooltip-10">Hover over me too!</a> </div> </body> </html> Let us save the above code in an HTML file tooltipexample.htm and open it in a standard browser which supports javascript, you must also see the following output − In the above example the tooltip for Hover over me! disappear immediately whereas the tooltip for Hover over me too! fades out after duration of 1000ms. Print Add Notes Bookmark this page
[ { "code": null, "e": 2692, "s": 2264, "text": "Tooltip widget of jQueryUI replaces the native tooltips. This widget adds new themes and allows for customization. First let us understand what tooltips are? Tooltips can be attached to any element. To display tooltips, just add title attribute to input elements and title attribute value will be used as tooltip. When you hover the element with your mouse, the title attribute is displayed in a little box next to the element." }, { "code": null, "e": 2906, "s": 2692, "text": "jQueryUI provides tooltip() method to add tooltip to any element on which you want to display tooltip. This gives a fade animation by default to show and hide the tooltip, compared to just toggling the visibility." }, { "code": null, "e": 2954, "s": 2906, "text": "The tooltip() method can be used in two forms −" }, { "code": null, "e": 3000, "s": 2954, "text": "$(selector, context).tooltip (options) Method" }, { "code": null, "e": 3046, "s": 3000, "text": "$(selector, context).tooltip (options) Method" }, { "code": null, "e": 3103, "s": 3046, "text": "$(selector, context).tooltip (\"action\", [params]) Method" }, { "code": null, "e": 3160, "s": 3103, "text": "$(selector, context).tooltip (\"action\", [params]) Method" }, { "code": null, "e": 3200, "s": 3160, "text": "$(selector, context).tooltip(options);\n" }, { "code": null, "e": 3376, "s": 3200, "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": 3448, "s": 3376, "text": "$(selector, context).tooltip({option1: value1, option2: value2..... });" }, { "code": null, "e": 3532, "s": 3448, "text": "The following table lists the different options that can be used with this method −" }, { "code": null, "e": 3641, "s": 3532, "text": "This option represents content of a tooltip. By default its value is function returning the title attribute." }, { "code": null, "e": 3658, "s": 3641, "text": "Option - content" }, { "code": null, "e": 3789, "s": 3658, "text": "This option represents content of a tooltip. By default its value is function returning the title attribute. This can be of type −" }, { "code": null, "e": 3927, "s": 3789, "text": "Function − The callback can either return the content directly, or call the first argument, passing in the content, eg. for ajax content." }, { "code": null, "e": 4065, "s": 3927, "text": "Function − The callback can either return the content directly, or call the first argument, passing in the content, eg. for ajax content." }, { "code": null, "e": 4123, "s": 4065, "text": "String − A string of HTML to use for the tooltip content." }, { "code": null, "e": 4181, "s": 4123, "text": "String − A string of HTML to use for the tooltip content." }, { "code": null, "e": 4188, "s": 4181, "text": "Syntax" }, { "code": null, "e": 4248, "s": 4188, "text": "$(\".selector\").tooltip(\n { content: \"Some content!\" }\n);\n" }, { "code": null, "e": 4330, "s": 4248, "text": "This option when set to true disables the tooltip. By default its value is false." }, { "code": null, "e": 4348, "s": 4330, "text": "Option - disabled" }, { "code": null, "e": 4430, "s": 4348, "text": "This option when set to true disables the tooltip. By default its value is false." }, { "code": null, "e": 4437, "s": 4430, "text": "Syntax" }, { "code": null, "e": 4487, "s": 4437, "text": "$(\".selector\").tooltip(\n { disabled: true }\n);\n" }, { "code": null, "e": 4586, "s": 4487, "text": "This option represents the animation effect when hiding the tooltip. By default its value is true." }, { "code": null, "e": 4600, "s": 4586, "text": "Option - hide" }, { "code": null, "e": 4721, "s": 4600, "text": "This option represents the animation effect when hiding the tooltip. By default its value is true. This can be of type −" }, { "code": null, "e": 4852, "s": 4721, "text": "Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing." }, { "code": null, "e": 4983, "s": 4852, "text": "Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing." }, { "code": null, "e": 5070, "s": 4983, "text": "Number − The tooltip will fade out with the specified duration and the default easing." }, { "code": null, "e": 5157, "s": 5070, "text": "Number − The tooltip will fade out with the specified duration and the default easing." }, { "code": null, "e": 5247, "s": 5157, "text": "String − The tooltip will be hidden using the specified effect such as \"slideUp\", \"fold\"." }, { "code": null, "e": 5337, "s": 5247, "text": "String − The tooltip will be hidden using the specified effect such as \"slideUp\", \"fold\"." }, { "code": null, "e": 5403, "s": 5337, "text": "Object − Possible values are effect, delay, duration, and easing." }, { "code": null, "e": 5469, "s": 5403, "text": "Object − Possible values are effect, delay, duration, and easing." }, { "code": null, "e": 5476, "s": 5469, "text": "Syntax" }, { "code": null, "e": 5555, "s": 5476, "text": "$(\".selector\").tooltip(\n { hide: { effect: \"explode\", duration: 1000 } }\n);\n" }, { "code": null, "e": 5641, "s": 5555, "text": "This option indicates which items can show tooltips. By default its value is [title]." }, { "code": null, "e": 5656, "s": 5641, "text": "Option - items" }, { "code": null, "e": 5742, "s": 5656, "text": "This option indicates which items can show tooltips. By default its value is [title]." }, { "code": null, "e": 5749, "s": 5742, "text": "Syntax" }, { "code": null, "e": 5802, "s": 5749, "text": "$(\".selector\").tooltip(\n { items: \"img[alt]\" }\n);\n" }, { "code": null, "e": 6010, "s": 5802, "text": "This option decides the position of the tooltip w.r.t the associated target element. By default its value is function returning the title attribute. Possible values are: my, at, of, collision, using, within." }, { "code": null, "e": 6028, "s": 6010, "text": "Option - position" }, { "code": null, "e": 6236, "s": 6028, "text": "This option decides the position of the tooltip w.r.t the associated target element. By default its value is function returning the title attribute. Possible values are: my, at, of, collision, using, within." }, { "code": null, "e": 6243, "s": 6236, "text": "Syntax" }, { "code": null, "e": 6341, "s": 6243, "text": "$(\".selector\").tooltip(\n { { my: \"left top+15\", at: \"left bottom\", collision: \"flipfit\" } }\n);\n" }, { "code": null, "e": 6433, "s": 6341, "text": "This option represents how to animate the showing of tooltip. By default its value is true." }, { "code": null, "e": 6447, "s": 6433, "text": "Option - show" }, { "code": null, "e": 6561, "s": 6447, "text": "This option represents how to animate the showing of tooltip. By default its value is true. This can be of type −" }, { "code": null, "e": 6692, "s": 6561, "text": "Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing." }, { "code": null, "e": 6823, "s": 6692, "text": "Boolean − This can be true or false. When set to true, the tooltip will fade out with the default duration and the default easing." }, { "code": null, "e": 6910, "s": 6823, "text": "Number − The tooltip will fade out with the specified duration and the default easing." }, { "code": null, "e": 6997, "s": 6910, "text": "Number − The tooltip will fade out with the specified duration and the default easing." }, { "code": null, "e": 7087, "s": 6997, "text": "String − The tooltip will be hidden using the specified effect such as \"slideUp\", \"fold\"." }, { "code": null, "e": 7177, "s": 7087, "text": "String − The tooltip will be hidden using the specified effect such as \"slideUp\", \"fold\"." }, { "code": null, "e": 7243, "s": 7177, "text": "Object − Possible values are effect, delay, duration, and easing." }, { "code": null, "e": 7309, "s": 7243, "text": "Object − Possible values are effect, delay, duration, and easing." }, { "code": null, "e": 7316, "s": 7309, "text": "Syntax" }, { "code": null, "e": 7392, "s": 7316, "text": "$(\".selector\").tooltip(\n { show: { effect: \"blind\", duration: 800 } }\n);\n" }, { "code": null, "e": 7526, "s": 7392, "text": "This option is a class which can be added to the tooltip widget for tooltips such as warning or errors. By default its value is null." }, { "code": null, "e": 7548, "s": 7526, "text": "Option - tooltipClass" }, { "code": null, "e": 7682, "s": 7548, "text": "This option is a class which can be added to the tooltip widget for tooltips such as warning or errors. By default its value is null." }, { "code": null, "e": 7689, "s": 7682, "text": "Syntax" }, { "code": null, "e": 7765, "s": 7689, "text": "$(\".selector\").tooltip(\n { tooltipClass: \"custom-tooltip-styling\" } }\n);\n" }, { "code": null, "e": 7864, "s": 7765, "text": "This option when set to true, the tooltip follows/tracks the mouse. By default its value is false." }, { "code": null, "e": 7879, "s": 7864, "text": "Option - track" }, { "code": null, "e": 7978, "s": 7879, "text": "This option when set to true, the tooltip follows/tracks the mouse. By default its value is false." }, { "code": null, "e": 7985, "s": 7978, "text": "Syntax" }, { "code": null, "e": 8032, "s": 7985, "text": "$(\".selector\").tooltip(\n { track: true }\n);\n" }, { "code": null, "e": 8117, "s": 8032, "text": "The following section will show you a few working examples of tooltip functionality." }, { "code": null, "e": 8241, "s": 8117, "text": "The following example demonstrates a simple example of tooltip functionality passing no parameters to the tooltip() method." }, { "code": null, "e": 9080, "s": 8241, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Tooltip 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 <!-- Javascript -->\n <script>\n $(function() {\n $(\"#tooltip-1\").tooltip();\n $(\"#tooltip-2\").tooltip();\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <label for = \"name\">Name:</label>\n <input id = \"tooltip-1\" title = \"Enter You name\">\n <p><a id = \"tooltip-2\" href = \"#\" title = \"Nice tooltip\">\n I also have a tooltip</a></p>\n </body>\n</html>" }, { "code": null, "e": 9279, "s": 9080, "text": "Let us save the above code in an HTML file tooltipexample.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": 9324, "s": 9279, "text": "\n I also have a tooltip\n " }, { "code": null, "e": 9428, "s": 9324, "text": "In the above example, hover over the links above or use the tab key to cycle the focus on each element." }, { "code": null, "e": 9569, "s": 9428, "text": "The following example shows the usage of three important options (a) content (b) track and (c) disabled in the tooltip function of JqueryUI." }, { "code": null, "e": 10556, "s": 9569, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Tooltip 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 <!-- Javascript -->\n <script>\n $(function() {\n $( \"#tooltip-3\" ).tooltip({\n content: \"<strong>Hi!</strong>\",\n track:true\n }),\n $( \"#tooltip-4\" ).tooltip({\n disabled: true\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <label for = \"name\">Message:</label>\n <input id = \"tooltip-3\" title = \"tooltip\"><br><br><br>\n <label for = \"name\">Tooltip disabled for me:</label>\n <input id = \"tooltip-4\" title = \"tooltip\">\n </body>\n</html>" }, { "code": null, "e": 10755, "s": 10556, "text": "Let us save the above code in an HTML file tooltipexample.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": 10939, "s": 10755, "text": "In the above example, the content of tooltip of first box is set using content option. You can also notice the tooltip follows the mouse. The tooltip for second input box is disabled." }, { "code": null, "e": 11033, "s": 10939, "text": "The following example shows the usage of option position in the tooltip function of JqueryUI." }, { "code": null, "e": 12589, "s": 11033, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Tooltip 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 body {\n margin-top: 100px;\n }\n\n .ui-tooltip-content::after, .ui-tooltip-content::before {\n content: \"\";\n position: absolute;\n border-style: solid;\n display: block;\n left: 90px;\n }\n .ui-tooltip-content::before {\n bottom: -10px;\n border-color: #AAA transparent;\n border-width: 10px 10px 0;\n }\n .ui-tooltip-content::after {\n bottom: -7px;\n border-color: white transparent;\n border-width: 10px 10px 0;\n }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#tooltip-7\" ).tooltip({\n position: {\n my: \"center bottom\",\n at: \"center top-10\",\n collision: \"none\"\n }\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <label for = \"name\">Enter Date of Birth:</label>\n <input id = \"tooltip-7\" title = \"Please use MM.DD.YY format.\">\n </body>\n</html>" }, { "code": null, "e": 12788, "s": 12589, "text": "Let us save the above code in an HTML file tooltipexample.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": 12862, "s": 12788, "text": "In the above example the tooltip position is set on top of the input box." }, { "code": null, "e": 13112, "s": 12862, "text": "The tooltip (action, params) method can perform an action on the tooltip elements, such as disabling the tooltip. The action is specified as a string in the first argument and optionally, one or more params can be provided based on the given action." }, { "code": null, "e": 13164, "s": 13112, "text": "$(selector, context).tooltip (\"action\", [params]);\n" }, { "code": null, "e": 13220, "s": 13164, "text": "The following table lists the actions for this method −" }, { "code": null, "e": 13295, "s": 13220, "text": "This action closes the tooltip. This method does not accept any arguments." }, { "code": null, "e": 13312, "s": 13295, "text": "Action - close()" }, { "code": null, "e": 13387, "s": 13312, "text": "This action closes the tooltip. This method does not accept any arguments." }, { "code": null, "e": 13394, "s": 13387, "text": "Syntax" }, { "code": null, "e": 13428, "s": 13394, "text": "$(\".selector\").tooltip(\"close\");\n" }, { "code": null, "e": 13586, "s": 13428, "text": "This action removes the tooltip functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments." }, { "code": null, "e": 13605, "s": 13586, "text": "Action - destroy()" }, { "code": null, "e": 13763, "s": 13605, "text": "This action removes the tooltip functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments." }, { "code": null, "e": 13770, "s": 13763, "text": "Syntax" }, { "code": null, "e": 13806, "s": 13770, "text": "$(\".selector\").tooltip(\"destroy\");\n" }, { "code": null, "e": 13886, "s": 13806, "text": "This action deactivates the tooltip. This method does not accept any arguments." }, { "code": null, "e": 13905, "s": 13886, "text": "Action - disable()" }, { "code": null, "e": 13985, "s": 13905, "text": "This action deactivates the tooltip. This method does not accept any arguments." }, { "code": null, "e": 13992, "s": 13985, "text": "Syntax" }, { "code": null, "e": 14028, "s": 13992, "text": "$(\".selector\").tooltip(\"disable\");\n" }, { "code": null, "e": 14106, "s": 14028, "text": "This action activates the tooltip. This method does not accept any arguments." }, { "code": null, "e": 14124, "s": 14106, "text": "Action - enable()" }, { "code": null, "e": 14202, "s": 14124, "text": "This action activates the tooltip. This method does not accept any arguments." }, { "code": null, "e": 14209, "s": 14202, "text": "Syntax" }, { "code": null, "e": 14244, "s": 14209, "text": "$(\".selector\").tooltip(\"enable\");\n" }, { "code": null, "e": 14335, "s": 14244, "text": "This action programmatically opens the tooltip. This method does not accept any arguments." }, { "code": null, "e": 14351, "s": 14335, "text": "Action - open()" }, { "code": null, "e": 14442, "s": 14351, "text": "This action programmatically opens the tooltip. This method does not accept any arguments." }, { "code": null, "e": 14449, "s": 14442, "text": "Syntax" }, { "code": null, "e": 14482, "s": 14449, "text": "$(\".selector\").tooltip(\"open\");\n" }, { "code": null, "e": 14596, "s": 14482, "text": "This action gets the value associated with optionName for the tooltip. This method does not accept any arguments." }, { "code": null, "e": 14626, "s": 14596, "text": "Action - option( optionName )" }, { "code": null, "e": 14740, "s": 14626, "text": "This action gets the value associated with optionName for the tooltip. This method does not accept any arguments." }, { "code": null, "e": 14747, "s": 14740, "text": "Syntax" }, { "code": null, "e": 14815, "s": 14747, "text": "var isDisabled = $( \".selector\" ).tooltip( \"option\", \"disabled\" );\n" }, { "code": null, "e": 14959, "s": 14815, "text": "This action gets an object containing key/value pairs representing the current tooltip options hash. This method does not accept any arguments." }, { "code": null, "e": 14977, "s": 14959, "text": "Action - option()" }, { "code": null, "e": 15121, "s": 14977, "text": "This action gets an object containing key/value pairs representing the current tooltip options hash. This method does not accept any arguments." }, { "code": null, "e": 15128, "s": 15121, "text": "Syntax" }, { "code": null, "e": 15163, "s": 15128, "text": "$(\".selector\").tooltip(\"option\");\n" }, { "code": null, "e": 15254, "s": 15163, "text": "This action sets the value of the tooltip option associated with the specified optionName." }, { "code": null, "e": 15291, "s": 15254, "text": "Action - option( optionName, value )" }, { "code": null, "e": 15382, "s": 15291, "text": "This action sets the value of the tooltip option associated with the specified optionName." }, { "code": null, "e": 15389, "s": 15382, "text": "Syntax" }, { "code": null, "e": 15446, "s": 15389, "text": "$( \".selector\" ).tooltip( \"option\", \"disabled\", true );\n" }, { "code": null, "e": 15496, "s": 15446, "text": "This action sets one or more options for tooltip." }, { "code": null, "e": 15523, "s": 15496, "text": "Action - option( options )" }, { "code": null, "e": 15573, "s": 15523, "text": "This action sets one or more options for tooltip." }, { "code": null, "e": 15580, "s": 15573, "text": "Syntax" }, { "code": null, "e": 15639, "s": 15580, "text": "$( \".selector\" ).tooltip( \"option\", { disabled: true } );\n" }, { "code": null, "e": 15751, "s": 15639, "text": "This action returns a jQuery object containing the original element. This method does not accept any arguments." }, { "code": null, "e": 15769, "s": 15751, "text": "Action - widget()" }, { "code": null, "e": 15881, "s": 15769, "text": "This action returns a jQuery object containing the original element. This method does not accept any arguments." }, { "code": null, "e": 15888, "s": 15881, "text": "Syntax" }, { "code": null, "e": 15923, "s": 15888, "text": "$(\".selector\").tooltip(\"widget\");\n" }, { "code": null, "e": 16063, "s": 15923, "text": "Now let us see an example using the actions from the above table. The following example demonstrates the use of actions disable and enable." }, { "code": null, "e": 17205, "s": 16063, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Tooltip 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 <!-- Javascript -->\n <script>\n $(function() {\n $(\"#tooltip-8\").tooltip({\n //use 'of' to link the tooltip to your specified input\n position: { of: '#myInput', my: 'left center', at: 'left center' },\n }),\n $('#myBtn').click(function () {\n $('#tooltip-8').tooltip(\"open\");\n });\n });\n </script>\n </head>\n \n <body style = \"padding:100px;\">\n <!-- HTML --> \n <a id = \"tooltip-8\" title = \"Message\" href = \"#\"></a>\n <input id = \"myInput\" type = \"text\" name = \"myInput\" value = \"0\" size = \"7\" />\n <input id = \"myBtn\" type = \"submit\" name = \"myBtn\" value = \"myBtn\" class = \"myBtn\" />\n </body>\n</html>" }, { "code": null, "e": 17369, "s": 17205, "text": "Let us save the above code in an HTML file tooltipexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 17436, "s": 17369, "text": "In the above example, click on myBtn button and a tooltip pops up." }, { "code": null, "e": 17638, "s": 17436, "text": "In addition to the tooltip (options) method which we saw in the previous sections, JqueryUI provides event methods as which gets triggered for a particular event. These event methods are listed below −" }, { "code": null, "e": 17733, "s": 17638, "text": "Triggered when the tooltip is created. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 17759, "s": 17733, "text": "Event - create(event, ui)" }, { "code": null, "e": 17854, "s": 17759, "text": "Triggered when the tooltip is created. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 17861, "s": 17854, "text": "Syntax" }, { "code": null, "e": 17923, "s": 17861, "text": "$(\".selector\").tooltip(\n create: function(event, ui) {}\n);\n" }, { "code": null, "e": 18062, "s": 17923, "text": "Triggered when the tooltip is closed. Usually triggers on focusout or mouseleave. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 18087, "s": 18062, "text": "Event - close(event, ui)" }, { "code": null, "e": 18254, "s": 18087, "text": "Triggered when the tooltip is closed. Usually triggers on focusout or mouseleave. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 18293, "s": 18254, "text": "tooltip − A generated tooltip element." }, { "code": null, "e": 18332, "s": 18293, "text": "tooltip − A generated tooltip element." }, { "code": null, "e": 18339, "s": 18332, "text": "Syntax" }, { "code": null, "e": 18400, "s": 18339, "text": "$(\".selector\").tooltip(\n close: function(event, ui) {}\n);\n" }, { "code": null, "e": 18549, "s": 18400, "text": "Triggered when the tooltip is displayed or shown. Usually triggered on focusin or mouseover. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 18573, "s": 18549, "text": "Event - open(event, ui)" }, { "code": null, "e": 18749, "s": 18573, "text": "Triggered when the tooltip is displayed or shown. Usually triggered on focusin or mouseover. Where event is of type Event, and ui is of type Object.Possible values of ui are −" }, { "code": null, "e": 18788, "s": 18749, "text": "tooltip − A generated tooltip element." }, { "code": null, "e": 18827, "s": 18788, "text": "tooltip − A generated tooltip element." }, { "code": null, "e": 18834, "s": 18827, "text": "Syntax" }, { "code": null, "e": 18894, "s": 18834, "text": "$(\".selector\").tooltip(\n open: function(event, ui) {}\n);\n" }, { "code": null, "e": 19034, "s": 18894, "text": "The following example demonstrates event method usage during tooltip functionality. This example demonstrates use of open and close events." }, { "code": null, "e": 20761, "s": 19034, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Tooltip 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 <!-- Javascript -->\n <script>\n $(function() {\n $('.tooltip-9').tooltip({\n items: 'a.tooltip-9',\n content: 'Hello welcome...',\n show: \"slideDown\", // show immediately\n open: function(event, ui) {\n ui.tooltip.hover(\n function () {\n $(this).fadeTo(\"slow\", 0.5);\n });\n }\n });\n });\n $(function() {\n $('.tooltip-10').tooltip({\n items: 'a.tooltip-10',\n content: 'Welcome to TutorialsPoint...',\n show: \"fold\", \n close: function(event, ui) {\n ui.tooltip.hover(function() {\n $(this).stop(true).fadeTo(500, 1); \n },\n function() {\n $(this).fadeOut('500', function() {\n $(this).remove();\n });\n });\n }\n });\n });\n </script>\n </head>\n \n <body style = \"padding:100px;\">\n <!-- HTML --> \n <div id = \"target\">\n <a href = \"#\" class = \"tooltip-9\">Hover over me!</a>\n <a href = \"#\" class = \"tooltip-10\">Hover over me too!</a>\n </div>\n </body>\n</html>" }, { "code": null, "e": 20925, "s": 20761, "text": "Let us save the above code in an HTML file tooltipexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 21078, "s": 20925, "text": "In the above example the tooltip for Hover over me! disappear immediately whereas the tooltip for Hover over me too! fades out after duration of 1000ms." }, { "code": null, "e": 21085, "s": 21078, "text": " Print" }, { "code": null, "e": 21096, "s": 21085, "text": " Add Notes" } ]
Powershell - Scripting
Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Its analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment. Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system. In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more. Windows PowerShell Scripting is a fully developed scripting language and has a rich expression parser/ Cmdlets − Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI). Cmdlets − Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI). Task oriented − PowerShell scripting language is task based and provide supports for existing scripts and command-line tools. Task oriented − PowerShell scripting language is task based and provide supports for existing scripts and command-line tools. Consistent design − As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation. Consistent design − As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation. Simple to Use − Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation. Simple to Use − Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation. Object based − PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly. Object based − PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly. Extensible interface. − PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software. Extensible interface. − PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software. PowerShell variables are named objects. As PowerShell works with objects, these variables are used to work with objects. Variable name should start with $ and can contain alphanumeric characters and underscore in their names. A variable can be created by typing a valid variable name. Type the following command in PowerShell ISE Console. Assuming you are in D:\test folder. $location = Get-Location Here we've created a variable $location and assigned it the output of Get-Location cmdlet. It now contains the current location. Type the following command in PowerShell ISE Console. $location You can see following output in PowerShell console. Path ---- D:\test Get-Member cmdlet can tell the type of variable being used. See the example below. $location | Get-Member You can see following output in PowerShell console. TypeName: System.Management.Automation.PathInfo Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Drive Property System.Management.Automation.PSDriveInfo Drive {get;} Path Property System.String Path {get;} Provider Property System.Management.Automation.ProviderInfo Provider {get;} ProviderPath Property System.String ProviderPath {get;} 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2401, "s": 2034, "text": "Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Its analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment." }, { "code": null, "e": 2640, "s": 2401, "text": "Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system." }, { "code": null, "e": 2932, "s": 2640, "text": "In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more. Windows PowerShell Scripting is a fully developed scripting language and has a rich expression parser/" }, { "code": null, "e": 3114, "s": 2932, "text": "Cmdlets − Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI)." }, { "code": null, "e": 3296, "s": 3114, "text": "Cmdlets − Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI)." }, { "code": null, "e": 3422, "s": 3296, "text": "Task oriented − PowerShell scripting language is task based and provide supports for existing scripts and command-line tools." }, { "code": null, "e": 3548, "s": 3422, "text": "Task oriented − PowerShell scripting language is task based and provide supports for existing scripts and command-line tools." }, { "code": null, "e": 3766, "s": 3548, "text": "Consistent design − As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation." }, { "code": null, "e": 3984, "s": 3766, "text": "Consistent design − As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation." }, { "code": null, "e": 4131, "s": 3984, "text": "Simple to Use − Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation." }, { "code": null, "e": 4278, "s": 4131, "text": "Simple to Use − Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation." }, { "code": null, "e": 4415, "s": 4278, "text": "Object based − PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly." }, { "code": null, "e": 4552, "s": 4415, "text": "Object based − PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly." }, { "code": null, "e": 4745, "s": 4552, "text": "Extensible interface. − PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software." }, { "code": null, "e": 4938, "s": 4745, "text": "Extensible interface. − PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software." }, { "code": null, "e": 5059, "s": 4938, "text": "PowerShell variables are named objects. As PowerShell works with objects, these variables are used to work with objects." }, { "code": null, "e": 5223, "s": 5059, "text": "Variable name should start with $ and can contain alphanumeric characters and underscore in their names. A variable can be created by typing a valid variable name." }, { "code": null, "e": 5313, "s": 5223, "text": "Type the following command in PowerShell ISE Console. Assuming you are in D:\\test folder." }, { "code": null, "e": 5338, "s": 5313, "text": "$location = Get-Location" }, { "code": null, "e": 5467, "s": 5338, "text": "Here we've created a variable $location and assigned it the output of Get-Location cmdlet. It now contains the current location." }, { "code": null, "e": 5521, "s": 5467, "text": "Type the following command in PowerShell ISE Console." }, { "code": null, "e": 5532, "s": 5521, "text": " $location" }, { "code": null, "e": 5584, "s": 5532, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 5852, "s": 5584, "text": "Path \n---- \nD:\\test \n" }, { "code": null, "e": 5935, "s": 5852, "text": "Get-Member cmdlet can tell the type of variable being used. See the example below." }, { "code": null, "e": 5959, "s": 5935, "text": " $location | Get-Member" }, { "code": null, "e": 6011, "s": 5959, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 6890, "s": 6011, "text": " TypeName: System.Management.Automation.PathInfo\n\nName MemberType Definition \n---- ---------- ---------- \nEquals Method bool Equals(System.Object obj) \nGetHashCode Method int GetHashCode() \nGetType Method type GetType() \nToString Method string ToString() \nDrive Property System.Management.Automation.PSDriveInfo Drive {get;} \nPath Property System.String Path {get;} \nProvider Property System.Management.Automation.ProviderInfo Provider {get;}\nProviderPath Property System.String ProviderPath {get;}\n" }, { "code": null, "e": 6925, "s": 6890, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6946, "s": 6925, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 6981, "s": 6946, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6994, "s": 6981, "text": " Vijay Saini" }, { "code": null, "e": 7031, "s": 6994, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 7043, "s": 7031, "text": " Fettah Ben" }, { "code": null, "e": 7050, "s": 7043, "text": " Print" }, { "code": null, "e": 7061, "s": 7050, "text": " Add Notes" } ]
How to create a responsive zig zag (alternating) layout with CSS?
To create responsive zig zag layout with CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { box-sizing:border-box; } body { margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } div h1{ font-size: 40px; color: blueviolet; text-align: center; } div p{ font-size: 18px; } .container { padding: 64px; } .row:after { content: ""; display: table; clear: both } .width66 { float: left; width: 66.66666%; padding: 20px; height: 471px; } .width33 { float: left; width: 33.33333%; padding: 20px; height: 471px; } .large-font { font-size: 48px; } .xlarge-font { font-size: 64px } .button { border: none; color: white; padding: 14px 28px; font-size: 16px; cursor: pointer; background-color: #4CAF50; } img { display: block; height: 250px; width: 250px; max-width: 100%; } @media screen and (max-width: 1000px) { .width66, .width33 { width: 100%; text-align: center; } img { margin: auto; } } </style> </head> <body> <h1 style="text-align:center">Responsive Zig Zag Layout Example</h2> <div class="width66"> <h1>A Gypsy</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia tempore expedita sequi consequuntur rerum quasi voluptate deleniti iure quae magni qui, laudantium illo dolorum temporibus, dolor labore, quos eos. Dolores?</p> </div> <div class="width33"> <img src="https://i.picsum.photos/id/551/800/800.jpg"> </div> <div class="width33"> <img src="https://i.picsum.photos/id/211/800/800.jpg" alt="App"> </div> <div class="width66"> <h1>A cruise ship</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia tempore expedita sequi consequuntur rerum quasi voluptate deleniti iure quae magni qui, laudantium illo dolorum temporibus, dolor labore, quos eos. Dolores?</p> </div> <div class="width66"> <h1>Natures View</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia tempore expedita sequi consequuntur rerum quasi voluptate deleniti iure quae magni qui, laudantium illo dolorum temporibus, dolor labore, quos eos. Dolores?</p> </div> <div class="width33"> <img src="https://i.picsum.photos/id/251/800/800.jpg" > </div> </div> </div> </body> </html> The above code will produce the following output − On resizing ourscreen −
[ { "code": null, "e": 1133, "s": 1062, "text": "To create responsive zig zag layout with CSS, the code is as follows −" }, { "code": null, "e": 1144, "s": 1133, "text": " Live Demo" }, { "code": null, "e": 3608, "s": 1144, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\n * {\n box-sizing:border-box;\n }\n body {\n margin: 0;\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n }\n div h1{\n font-size: 40px;\n color: blueviolet;\n text-align: center;\n }\n div p{\n font-size: 18px;\n }\n .container {\n padding: 64px;\n }\n .row:after {\n content: \"\";\n display: table;\n clear: both\n }\n .width66 {\n float: left;\n width: 66.66666%;\n padding: 20px;\n height: 471px;\n }\n .width33 {\n float: left;\n width: 33.33333%;\n padding: 20px;\n height: 471px;\n }\n .large-font {\n font-size: 48px;\n }\n .xlarge-font {\n font-size: 64px\n }\n .button {\n border: none;\n color: white;\n padding: 14px 28px;\n font-size: 16px;\n cursor: pointer;\n background-color: #4CAF50;\n }\n img {\n display: block;\n height: 250px;\n width: 250px;\n max-width: 100%;\n }\n @media screen and (max-width: 1000px) {\n .width66, .width33 {\n width: 100%;\n text-align: center;\n }\n img {\n margin: auto;\n }\n }\n</style>\n</head>\n<body>\n<h1 style=\"text-align:center\">Responsive Zig Zag Layout Example</h2>\n<div class=\"width66\">\n<h1>A Gypsy</h1>\n<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia tempore expedita sequi consequuntur rerum quasi voluptate deleniti iure quae magni qui, laudantium illo dolorum temporibus, dolor labore, quos eos. Dolores?</p>\n</div>\n<div class=\"width33\">\n<img src=\"https://i.picsum.photos/id/551/800/800.jpg\">\n</div>\n<div class=\"width33\">\n<img src=\"https://i.picsum.photos/id/211/800/800.jpg\" alt=\"App\">\n</div>\n<div class=\"width66\">\n<h1>A cruise ship</h1>\n<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia tempore expedita sequi consequuntur rerum quasi voluptate deleniti iure quae magni qui, laudantium illo dolorum temporibus, dolor labore, quos eos. Dolores?</p>\n</div>\n<div class=\"width66\">\n<h1>Natures View</h1>\n<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia tempore expedita sequi consequuntur rerum quasi voluptate deleniti iure quae magni qui, laudantium illo dolorum temporibus, dolor labore, quos eos. Dolores?</p>\n</div>\n<div class=\"width33\">\n<img src=\"https://i.picsum.photos/id/251/800/800.jpg\" >\n</div>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 3659, "s": 3608, "text": "The above code will produce the following output −" }, { "code": null, "e": 3683, "s": 3659, "text": "On resizing ourscreen −" } ]
How to draw shapes using SVG in HTML5?
SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG. You can draw shapes like circle, rectangle, line, etc using SVG in HTML5 easily. Let’s see an example to draw a rectangle using SVG. You can try to run the following code to draw a rectangle in HTML5. The <rect> element will be used <!DOCTYPE html> <html> <head> <style> #svgelem { position: relative; left: 10%; -webkit-transform: translateX(-20%); -ms-transform: translateX(-20%); transform: translateX(-20%); } </style> <title>SVG</title> </head> <body> <h2>HTML5 SVG Rectangle</h2> <svg id="svgelem" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="200" height="100" fill="green"/> </svg> </body> </html>
[ { "code": null, "e": 1315, "s": 1062, "text": "SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG." }, { "code": null, "e": 1448, "s": 1315, "text": "You can draw shapes like circle, rectangle, line, etc using SVG in HTML5 easily. Let’s see an example to draw a rectangle using SVG." }, { "code": null, "e": 1548, "s": 1448, "text": "You can try to run the following code to draw a rectangle in HTML5. The <rect> element will be used" }, { "code": null, "e": 2084, "s": 1548, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #svgelem {\n position: relative;\n left: 10%;\n -webkit-transform: translateX(-20%);\n -ms-transform: translateX(-20%);\n transform: translateX(-20%);\n }\n </style>\n <title>SVG</title>\n </head>\n <body>\n <h2>HTML5 SVG Rectangle</h2>\n <svg id=\"svgelem\" width=\"300\" height=\"200\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect width=\"200\" height=\"100\" fill=\"green\"/>\n </svg>\n </body>\n</html>" } ]
Java Concurrency - AtomicInteger Class
A java.util.concurrent.atomic.AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features. Following is the list of important methods available in the AtomicInteger class. public int addAndGet(int delta) Atomically adds the given value to the current value. public boolean compareAndSet(int expect, int update) Atomically sets the value to the given updated value if the current value is same as the expected value. public int decrementAndGet() Atomically decrements by one the current value. public double doubleValue() Returns the value of the specified number as a double. public float floatValue() Returns the value of the specified number as a float. public int get() Gets the current value. public int getAndAdd(int delta) Atomiclly adds the given value to the current value. public int getAndDecrement() Atomically decrements by one the current value. public int getAndIncrement() Atomically increments by one the current value. public int getAndSet(int newValue) Atomically sets to the given value and returns the old value. public int incrementAndGet() Atomically increments by one the current value. public int intValue() Returns the value of the specified number as an int. public void lazySet(int newValue) Eventually sets to the given value. public long longValue() Returns the value of the specified number as a long. public void set(int newValue) Sets to the given value. public String toString() Returns the String representation of the current value. public boolean weakCompareAndSet(int expect, int update) Atomically sets the value to the given updated value if the current value is same as the expected value. The following TestThread program shows a unsafe implementation of counter in thread based environment. public class TestThread { static class Counter { private int c = 0; public void increment() { c++; } public int value() { return c; } } public static void main(final String[] arguments) throws InterruptedException { final Counter counter = new Counter(); //1000 threads for(int i = 0; i < 1000 ; i++) { new Thread(new Runnable() { public void run() { counter.increment(); } }).start(); } Thread.sleep(6000); System.out.println("Final number (should be 1000): " + counter.value()); } } This may produce the following result depending upon computer's speed and thread interleaving. Final number (should be 1000): 1000 import java.util.concurrent.atomic.AtomicInteger; public class TestThread { static class Counter { private AtomicInteger c = new AtomicInteger(0); public void increment() { c.getAndIncrement(); } public int value() { return c.get(); } } public static void main(final String[] arguments) throws InterruptedException { final Counter counter = new Counter(); //1000 threads for(int i = 0; i < 1000 ; i++) { new Thread(new Runnable() { public void run() { counter.increment(); } }).start(); } Thread.sleep(6000); System.out.println("Final number (should be 1000): " + counter.value()); } } This will produce the following result. Final number (should be 1000): 1000 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 3161, "s": 2657, "text": "A java.util.concurrent.atomic.AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features." }, { "code": null, "e": 3242, "s": 3161, "text": "Following is the list of important methods available in the AtomicInteger class." }, { "code": null, "e": 3274, "s": 3242, "text": "public int addAndGet(int delta)" }, { "code": null, "e": 3328, "s": 3274, "text": "Atomically adds the given value to the current value." }, { "code": null, "e": 3381, "s": 3328, "text": "public boolean compareAndSet(int expect, int update)" }, { "code": null, "e": 3486, "s": 3381, "text": "Atomically sets the value to the given updated value if the current value is same as the expected value." }, { "code": null, "e": 3515, "s": 3486, "text": "public int decrementAndGet()" }, { "code": null, "e": 3563, "s": 3515, "text": "Atomically decrements by one the current value." }, { "code": null, "e": 3591, "s": 3563, "text": "public double doubleValue()" }, { "code": null, "e": 3646, "s": 3591, "text": "Returns the value of the specified number as a double." }, { "code": null, "e": 3672, "s": 3646, "text": "public float floatValue()" }, { "code": null, "e": 3726, "s": 3672, "text": "Returns the value of the specified number as a float." }, { "code": null, "e": 3743, "s": 3726, "text": "public int get()" }, { "code": null, "e": 3767, "s": 3743, "text": "Gets the current value." }, { "code": null, "e": 3799, "s": 3767, "text": "public int getAndAdd(int delta)" }, { "code": null, "e": 3852, "s": 3799, "text": "Atomiclly adds the given value to the current value." }, { "code": null, "e": 3881, "s": 3852, "text": "public int getAndDecrement()" }, { "code": null, "e": 3929, "s": 3881, "text": "Atomically decrements by one the current value." }, { "code": null, "e": 3958, "s": 3929, "text": "public int getAndIncrement()" }, { "code": null, "e": 4007, "s": 3958, "text": "\nAtomically increments by one the current value." }, { "code": null, "e": 4042, "s": 4007, "text": "public int getAndSet(int newValue)" }, { "code": null, "e": 4104, "s": 4042, "text": "Atomically sets to the given value and returns the old value." }, { "code": null, "e": 4133, "s": 4104, "text": "public int incrementAndGet()" }, { "code": null, "e": 4181, "s": 4133, "text": "Atomically increments by one the current value." }, { "code": null, "e": 4203, "s": 4181, "text": "public int intValue()" }, { "code": null, "e": 4256, "s": 4203, "text": "Returns the value of the specified number as an int." }, { "code": null, "e": 4291, "s": 4256, "text": "public void lazySet(int newValue)" }, { "code": null, "e": 4327, "s": 4291, "text": "Eventually sets to the given value." }, { "code": null, "e": 4352, "s": 4327, "text": "public long longValue()" }, { "code": null, "e": 4405, "s": 4352, "text": "Returns the value of the specified number as a long." }, { "code": null, "e": 4436, "s": 4405, "text": "public void set(int newValue)" }, { "code": null, "e": 4461, "s": 4436, "text": "Sets to the given value." }, { "code": null, "e": 4486, "s": 4461, "text": "public String toString()" }, { "code": null, "e": 4542, "s": 4486, "text": "Returns the String representation of the current value." }, { "code": null, "e": 4599, "s": 4542, "text": "public boolean weakCompareAndSet(int expect, int update)" }, { "code": null, "e": 4704, "s": 4599, "text": "Atomically sets the value to the given updated value if the current value is same as the expected value." }, { "code": null, "e": 4807, "s": 4704, "text": "The following TestThread program shows a unsafe implementation of counter in thread based environment." }, { "code": null, "e": 5487, "s": 4807, "text": "public class TestThread {\n\n static class Counter {\n private int c = 0;\n\n public void increment() {\n c++;\n }\n\n public int value() {\n return c;\n }\n }\n \n public static void main(final String[] arguments) throws InterruptedException {\n final Counter counter = new Counter();\n \n //1000 threads\n for(int i = 0; i < 1000 ; i++) {\n \n new Thread(new Runnable() {\n \n public void run() {\n counter.increment();\n }\n }).start(); \n } \n Thread.sleep(6000);\n System.out.println(\"Final number (should be 1000): \" + counter.value());\n } \n}" }, { "code": null, "e": 5582, "s": 5487, "text": "This may produce the following result depending upon computer's speed and thread interleaving." }, { "code": null, "e": 5619, "s": 5582, "text": "Final number (should be 1000): 1000\n" }, { "code": null, "e": 6377, "s": 5619, "text": "import java.util.concurrent.atomic.AtomicInteger;\n\npublic class TestThread {\n\n static class Counter {\n private AtomicInteger c = new AtomicInteger(0);\n\n public void increment() {\n c.getAndIncrement();\n }\n\n public int value() {\n return c.get();\n }\n }\n \n public static void main(final String[] arguments) throws InterruptedException {\n final Counter counter = new Counter();\n \n //1000 threads\n for(int i = 0; i < 1000 ; i++) {\n\n new Thread(new Runnable() {\n public void run() {\n counter.increment();\n }\n }).start(); \n } \n Thread.sleep(6000);\n System.out.println(\"Final number (should be 1000): \" + counter.value());\n }\n}" }, { "code": null, "e": 6417, "s": 6377, "text": "This will produce the following result." }, { "code": null, "e": 6454, "s": 6417, "text": "Final number (should be 1000): 1000\n" }, { "code": null, "e": 6487, "s": 6454, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6503, "s": 6487, "text": " Malhar Lathkar" }, { "code": null, "e": 6536, "s": 6503, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6552, "s": 6536, "text": " Malhar Lathkar" }, { "code": null, "e": 6587, "s": 6552, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6601, "s": 6587, "text": " Anadi Sharma" }, { "code": null, "e": 6635, "s": 6601, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6649, "s": 6635, "text": " Tushar Kale" }, { "code": null, "e": 6686, "s": 6649, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6701, "s": 6686, "text": " Monica Mittal" }, { "code": null, "e": 6734, "s": 6701, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6753, "s": 6734, "text": " Arnab Chakraborty" }, { "code": null, "e": 6760, "s": 6753, "text": " Print" }, { "code": null, "e": 6771, "s": 6760, "text": " Add Notes" } ]
Convert dataframe rows and columns to vector in R - GeeksforGeeks
05 Apr, 2021 In this article, we are going to convert a dataframe column to a vector and a dataframe row to a vector in the R Programming Language. We are taking a column in the data frame and passing it into another variable by using the selection method. The selection method can be defined as choosing a column from a data frame using the ” [[]]” operator. Steps – Create data frame Select column to be converted Assign it to a variable Display data frame so generated. Syntax: dataframe[[‘column’]] Example: R # create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data) # convert id column into a vectorcolumn_data=data[['id']]print(column_data) # convert name column into a vectorcolumn_data1=data[['name']]print(column_data1) Output: We can convert every row or entire dataframe by using a method called as.vector() Approach Create dataframe Select row to be converted Pass it to the function Display result Syntax: as.vector(t(dataframe_name)) Where t is the transpose of the dataframe. If t is not specified, the output is both rows and column names. If it is specified output is only rows. Example: without t specification. R # create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data)print("-----------") # converting 1 st row to a vectoras.vector((data[1,]))print("-----------") # converting 2nd row to a vectoras.vector((data[2,]))print("-----------") # converting 3 rd row to a vectoras.vector((data[3,]))print("-----------") Output: Example: Using t R # create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data)print("-----------") # converting 1 st row to a vectoras.vector(t(data[1,]))print("-----------") # converting 2nd row to a vectoras.vector(t(data[2,]))print("-----------") # converting 3 rd row to a vectoras.vector(t(data[3,]))print("-----------") Output: Example: R # create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data)print("-----------") # converting all dataframe to a vectoras.vector(t(data)) Output: Example 2 : R # create vectorsid=c(7058,7084,7098)address=c('guntur','hyd','kothapeta')name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,address,name) print(data)print("-----dataframe row to a vector------") # converting dataframe to a vectoras.vector(t(data)) print("-----dataframe column to a vector------") # converting dataframe 1 st column to a vectordata1=data[['id']]print(data1) # converting dataframe 2 nd column to a vectordata1=data[['address']]print(data1) # converting dataframe 3 rd column to a vectordata1=data[['name']]print(data1) Output: 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. Comments Old Comments Loops in R (for, while, repeat) Filter data by multiple conditions in R using Dplyr How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Remove rows with NA in one column of R DataFrame How to change Row Names of DataFrame in R ? Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 24938, "s": 24910, "text": "\n05 Apr, 2021" }, { "code": null, "e": 25073, "s": 24938, "text": "In this article, we are going to convert a dataframe column to a vector and a dataframe row to a vector in the R Programming Language." }, { "code": null, "e": 25285, "s": 25073, "text": "We are taking a column in the data frame and passing it into another variable by using the selection method. The selection method can be defined as choosing a column from a data frame using the ” [[]]” operator." }, { "code": null, "e": 25293, "s": 25285, "text": "Steps –" }, { "code": null, "e": 25311, "s": 25293, "text": "Create data frame" }, { "code": null, "e": 25341, "s": 25311, "text": "Select column to be converted" }, { "code": null, "e": 25365, "s": 25341, "text": "Assign it to a variable" }, { "code": null, "e": 25398, "s": 25365, "text": "Display data frame so generated." }, { "code": null, "e": 25406, "s": 25398, "text": "Syntax:" }, { "code": null, "e": 25428, "s": 25406, "text": "dataframe[[‘column’]]" }, { "code": null, "e": 25437, "s": 25428, "text": "Example:" }, { "code": null, "e": 25439, "s": 25437, "text": "R" }, { "code": "# create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data) # convert id column into a vectorcolumn_data=data[['id']]print(column_data) # convert name column into a vectorcolumn_data1=data[['name']]print(column_data1)", "e": 25733, "s": 25439, "text": null }, { "code": null, "e": 25741, "s": 25733, "text": "Output:" }, { "code": null, "e": 25823, "s": 25741, "text": "We can convert every row or entire dataframe by using a method called as.vector()" }, { "code": null, "e": 25832, "s": 25823, "text": "Approach" }, { "code": null, "e": 25849, "s": 25832, "text": "Create dataframe" }, { "code": null, "e": 25876, "s": 25849, "text": "Select row to be converted" }, { "code": null, "e": 25900, "s": 25876, "text": "Pass it to the function" }, { "code": null, "e": 25915, "s": 25900, "text": "Display result" }, { "code": null, "e": 25923, "s": 25915, "text": "Syntax:" }, { "code": null, "e": 25952, "s": 25923, "text": "as.vector(t(dataframe_name))" }, { "code": null, "e": 26100, "s": 25952, "text": "Where t is the transpose of the dataframe. If t is not specified, the output is both rows and column names. If it is specified output is only rows." }, { "code": null, "e": 26134, "s": 26100, "text": "Example: without t specification." }, { "code": null, "e": 26136, "s": 26134, "text": "R" }, { "code": "# create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data)print(\"-----------\") # converting 1 st row to a vectoras.vector((data[1,]))print(\"-----------\") # converting 2nd row to a vectoras.vector((data[2,]))print(\"-----------\") # converting 3 rd row to a vectoras.vector((data[3,]))print(\"-----------\")", "e": 26517, "s": 26136, "text": null }, { "code": null, "e": 26525, "s": 26517, "text": "Output:" }, { "code": null, "e": 26543, "s": 26525, "text": "Example: Using t " }, { "code": null, "e": 26545, "s": 26543, "text": "R" }, { "code": "# create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data)print(\"-----------\") # converting 1 st row to a vectoras.vector(t(data[1,]))print(\"-----------\") # converting 2nd row to a vectoras.vector(t(data[2,]))print(\"-----------\") # converting 3 rd row to a vectoras.vector(t(data[3,]))print(\"-----------\")", "e": 26929, "s": 26545, "text": null }, { "code": null, "e": 26937, "s": 26929, "text": "Output:" }, { "code": null, "e": 26946, "s": 26937, "text": "Example:" }, { "code": null, "e": 26948, "s": 26946, "text": "R" }, { "code": "# create vectorsid=c(7058,7084,7098)name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,name) print(data)print(\"-----------\") # converting all dataframe to a vectoras.vector(t(data))", "e": 27161, "s": 26948, "text": null }, { "code": null, "e": 27169, "s": 27161, "text": "Output:" }, { "code": null, "e": 27181, "s": 27169, "text": "Example 2 :" }, { "code": null, "e": 27183, "s": 27181, "text": "R" }, { "code": "# create vectorsid=c(7058,7084,7098)address=c('guntur','hyd','kothapeta')name=c('sravan','karthik','nikhil') # passing into dataframedata=data.frame(id,address,name) print(data)print(\"-----dataframe row to a vector------\") # converting dataframe to a vectoras.vector(t(data)) print(\"-----dataframe column to a vector------\") # converting dataframe 1 st column to a vectordata1=data[['id']]print(data1) # converting dataframe 2 nd column to a vectordata1=data[['address']]print(data1) # converting dataframe 3 rd column to a vectordata1=data[['name']]print(data1)", "e": 27755, "s": 27183, "text": null }, { "code": null, "e": 27763, "s": 27755, "text": "Output:" }, { "code": null, "e": 27770, "s": 27763, "text": "Picked" }, { "code": null, "e": 27791, "s": 27770, "text": "R DataFrame-Programs" }, { "code": null, "e": 27803, "s": 27791, "text": "R-DataFrame" }, { "code": null, "e": 27814, "s": 27803, "text": "R Language" }, { "code": null, "e": 27825, "s": 27814, "text": "R Programs" }, { "code": null, "e": 27923, "s": 27825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27932, "s": 27923, "text": "Comments" }, { "code": null, "e": 27945, "s": 27932, "text": "Old Comments" }, { "code": null, "e": 27977, "s": 27945, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 28029, "s": 27977, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 28073, "s": 28029, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28125, "s": 28073, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28174, "s": 28125, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 28218, "s": 28174, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28267, "s": 28218, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 28325, "s": 28267, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28374, "s": 28325, "text": "How to filter R DataFrame by values in a column?" } ]
How to use metric learning: embedding is all you need | by Ivan Panshin | Towards Data Science
One of the most simplest and common tasks in machine learning is classification. For instance, in computer vision you want to be able to fine-tune the last layers of common convolutional neural networks (CNN) to correctly classify samples into some categories (classes). However, there are several fundamentally different ways to achieve that. Metric learning is one of them, and today I would like to share with you how to correctly use it. In order to make things practical we’re going to look at Supervised Contrastive Learning (SupCon), which is a part of Contrastive Learning, which, in turn, is a part of Metric Learning, but more on that later. The complete code can be found in the GitHub repo. Before we dive into metric learning, it’s actually a good idea to first understand how the task of classification is usually solved. One of the most important ideas of practical computer vision today is convolutional neural networks, and they consist of 2 parts: encoder and head (in this case — classifier). First — you take an image and compute a set of features that captures the important qualities of that image. This is done using convolution and pooling operations (that’s why it’s called convolutional neural networks). After that — you unsqueeze those features into the single vector, and use a regular fully-connected neural network to perform the classification. In practice, you take some model (for example, ResNet, DenseNet, EfficientNet, etc) that is pretrained on a big dataset (like ImageNet), and fine-tune it on your task (either just the last layers, or the whole model). However, there are several things to note here. First of all, usually you only care about the outputs of FC part of the network. That is, you take its outputs, and supply them to the loss function in order to keep the model learning. In order words, you don’t really care what happens in the middle of the network (for example, with features from the encoder). Second of all, (again, usually) you train this whole thing with some basic loss function like Cross-Entropy. In order to gain a better intuition about this 2 step process (encoder + FC) you can think about it as follows: encoder maps an image into some high dimensional space (for example, in case of ResNet18 we’re talking about 512 dimensions, and for Resnet101– 2048). After that, the objective of FC is to draw a line between these dots that represent samples in order to map them to classes. And these 2 things are trained at the same time. So you’re trying to optimize features and “drawing the line in high dimensional space” jointly. What’s wrong with that approach? Well, nothing, really. It actually works just fine. But it doesn’t mean that there isn’t another way. One of the most interesting ideas (at least personally for me) in the modern machine learning is called metric learning (or deep metric learning). In simple terms: what if, instead of going for the outputs of FC layer, we take a closer look at features that are generated by the encoder. What if we manage to optimize those features with some loss function, rather that the logits from the end of the network. And this is actually what metric learning is about: generating good features (embeddings) with an encoder. But what does it mean — “good”? Well, if you think about it, in case of computer vision you want to have similar features for images that are similar, and very distinct features for images that are nothing alike. Okay, suppose in Metric Learning all we care about is good features. But what’s the deal with Supervised Contrastive Learning? To be honest, there is nothing that special about this specific approach. It’s just a fairly recent paper that proposed some nice tricks, and an interesting 2 step approach: Train a good encoder, that is capable of generating good features for images.Freeze the encoder, add a FC layer, and train just that. Train a good encoder, that is capable of generating good features for images. Freeze the encoder, add a FC layer, and train just that. You might be wondering what’s the difference with regular classifier training then. The difference is that in regular training you train encoder and FC at the same time. On the other hand, here, you first train a decent encoder, then freeze it (don’t train anymore), and train only FC. The intuition behind that logic is that if we manage to first generate really good features for images, it should be easy to optimize FC (whose objective, as we noted earlier, is to optimize the line that separates the samples). Let’s dig into the details of SupCon implementation. Before checking the training loop, one thing you should understand about SupCon is what model is being trained. That’s quite simple: encoder (like ResNet, DenseNet, EffNet, etc), but without regular FC layers for classification. Instead of classification head, here we have a projection head. Projection head is a sequence of 2 FC layers that maps encoder features to a lower dimensional space (usually 128 dimensional, you can even see that value on the picture above). The reason for projection head is that it’s simply easier for model to learn with 128 carefully selected features rather than all several thousand features that come from the encoder. All right, time to finally check the training loop. Construct a batch of N images. Unlike other Metric Learning approaches, you don’t need to care too much about the choice of those samples. Just take as many as you can, the rest will be handled by the loss.Forward those images thought the network in pairs, where a pair is constructed as [augmentation(image_i), augmentation(image_i)], get embeddings. Normalize them.Take some image as an anchor. Find all the images of the same class in the batch. Use them as positive samples. Find all the images of difference classes. Use them as negative samples.Apply SupCon loss to the normalized embeddings, making positive samples closer to each other, and at the same time — more apart from negative samples.After the training is done, delete projection head, and add FC on top of encoder (just like in the regular classification training). Freeze the encoder, and fine-tune the FC. Construct a batch of N images. Unlike other Metric Learning approaches, you don’t need to care too much about the choice of those samples. Just take as many as you can, the rest will be handled by the loss. Forward those images thought the network in pairs, where a pair is constructed as [augmentation(image_i), augmentation(image_i)], get embeddings. Normalize them. Take some image as an anchor. Find all the images of the same class in the batch. Use them as positive samples. Find all the images of difference classes. Use them as negative samples. Apply SupCon loss to the normalized embeddings, making positive samples closer to each other, and at the same time — more apart from negative samples. After the training is done, delete projection head, and add FC on top of encoder (just like in the regular classification training). Freeze the encoder, and fine-tune the FC. Several thing to keep in mind here. First, after the training is done, it’s more profitable to get rid of the projection head, and use features before it. Authors explain this fact due to the loss of information in the head, since we lower the embedding’s size. Second, the choice of augmentations is important. Authors propose a combination of cropping and color jittering. Third, Supcon deals with all the images in the batch at once (so, no need to construct pairs or triplets). And the more images are in the batch, the easier it is for model to learn (since SupCon has a quality of implicit positive and negative hard mining). Fourth, you can actually stop at step 4. Meaning that it’s possible to do classification just with embeddings, without any FC layers. In order to do that, compute embeddings for all the train samples. Then, at validation time, for each sample compute an embedding, compare it to every train embedding (compare = cosine distance), take the most similar, take its class. There is actually a semi-official implementation of SupCon in PyTorch. Unfortunately, it contains very irritating hidden bugs. One of the most serious ones: the creator of the repo used his own implementations of ResNets, and due to some bugs in it, the batch size is twice lower than it can be with regular torchvision models. On top of that — the repo has no validation or visualizations, so you have no idea when to stop training. In my repo I fix all these issues, and add more tricks for a stable training. To be more precise, in my implementation you have access to: Augmentations with albumentationsYaml configst-SNE visualizations2-step validation (for features before and after the projection head) using metrics like AMI, NMI, mAP, precision_at_1, etc PyTorch Metric Learning.Exponential Moving Average for a more stable training, and Stochastic Moving Average for a better generalization and just overall performance.Automatic Mixed Precision training in order to be able to train with a bigger batch size (roughly by a factor of 2).LabelSmoothing loss, and LRFinder for the second stage of the training (FC).Support of timm models and jettify optimizersFixing the seeds in order to make the training deterministic.Saving weights based on validation, logs — to regular .txt files, as well as TensorBoard logs for future examination. Augmentations with albumentations Yaml configs t-SNE visualizations 2-step validation (for features before and after the projection head) using metrics like AMI, NMI, mAP, precision_at_1, etc PyTorch Metric Learning. Exponential Moving Average for a more stable training, and Stochastic Moving Average for a better generalization and just overall performance. Automatic Mixed Precision training in order to be able to train with a bigger batch size (roughly by a factor of 2). LabelSmoothing loss, and LRFinder for the second stage of the training (FC). Support of timm models and jettify optimizers Fixing the seeds in order to make the training deterministic. Saving weights based on validation, logs — to regular .txt files, as well as TensorBoard logs for future examination. From the box the repo has support for Cifar10, and Cifar100. However, it’s quite trivial to add your own datasets. In order to run the whole pipleline, do the following: python train.py --config_name configs/train/train_supcon_resnet18_cifar10_stage1.ymlpython swa.py --config_name configs/train/swa_supcon_resnet18_cifar100_stage1.ymlpython train.py --config_name configs/train/train_supcon_resnet18_cifar10_stage2.ymlpython swa.py --config_name configs/train/swa_supcon_resnet18_cifar100_stage2.yml After that you can check t-SNE visualizations in the corresponding Jupyter notebook. For example, for Cifar10 and Cifar100 you can expect something as follows: Metric Learning is a very powerful thing. However, it’s been quite hard for me to reach the level of accuracy that regular CE/LabelSmoothing can provide. Moreover, it also may be computationally expensive and unstable during training. I tested SupCon and other metric losses on variety of tasks (classification, out of distribution predictions, generalization to new classes, etc), and the advantage of using something like SupCon is unclear. Wait a minute, what’s the point then? I personally see 2 things here. First — SupCon (and other Metric Learning approaches) still can provide more structured clusters, than CE, since it directly optimizes that property. Second — it’s still very beneficial to have one more skill/tool that you might try. So it’s possible that with a better set of augmentations, or a different dataset (maybe with more fine-grained classes) SupCon can yield better results, not just on par with regular classification training. So we just have to try and experiment. No free lunch, right?
[ { "code": null, "e": 390, "s": 46, "text": "One of the most simplest and common tasks in machine learning is classification. For instance, in computer vision you want to be able to fine-tune the last layers of common convolutional neural networks (CNN) to correctly classify samples into some categories (classes). However, there are several fundamentally different ways to achieve that." }, { "code": null, "e": 698, "s": 390, "text": "Metric learning is one of them, and today I would like to share with you how to correctly use it. In order to make things practical we’re going to look at Supervised Contrastive Learning (SupCon), which is a part of Contrastive Learning, which, in turn, is a part of Metric Learning, but more on that later." }, { "code": null, "e": 749, "s": 698, "text": "The complete code can be found in the GitHub repo." }, { "code": null, "e": 1058, "s": 749, "text": "Before we dive into metric learning, it’s actually a good idea to first understand how the task of classification is usually solved. One of the most important ideas of practical computer vision today is convolutional neural networks, and they consist of 2 parts: encoder and head (in this case — classifier)." }, { "code": null, "e": 1641, "s": 1058, "text": "First — you take an image and compute a set of features that captures the important qualities of that image. This is done using convolution and pooling operations (that’s why it’s called convolutional neural networks). After that — you unsqueeze those features into the single vector, and use a regular fully-connected neural network to perform the classification. In practice, you take some model (for example, ResNet, DenseNet, EfficientNet, etc) that is pretrained on a big dataset (like ImageNet), and fine-tune it on your task (either just the last layers, or the whole model)." }, { "code": null, "e": 2111, "s": 1641, "text": "However, there are several things to note here. First of all, usually you only care about the outputs of FC part of the network. That is, you take its outputs, and supply them to the loss function in order to keep the model learning. In order words, you don’t really care what happens in the middle of the network (for example, with features from the encoder). Second of all, (again, usually) you train this whole thing with some basic loss function like Cross-Entropy." }, { "code": null, "e": 2644, "s": 2111, "text": "In order to gain a better intuition about this 2 step process (encoder + FC) you can think about it as follows: encoder maps an image into some high dimensional space (for example, in case of ResNet18 we’re talking about 512 dimensions, and for Resnet101– 2048). After that, the objective of FC is to draw a line between these dots that represent samples in order to map them to classes. And these 2 things are trained at the same time. So you’re trying to optimize features and “drawing the line in high dimensional space” jointly." }, { "code": null, "e": 2779, "s": 2644, "text": "What’s wrong with that approach? Well, nothing, really. It actually works just fine. But it doesn’t mean that there isn’t another way." }, { "code": null, "e": 3296, "s": 2779, "text": "One of the most interesting ideas (at least personally for me) in the modern machine learning is called metric learning (or deep metric learning). In simple terms: what if, instead of going for the outputs of FC layer, we take a closer look at features that are generated by the encoder. What if we manage to optimize those features with some loss function, rather that the logits from the end of the network. And this is actually what metric learning is about: generating good features (embeddings) with an encoder." }, { "code": null, "e": 3509, "s": 3296, "text": "But what does it mean — “good”? Well, if you think about it, in case of computer vision you want to have similar features for images that are similar, and very distinct features for images that are nothing alike." }, { "code": null, "e": 3810, "s": 3509, "text": "Okay, suppose in Metric Learning all we care about is good features. But what’s the deal with Supervised Contrastive Learning? To be honest, there is nothing that special about this specific approach. It’s just a fairly recent paper that proposed some nice tricks, and an interesting 2 step approach:" }, { "code": null, "e": 3944, "s": 3810, "text": "Train a good encoder, that is capable of generating good features for images.Freeze the encoder, add a FC layer, and train just that." }, { "code": null, "e": 4022, "s": 3944, "text": "Train a good encoder, that is capable of generating good features for images." }, { "code": null, "e": 4079, "s": 4022, "text": "Freeze the encoder, add a FC layer, and train just that." }, { "code": null, "e": 4594, "s": 4079, "text": "You might be wondering what’s the difference with regular classifier training then. The difference is that in regular training you train encoder and FC at the same time. On the other hand, here, you first train a decent encoder, then freeze it (don’t train anymore), and train only FC. The intuition behind that logic is that if we manage to first generate really good features for images, it should be easy to optimize FC (whose objective, as we noted earlier, is to optimize the line that separates the samples)." }, { "code": null, "e": 4647, "s": 4594, "text": "Let’s dig into the details of SupCon implementation." }, { "code": null, "e": 4876, "s": 4647, "text": "Before checking the training loop, one thing you should understand about SupCon is what model is being trained. That’s quite simple: encoder (like ResNet, DenseNet, EffNet, etc), but without regular FC layers for classification." }, { "code": null, "e": 5302, "s": 4876, "text": "Instead of classification head, here we have a projection head. Projection head is a sequence of 2 FC layers that maps encoder features to a lower dimensional space (usually 128 dimensional, you can even see that value on the picture above). The reason for projection head is that it’s simply easier for model to learn with 128 carefully selected features rather than all several thousand features that come from the encoder." }, { "code": null, "e": 5354, "s": 5302, "text": "All right, time to finally check the training loop." }, { "code": null, "e": 6230, "s": 5354, "text": "Construct a batch of N images. Unlike other Metric Learning approaches, you don’t need to care too much about the choice of those samples. Just take as many as you can, the rest will be handled by the loss.Forward those images thought the network in pairs, where a pair is constructed as [augmentation(image_i), augmentation(image_i)], get embeddings. Normalize them.Take some image as an anchor. Find all the images of the same class in the batch. Use them as positive samples. Find all the images of difference classes. Use them as negative samples.Apply SupCon loss to the normalized embeddings, making positive samples closer to each other, and at the same time — more apart from negative samples.After the training is done, delete projection head, and add FC on top of encoder (just like in the regular classification training). Freeze the encoder, and fine-tune the FC." }, { "code": null, "e": 6437, "s": 6230, "text": "Construct a batch of N images. Unlike other Metric Learning approaches, you don’t need to care too much about the choice of those samples. Just take as many as you can, the rest will be handled by the loss." }, { "code": null, "e": 6599, "s": 6437, "text": "Forward those images thought the network in pairs, where a pair is constructed as [augmentation(image_i), augmentation(image_i)], get embeddings. Normalize them." }, { "code": null, "e": 6784, "s": 6599, "text": "Take some image as an anchor. Find all the images of the same class in the batch. Use them as positive samples. Find all the images of difference classes. Use them as negative samples." }, { "code": null, "e": 6935, "s": 6784, "text": "Apply SupCon loss to the normalized embeddings, making positive samples closer to each other, and at the same time — more apart from negative samples." }, { "code": null, "e": 7110, "s": 6935, "text": "After the training is done, delete projection head, and add FC on top of encoder (just like in the regular classification training). Freeze the encoder, and fine-tune the FC." }, { "code": null, "e": 8111, "s": 7110, "text": "Several thing to keep in mind here. First, after the training is done, it’s more profitable to get rid of the projection head, and use features before it. Authors explain this fact due to the loss of information in the head, since we lower the embedding’s size. Second, the choice of augmentations is important. Authors propose a combination of cropping and color jittering. Third, Supcon deals with all the images in the batch at once (so, no need to construct pairs or triplets). And the more images are in the batch, the easier it is for model to learn (since SupCon has a quality of implicit positive and negative hard mining). Fourth, you can actually stop at step 4. Meaning that it’s possible to do classification just with embeddings, without any FC layers. In order to do that, compute embeddings for all the train samples. Then, at validation time, for each sample compute an embedding, compare it to every train embedding (compare = cosine distance), take the most similar, take its class." }, { "code": null, "e": 8623, "s": 8111, "text": "There is actually a semi-official implementation of SupCon in PyTorch. Unfortunately, it contains very irritating hidden bugs. One of the most serious ones: the creator of the repo used his own implementations of ResNets, and due to some bugs in it, the batch size is twice lower than it can be with regular torchvision models. On top of that — the repo has no validation or visualizations, so you have no idea when to stop training. In my repo I fix all these issues, and add more tricks for a stable training." }, { "code": null, "e": 8684, "s": 8623, "text": "To be more precise, in my implementation you have access to:" }, { "code": null, "e": 9455, "s": 8684, "text": "Augmentations with albumentationsYaml configst-SNE visualizations2-step validation (for features before and after the projection head) using metrics like AMI, NMI, mAP, precision_at_1, etc PyTorch Metric Learning.Exponential Moving Average for a more stable training, and Stochastic Moving Average for a better generalization and just overall performance.Automatic Mixed Precision training in order to be able to train with a bigger batch size (roughly by a factor of 2).LabelSmoothing loss, and LRFinder for the second stage of the training (FC).Support of timm models and jettify optimizersFixing the seeds in order to make the training deterministic.Saving weights based on validation, logs — to regular .txt files, as well as TensorBoard logs for future examination." }, { "code": null, "e": 9489, "s": 9455, "text": "Augmentations with albumentations" }, { "code": null, "e": 9502, "s": 9489, "text": "Yaml configs" }, { "code": null, "e": 9523, "s": 9502, "text": "t-SNE visualizations" }, { "code": null, "e": 9672, "s": 9523, "text": "2-step validation (for features before and after the projection head) using metrics like AMI, NMI, mAP, precision_at_1, etc PyTorch Metric Learning." }, { "code": null, "e": 9815, "s": 9672, "text": "Exponential Moving Average for a more stable training, and Stochastic Moving Average for a better generalization and just overall performance." }, { "code": null, "e": 9932, "s": 9815, "text": "Automatic Mixed Precision training in order to be able to train with a bigger batch size (roughly by a factor of 2)." }, { "code": null, "e": 10009, "s": 9932, "text": "LabelSmoothing loss, and LRFinder for the second stage of the training (FC)." }, { "code": null, "e": 10055, "s": 10009, "text": "Support of timm models and jettify optimizers" }, { "code": null, "e": 10117, "s": 10055, "text": "Fixing the seeds in order to make the training deterministic." }, { "code": null, "e": 10235, "s": 10117, "text": "Saving weights based on validation, logs — to regular .txt files, as well as TensorBoard logs for future examination." }, { "code": null, "e": 10405, "s": 10235, "text": "From the box the repo has support for Cifar10, and Cifar100. However, it’s quite trivial to add your own datasets. In order to run the whole pipleline, do the following:" }, { "code": null, "e": 10736, "s": 10405, "text": "python train.py --config_name configs/train/train_supcon_resnet18_cifar10_stage1.ymlpython swa.py --config_name configs/train/swa_supcon_resnet18_cifar100_stage1.ymlpython train.py --config_name configs/train/train_supcon_resnet18_cifar10_stage2.ymlpython swa.py --config_name configs/train/swa_supcon_resnet18_cifar100_stage2.yml" }, { "code": null, "e": 10896, "s": 10736, "text": "After that you can check t-SNE visualizations in the corresponding Jupyter notebook. For example, for Cifar10 and Cifar100 you can expect something as follows:" }, { "code": null, "e": 11339, "s": 10896, "text": "Metric Learning is a very powerful thing. However, it’s been quite hard for me to reach the level of accuracy that regular CE/LabelSmoothing can provide. Moreover, it also may be computationally expensive and unstable during training. I tested SupCon and other metric losses on variety of tasks (classification, out of distribution predictions, generalization to new classes, etc), and the advantage of using something like SupCon is unclear." }, { "code": null, "e": 11850, "s": 11339, "text": "Wait a minute, what’s the point then? I personally see 2 things here. First — SupCon (and other Metric Learning approaches) still can provide more structured clusters, than CE, since it directly optimizes that property. Second — it’s still very beneficial to have one more skill/tool that you might try. So it’s possible that with a better set of augmentations, or a different dataset (maybe with more fine-grained classes) SupCon can yield better results, not just on par with regular classification training." } ]
Find geometric sum of the series using recursion
09 Aug, 2021 Given an integer N, we need to find the geometric sum of the following series using recursion. 1 + 1/3 + 1/9 + 1/27 + ... + 1/(3^n) Examples: Input N = 5 Output: 1.49794 Input: N = 7 Output: 1.49977 Approach:In the above-mentioned problem, we are asked to use recursion. We will calculate the last term and call recursion on the remaining n-1 terms each time. The final sum returned is the result.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP implementation to Find the// geometric sum of the series using recursion #include <bits/stdc++.h>using namespace std; // function to find the sum of given seriesdouble sum(int n){ // base case if (n == 0) return 1; // calculate the sum each time double ans = 1 / (double)pow(3, n) + sum(n - 1); // return final answer return ans;} // Driver codeint main(){ // integer initialisation int n = 5; cout << sum(n) << endl; return 0;} // JAVA implementation to Find the// geometric sum of the series using recursion import java.util.*; class GFG { static double sum(int n) { // base case if (n == 0) return 1; // calculate the sum each time double ans = 1 / (double)Math.pow(3, n) + sum(n - 1); // return final answer return ans; } // Driver code public static void main(String[] args) { // integer initialisation int n = 5; // print result System.out.println(sum(n)); }} # CPP implementation to Find the# geometric sum of the series using recursion def sum(n): # base case if n == 0: return 1 # calculate the sum each time # and return final answer return 1 / pow(3, n) + sum(n-1) n = 5; print(sum(n)); // C# implementation to Find the// geometric sum of the series using recursion using System; class GFG { static double sum(int n) { // base case if (n == 0) return 1; // calculate the sum each time double ans = 1 / (double)Math.Pow(3, n) + sum(n - 1); // return final answer return ans; } // Driver code static public void Main() { int n = 5; Console.WriteLine(sum(n)); }} <script> // Javascript implementation to Find the// geometric sum of the series using recursion // function to find the sum of given seriesfunction sum(n){ // base case if (n == 0) return 1; // calculate the sum each time var ans = 1 / Math.pow(3, n) + sum(n - 1); // return final answer return ans;} // Driver code// integer initialisationvar n = 5;document.write( sum(n).toFixed(5)); </script> 1.49794 Time Complexity: O(N)Auxiliary Space: O(N) itsok pankajsharmagfg Algorithms Recursion Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Aug, 2021" }, { "code": null, "e": 149, "s": 52, "text": "Given an integer N, we need to find the geometric sum of the following series using recursion. " }, { "code": null, "e": 188, "s": 149, "text": "1 + 1/3 + 1/9 + 1/27 + ... + 1/(3^n) " }, { "code": null, "e": 200, "s": 188, "text": "Examples: " }, { "code": null, "e": 259, "s": 200, "text": "Input N = 5 \nOutput: 1.49794\n\nInput: N = 7\nOutput: 1.49977" }, { "code": null, "e": 512, "s": 261, "text": "Approach:In the above-mentioned problem, we are asked to use recursion. We will calculate the last term and call recursion on the remaining n-1 terms each time. The final sum returned is the result.Below is the implementation of the above approach: " }, { "code": null, "e": 516, "s": 512, "text": "C++" }, { "code": null, "e": 521, "s": 516, "text": "Java" }, { "code": null, "e": 529, "s": 521, "text": "Python3" }, { "code": null, "e": 532, "s": 529, "text": "C#" }, { "code": null, "e": 543, "s": 532, "text": "Javascript" }, { "code": "// CPP implementation to Find the// geometric sum of the series using recursion #include <bits/stdc++.h>using namespace std; // function to find the sum of given seriesdouble sum(int n){ // base case if (n == 0) return 1; // calculate the sum each time double ans = 1 / (double)pow(3, n) + sum(n - 1); // return final answer return ans;} // Driver codeint main(){ // integer initialisation int n = 5; cout << sum(n) << endl; return 0;}", "e": 1021, "s": 543, "text": null }, { "code": "// JAVA implementation to Find the// geometric sum of the series using recursion import java.util.*; class GFG { static double sum(int n) { // base case if (n == 0) return 1; // calculate the sum each time double ans = 1 / (double)Math.pow(3, n) + sum(n - 1); // return final answer return ans; } // Driver code public static void main(String[] args) { // integer initialisation int n = 5; // print result System.out.println(sum(n)); }}", "e": 1565, "s": 1021, "text": null }, { "code": "# CPP implementation to Find the# geometric sum of the series using recursion def sum(n): # base case if n == 0: return 1 # calculate the sum each time # and return final answer return 1 / pow(3, n) + sum(n-1) n = 5; print(sum(n));", "e": 1830, "s": 1565, "text": null }, { "code": "// C# implementation to Find the// geometric sum of the series using recursion using System; class GFG { static double sum(int n) { // base case if (n == 0) return 1; // calculate the sum each time double ans = 1 / (double)Math.Pow(3, n) + sum(n - 1); // return final answer return ans; } // Driver code static public void Main() { int n = 5; Console.WriteLine(sum(n)); }}", "e": 2296, "s": 1830, "text": null }, { "code": "<script> // Javascript implementation to Find the// geometric sum of the series using recursion // function to find the sum of given seriesfunction sum(n){ // base case if (n == 0) return 1; // calculate the sum each time var ans = 1 / Math.pow(3, n) + sum(n - 1); // return final answer return ans;} // Driver code// integer initialisationvar n = 5;document.write( sum(n).toFixed(5)); </script>", "e": 2719, "s": 2296, "text": null }, { "code": null, "e": 2727, "s": 2719, "text": "1.49794" }, { "code": null, "e": 2772, "s": 2729, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 2778, "s": 2772, "text": "itsok" }, { "code": null, "e": 2794, "s": 2778, "text": "pankajsharmagfg" }, { "code": null, "e": 2805, "s": 2794, "text": "Algorithms" }, { "code": null, "e": 2815, "s": 2805, "text": "Recursion" }, { "code": null, "e": 2825, "s": 2815, "text": "Recursion" }, { "code": null, "e": 2836, "s": 2825, "text": "Algorithms" } ]
exec command in Linux with examples
15 May, 2019 exec command in Linux is used to execute a command from the bash itself. This command does not create a new process it just replaces the bash with the command to be executed. If the exec command is successful, it does not return to the calling process. Syntax: exec [-cl] [-a name] [command [arguments]] [redirection ...] Options: c: It is used to execute the command with empty environment. a name: Used to pass a name as the zeroth argument of the command. l: Used to pass dash as the zeroth argument of the command. Note: exec command does not create a new process. When we run the exec command from the terminal, the ongoing terminal process is replaced by the command that is provided as the argument for the exec command. The exec command can be used in two modes: Exec with a command as an argument: In the first mode, the exec tries to execute it as a command passing the remaining arguments, if any, to that command and managing the redirections, if any.Example 1:Example 2:The exec command searches the path mentioned in the $PATH variable to find a command to be executed. If the command is not found the exec command as well as the shell exits in an error. Example 1: Example 2: The exec command searches the path mentioned in the $PATH variable to find a command to be executed. If the command is not found the exec command as well as the shell exits in an error. Exec without a command: If no command is supplied, the redirections can be used to modify the current shell environment. This is useful as it allows us to change the file descriptors of the shell as per our desire. The process continues even after the exec command unlike the previous case but now the standard input, output, and error are modified according to the redirections.Example:Here the exec command changes the standard out of the shell to the tmp file and so all the commands executed after the exec command write their results in that file. This is one of the most common ways of using exec without any commands. Example: Here the exec command changes the standard out of the shell to the tmp file and so all the commands executed after the exec command write their results in that file. This is one of the most common ways of using exec without any commands. linux-command Linux-Shell-Commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 May, 2019" }, { "code": null, "e": 306, "s": 53, "text": "exec command in Linux is used to execute a command from the bash itself. This command does not create a new process it just replaces the bash with the command to be executed. If the exec command is successful, it does not return to the calling process." }, { "code": null, "e": 314, "s": 306, "text": "Syntax:" }, { "code": null, "e": 376, "s": 314, "text": "exec [-cl] [-a name] [command [arguments]] [redirection ...]\n" }, { "code": null, "e": 385, "s": 376, "text": "Options:" }, { "code": null, "e": 446, "s": 385, "text": "c: It is used to execute the command with empty environment." }, { "code": null, "e": 513, "s": 446, "text": "a name: Used to pass a name as the zeroth argument of the command." }, { "code": null, "e": 573, "s": 513, "text": "l: Used to pass dash as the zeroth argument of the command." }, { "code": null, "e": 782, "s": 573, "text": "Note: exec command does not create a new process. When we run the exec command from the terminal, the ongoing terminal process is replaced by the command that is provided as the argument for the exec command." }, { "code": null, "e": 825, "s": 782, "text": "The exec command can be used in two modes:" }, { "code": null, "e": 1223, "s": 825, "text": "Exec with a command as an argument: In the first mode, the exec tries to execute it as a command passing the remaining arguments, if any, to that command and managing the redirections, if any.Example 1:Example 2:The exec command searches the path mentioned in the $PATH variable to find a command to be executed. If the command is not found the exec command as well as the shell exits in an error." }, { "code": null, "e": 1234, "s": 1223, "text": "Example 1:" }, { "code": null, "e": 1245, "s": 1234, "text": "Example 2:" }, { "code": null, "e": 1431, "s": 1245, "text": "The exec command searches the path mentioned in the $PATH variable to find a command to be executed. If the command is not found the exec command as well as the shell exits in an error." }, { "code": null, "e": 2056, "s": 1431, "text": "Exec without a command: If no command is supplied, the redirections can be used to modify the current shell environment. This is useful as it allows us to change the file descriptors of the shell as per our desire. The process continues even after the exec command unlike the previous case but now the standard input, output, and error are modified according to the redirections.Example:Here the exec command changes the standard out of the shell to the tmp file and so all the commands executed after the exec command write their results in that file. This is one of the most common ways of using exec without any commands." }, { "code": null, "e": 2065, "s": 2056, "text": "Example:" }, { "code": null, "e": 2303, "s": 2065, "text": "Here the exec command changes the standard out of the shell to the tmp file and so all the commands executed after the exec command write their results in that file. This is one of the most common ways of using exec without any commands." }, { "code": null, "e": 2317, "s": 2303, "text": "linux-command" }, { "code": null, "e": 2338, "s": 2317, "text": "Linux-Shell-Commands" }, { "code": null, "e": 2345, "s": 2338, "text": "Picked" }, { "code": null, "e": 2356, "s": 2345, "text": "Linux-Unix" } ]
Perl | Special Character Classes in Regular Expressions
27 Sep, 2019 There are many different character classes implemented in Perl and some of them used so frequently that a special sequence is created for them. The aim of creating a special sequence is to make the code more readable and shorter. The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit. The \d is standardized to “digit”. The main advantage is that the user can easily write in shorter form and can easily read it. There are two ways to use this special character class. Let’s take an example for better understanding to know how to match the character string.Example:/#[MNOPQ]-\d\d\d/ The above given character string will be match as below.#M-12345 #N-66666 Here, we can also make the use of quantifiers by putting that on the character class.Example:/#[MNOPQ]-\d{5}/ The above-given example is same as the previous regex and it allows any number of digits after the dash and it can be written as /#[MNOPQ]-\d+/.The second method is used in the larger character classes. The \d is put in square bracket and match single character digit.Example:[\dABCDEFDEFGHIJKLMN] There can be match a single digit or match any of the capital letters A, B, C, D, E, F, G, H, I, J, K, L, M or N. It can be written in shorter form by using dash(-). Then it will be like:[\dA-N] PO SIX character classes: PO SIX are the standards to maintaining the compatibility between operating systems and defines the application programming interface(API), with command line shells and utility interfaces. It also specifies a number of “groups of characters” with a name such as (alpha, alnum, ascii, blank etc). The PO SIX character classes always exists in the form of [:class:] where class is the name and the [: and :] are the delimiters. POSIX character classes always appear inside the bracketed character classes. These classes are a convenient and explanatory way of listing a group of characters.Syntax:$string =~ /[[:class:]]/Here class can be alpha, alnum, ascii etc.POSIX character classes support larger bracketed character classes as shown below:[01[:Class:]%] Here it will match ‘0’, ‘1’ and any Character Classes and the percent sign. Perl provides support for different PO SIX character classes as shown below in table:ClassDescriptionalphaAny alphabetical character (“[A-Za-z]”)alnumAny alphanumeric character (“[A-Za-z0-9]”).asciiAny character in the ASCII character set.blankA space or a horizontal tabcntrlAny control character.digitAny decimal digit (“[0-9]”).graphAny printable character, excluding a spacelowerAny lowercase character (“[a-z]”)punctAny graphical characterspaceAny whitespace characterupperAny uppercase character (“[A-Z]”)xdigitAny hexadecimal digit (“[0-9a-fA-F]”)wordA Perl extension (“[A-Za-z0-9_]”), equivalent to “\w”Word character \w[0-9a-zA-Z_]: The \w belongs to word character class. The \w matches any single alphanumeric character which may be an alphabetic character, or a decimal digit or punctuation character such as underscore(_). It will match only single character word, not the whole word. If you want to match the whole word then use \w+.Whitespace \s[\t\n\f\r ]: The character class \s will match a single character i.e. a whitespace. It will also match the 5 characters i.e. \t -horizontal tab, \n-the newline, \f-the form feed, \r-the carriage return, and the space. In Perl v5.18, a new character to be introduced which is matches the \cK – vertical tab .Negated character classes \D, \W, \S : There are more than 110, 000 Unicode characters available in this world. To negate a character class just use caret(^) symbol. It will negate the specified character after the symbol or even a range. In negated character classes we use [^\d] to negate the digits from 0 to 9. But in place of [^\d] we can use simply \D to negate the digits from 0 to 9. Following table illustrate the special negated character classes:Character ClassNegatedMeaningDescription\d\D[^\d]matches any non-digit character\s\S[^\s]matches any non-whitespace character\w\W[^\w]matches any non-“word” characterUnicode character classes: The Unicode is a definition of “all” the existing characters and the Unicode Standard provides a unique number for each and every character, and it is platform independent. There are more than 100, 000 character available in this world and each character described as a character point. But some of the characters are grouped together.Syntax:\p{...any character...} This syntax is used to match a single character from one of the groups. If you need to match anything except a specified character then you can use the corresponding \P{...any character...} expression. Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit. The \d is standardized to “digit”. The main advantage is that the user can easily write in shorter form and can easily read it. There are two ways to use this special character class. Let’s take an example for better understanding to know how to match the character string.Example:/#[MNOPQ]-\d\d\d/ The above given character string will be match as below.#M-12345 #N-66666 Here, we can also make the use of quantifiers by putting that on the character class.Example:/#[MNOPQ]-\d{5}/ The above-given example is same as the previous regex and it allows any number of digits after the dash and it can be written as /#[MNOPQ]-\d+/.The second method is used in the larger character classes. The \d is put in square bracket and match single character digit.Example:[\dABCDEFDEFGHIJKLMN] There can be match a single digit or match any of the capital letters A, B, C, D, E, F, G, H, I, J, K, L, M or N. It can be written in shorter form by using dash(-). Then it will be like:[\dA-N] Example: /#[MNOPQ]-\d\d\d/ The above given character string will be match as below. #M-12345 #N-66666 Here, we can also make the use of quantifiers by putting that on the character class. Example: /#[MNOPQ]-\d{5}/ The above-given example is same as the previous regex and it allows any number of digits after the dash and it can be written as /#[MNOPQ]-\d+/. The second method is used in the larger character classes. The \d is put in square bracket and match single character digit. Example: [\dABCDEFDEFGHIJKLMN] There can be match a single digit or match any of the capital letters A, B, C, D, E, F, G, H, I, J, K, L, M or N. It can be written in shorter form by using dash(-). Then it will be like: [\dA-N] PO SIX character classes: PO SIX are the standards to maintaining the compatibility between operating systems and defines the application programming interface(API), with command line shells and utility interfaces. It also specifies a number of “groups of characters” with a name such as (alpha, alnum, ascii, blank etc). The PO SIX character classes always exists in the form of [:class:] where class is the name and the [: and :] are the delimiters. POSIX character classes always appear inside the bracketed character classes. These classes are a convenient and explanatory way of listing a group of characters.Syntax:$string =~ /[[:class:]]/Here class can be alpha, alnum, ascii etc.POSIX character classes support larger bracketed character classes as shown below:[01[:Class:]%] Here it will match ‘0’, ‘1’ and any Character Classes and the percent sign. Perl provides support for different PO SIX character classes as shown below in table:ClassDescriptionalphaAny alphabetical character (“[A-Za-z]”)alnumAny alphanumeric character (“[A-Za-z0-9]”).asciiAny character in the ASCII character set.blankA space or a horizontal tabcntrlAny control character.digitAny decimal digit (“[0-9]”).graphAny printable character, excluding a spacelowerAny lowercase character (“[a-z]”)punctAny graphical characterspaceAny whitespace characterupperAny uppercase character (“[A-Z]”)xdigitAny hexadecimal digit (“[0-9a-fA-F]”)wordA Perl extension (“[A-Za-z0-9_]”), equivalent to “\w” Syntax: $string =~ /[[:class:]]/ Here class can be alpha, alnum, ascii etc. POSIX character classes support larger bracketed character classes as shown below: [01[:Class:]%] Here it will match ‘0’, ‘1’ and any Character Classes and the percent sign. Perl provides support for different PO SIX character classes as shown below in table: Word character \w[0-9a-zA-Z_]: The \w belongs to word character class. The \w matches any single alphanumeric character which may be an alphabetic character, or a decimal digit or punctuation character such as underscore(_). It will match only single character word, not the whole word. If you want to match the whole word then use \w+. Whitespace \s[\t\n\f\r ]: The character class \s will match a single character i.e. a whitespace. It will also match the 5 characters i.e. \t -horizontal tab, \n-the newline, \f-the form feed, \r-the carriage return, and the space. In Perl v5.18, a new character to be introduced which is matches the \cK – vertical tab . Negated character classes \D, \W, \S : There are more than 110, 000 Unicode characters available in this world. To negate a character class just use caret(^) symbol. It will negate the specified character after the symbol or even a range. In negated character classes we use [^\d] to negate the digits from 0 to 9. But in place of [^\d] we can use simply \D to negate the digits from 0 to 9. Following table illustrate the special negated character classes:Character ClassNegatedMeaningDescription\d\D[^\d]matches any non-digit character\s\S[^\s]matches any non-whitespace character\w\W[^\w]matches any non-“word” character Unicode character classes: The Unicode is a definition of “all” the existing characters and the Unicode Standard provides a unique number for each and every character, and it is platform independent. There are more than 100, 000 character available in this world and each character described as a character point. But some of the characters are grouped together.Syntax:\p{...any character...} This syntax is used to match a single character from one of the groups. If you need to match anything except a specified character then you can use the corresponding \P{...any character...} expression. Syntax: \p{...any character...} This syntax is used to match a single character from one of the groups. If you need to match anything except a specified character then you can use the corresponding \P{...any character...} expression. shubham_singh Perl-regex Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 312, "s": 28, "text": "There are many different character classes implemented in Perl and some of them used so frequently that a special sequence is created for them. The aim of creating a special sequence is to make the code more readable and shorter. The Special Character Classes in Perl are as follows:" }, { "code": null, "e": 4767, "s": 312, "text": "Digit \\d[0-9]: The \\d is used to match any digit character and its equivalent to [0-9]. In the regex /\\d/ will match a single digit. The \\d is standardized to “digit”. The main advantage is that the user can easily write in shorter form and can easily read it. There are two ways to use this special character class. Let’s take an example for better understanding to know how to match the character string.Example:/#[MNOPQ]-\\d\\d\\d/\nThe above given character string will be match as below.#M-12345\n#N-66666\nHere, we can also make the use of quantifiers by putting that on the character class.Example:/#[MNOPQ]-\\d{5}/\nThe above-given example is same as the previous regex and it allows any number of digits after the dash and it can be written as /#[MNOPQ]-\\d+/.The second method is used in the larger character classes. The \\d is put in square bracket and match single character digit.Example:[\\dABCDEFDEFGHIJKLMN]\nThere can be match a single digit or match any of the capital letters A, B, C, D, E, F, G, H, I, J, K, L, M or N. It can be written in shorter form by using dash(-). Then it will be like:[\\dA-N]\nPO SIX character classes: PO SIX are the standards to maintaining the compatibility between operating systems and defines the application programming interface(API), with command line shells and utility interfaces. It also specifies a number of “groups of characters” with a name such as (alpha, alnum, ascii, blank etc). The PO SIX character classes always exists in the form of [:class:] where class is the name and the [: and :] are the delimiters. POSIX character classes always appear inside the bracketed character classes. These classes are a convenient and explanatory way of listing a group of characters.Syntax:$string =~ /[[:class:]]/Here class can be alpha, alnum, ascii etc.POSIX character classes support larger bracketed character classes as shown below:[01[:Class:]%]\nHere it will match ‘0’, ‘1’ and any Character Classes and the percent sign. Perl provides support for different PO SIX character classes as shown below in table:ClassDescriptionalphaAny alphabetical character (“[A-Za-z]”)alnumAny alphanumeric character (“[A-Za-z0-9]”).asciiAny character in the ASCII character set.blankA space or a horizontal tabcntrlAny control character.digitAny decimal digit (“[0-9]”).graphAny printable character, excluding a spacelowerAny lowercase character (“[a-z]”)punctAny graphical characterspaceAny whitespace characterupperAny uppercase character (“[A-Z]”)xdigitAny hexadecimal digit (“[0-9a-fA-F]”)wordA Perl extension (“[A-Za-z0-9_]”), equivalent to “\\w”Word character \\w[0-9a-zA-Z_]: The \\w belongs to word character class. The \\w matches any single alphanumeric character which may be an alphabetic character, or a decimal digit or punctuation character such as underscore(_). It will match only single character word, not the whole word. If you want to match the whole word then use \\w+.Whitespace \\s[\\t\\n\\f\\r ]: The character class \\s will match a single character i.e. a whitespace. It will also match the 5 characters i.e. \\t -horizontal tab, \\n-the newline, \\f-the form feed, \\r-the carriage return, and the space. In Perl v5.18, a new character to be introduced which is matches the \\cK – vertical tab .Negated character classes \\D, \\W, \\S : There are more than 110, 000 Unicode characters available in this world. To negate a character class just use caret(^) symbol. It will negate the specified character after the symbol or even a range. In negated character classes we use [^\\d] to negate the digits from 0 to 9. But in place of [^\\d] we can use simply \\D to negate the digits from 0 to 9. Following table illustrate the special negated character classes:Character ClassNegatedMeaningDescription\\d\\D[^\\d]matches any non-digit character\\s\\S[^\\s]matches any non-whitespace character\\w\\W[^\\w]matches any non-“word” characterUnicode character classes: The Unicode is a definition of “all” the existing characters and the Unicode Standard provides a unique number for each and every character, and it is platform independent. There are more than 100, 000 character available in this world and each character described as a character point. But some of the characters are grouped together.Syntax:\\p{...any character...}\nThis syntax is used to match a single character from one of the groups. If you need to match anything except a specified character then you can use the corresponding \\P{...any character...} expression." }, { "code": null, "e": 5877, "s": 4767, "text": "Digit \\d[0-9]: The \\d is used to match any digit character and its equivalent to [0-9]. In the regex /\\d/ will match a single digit. The \\d is standardized to “digit”. The main advantage is that the user can easily write in shorter form and can easily read it. There are two ways to use this special character class. Let’s take an example for better understanding to know how to match the character string.Example:/#[MNOPQ]-\\d\\d\\d/\nThe above given character string will be match as below.#M-12345\n#N-66666\nHere, we can also make the use of quantifiers by putting that on the character class.Example:/#[MNOPQ]-\\d{5}/\nThe above-given example is same as the previous regex and it allows any number of digits after the dash and it can be written as /#[MNOPQ]-\\d+/.The second method is used in the larger character classes. The \\d is put in square bracket and match single character digit.Example:[\\dABCDEFDEFGHIJKLMN]\nThere can be match a single digit or match any of the capital letters A, B, C, D, E, F, G, H, I, J, K, L, M or N. It can be written in shorter form by using dash(-). Then it will be like:[\\dA-N]\n" }, { "code": null, "e": 5886, "s": 5877, "text": "Example:" }, { "code": null, "e": 5905, "s": 5886, "text": "/#[MNOPQ]-\\d\\d\\d/\n" }, { "code": null, "e": 5962, "s": 5905, "text": "The above given character string will be match as below." }, { "code": null, "e": 5981, "s": 5962, "text": "#M-12345\n#N-66666\n" }, { "code": null, "e": 6067, "s": 5981, "text": "Here, we can also make the use of quantifiers by putting that on the character class." }, { "code": null, "e": 6076, "s": 6067, "text": "Example:" }, { "code": null, "e": 6094, "s": 6076, "text": "/#[MNOPQ]-\\d{5}/\n" }, { "code": null, "e": 6239, "s": 6094, "text": "The above-given example is same as the previous regex and it allows any number of digits after the dash and it can be written as /#[MNOPQ]-\\d+/." }, { "code": null, "e": 6364, "s": 6239, "text": "The second method is used in the larger character classes. The \\d is put in square bracket and match single character digit." }, { "code": null, "e": 6373, "s": 6364, "text": "Example:" }, { "code": null, "e": 6396, "s": 6373, "text": "[\\dABCDEFDEFGHIJKLMN]\n" }, { "code": null, "e": 6584, "s": 6396, "text": "There can be match a single digit or match any of the capital letters A, B, C, D, E, F, G, H, I, J, K, L, M or N. It can be written in shorter form by using dash(-). Then it will be like:" }, { "code": null, "e": 6593, "s": 6584, "text": "[\\dA-N]\n" }, { "code": null, "e": 8065, "s": 6593, "text": "PO SIX character classes: PO SIX are the standards to maintaining the compatibility between operating systems and defines the application programming interface(API), with command line shells and utility interfaces. It also specifies a number of “groups of characters” with a name such as (alpha, alnum, ascii, blank etc). The PO SIX character classes always exists in the form of [:class:] where class is the name and the [: and :] are the delimiters. POSIX character classes always appear inside the bracketed character classes. These classes are a convenient and explanatory way of listing a group of characters.Syntax:$string =~ /[[:class:]]/Here class can be alpha, alnum, ascii etc.POSIX character classes support larger bracketed character classes as shown below:[01[:Class:]%]\nHere it will match ‘0’, ‘1’ and any Character Classes and the percent sign. Perl provides support for different PO SIX character classes as shown below in table:ClassDescriptionalphaAny alphabetical character (“[A-Za-z]”)alnumAny alphanumeric character (“[A-Za-z0-9]”).asciiAny character in the ASCII character set.blankA space or a horizontal tabcntrlAny control character.digitAny decimal digit (“[0-9]”).graphAny printable character, excluding a spacelowerAny lowercase character (“[a-z]”)punctAny graphical characterspaceAny whitespace characterupperAny uppercase character (“[A-Z]”)xdigitAny hexadecimal digit (“[0-9a-fA-F]”)wordA Perl extension (“[A-Za-z0-9_]”), equivalent to “\\w”" }, { "code": null, "e": 8073, "s": 8065, "text": "Syntax:" }, { "code": null, "e": 8098, "s": 8073, "text": "$string =~ /[[:class:]]/" }, { "code": null, "e": 8141, "s": 8098, "text": "Here class can be alpha, alnum, ascii etc." }, { "code": null, "e": 8224, "s": 8141, "text": "POSIX character classes support larger bracketed character classes as shown below:" }, { "code": null, "e": 8240, "s": 8224, "text": "[01[:Class:]%]\n" }, { "code": null, "e": 8402, "s": 8240, "text": "Here it will match ‘0’, ‘1’ and any Character Classes and the percent sign. Perl provides support for different PO SIX character classes as shown below in table:" }, { "code": null, "e": 8739, "s": 8402, "text": "Word character \\w[0-9a-zA-Z_]: The \\w belongs to word character class. The \\w matches any single alphanumeric character which may be an alphabetic character, or a decimal digit or punctuation character such as underscore(_). It will match only single character word, not the whole word. If you want to match the whole word then use \\w+." }, { "code": null, "e": 9061, "s": 8739, "text": "Whitespace \\s[\\t\\n\\f\\r ]: The character class \\s will match a single character i.e. a whitespace. It will also match the 5 characters i.e. \\t -horizontal tab, \\n-the newline, \\f-the form feed, \\r-the carriage return, and the space. In Perl v5.18, a new character to be introduced which is matches the \\cK – vertical tab ." }, { "code": null, "e": 9685, "s": 9061, "text": "Negated character classes \\D, \\W, \\S : There are more than 110, 000 Unicode characters available in this world. To negate a character class just use caret(^) symbol. It will negate the specified character after the symbol or even a range. In negated character classes we use [^\\d] to negate the digits from 0 to 9. But in place of [^\\d] we can use simply \\D to negate the digits from 0 to 9. Following table illustrate the special negated character classes:Character ClassNegatedMeaningDescription\\d\\D[^\\d]matches any non-digit character\\s\\S[^\\s]matches any non-whitespace character\\w\\W[^\\w]matches any non-“word” character" }, { "code": null, "e": 10280, "s": 9685, "text": "Unicode character classes: The Unicode is a definition of “all” the existing characters and the Unicode Standard provides a unique number for each and every character, and it is platform independent. There are more than 100, 000 character available in this world and each character described as a character point. But some of the characters are grouped together.Syntax:\\p{...any character...}\nThis syntax is used to match a single character from one of the groups. If you need to match anything except a specified character then you can use the corresponding \\P{...any character...} expression." }, { "code": null, "e": 10288, "s": 10280, "text": "Syntax:" }, { "code": null, "e": 10313, "s": 10288, "text": "\\p{...any character...}\n" }, { "code": null, "e": 10515, "s": 10313, "text": "This syntax is used to match a single character from one of the groups. If you need to match anything except a specified character then you can use the corresponding \\P{...any character...} expression." }, { "code": null, "e": 10529, "s": 10515, "text": "shubham_singh" }, { "code": null, "e": 10540, "s": 10529, "text": "Perl-regex" }, { "code": null, "e": 10545, "s": 10540, "text": "Perl" }, { "code": null, "e": 10550, "s": 10545, "text": "Perl" } ]
Plotting multiple time series on the same plot using ggplot in R
24 Jun, 2021 Time series data is hierarchical data. It is a series of data associated with a timestamp. An example of a time series is gold prices over a period or temperature range or precipitation during yearly storms. To visualize this data, R provides a handy library called ggplot. Using ggplot, we can see all sorts of plots. Along with ggplot, R also provides libraries to clean up data and transform or manipulate it to fit our visualization requirements. This article will look at one dataset from the R datasets and one dataset obtained from a CSV file. The dataset gives us the daily death counts from Covid-19 for all European Countries for March 2020. We will plot the number of deaths(y-axis) vs. day(x-axis) for every country. Data in use can be downloaded from here. Plot 1: Daily Death Count The steps for plotting are as follows: Open R Studio and open an R notebook (has more options). Save this file as .rmd, preferably in the same folder as your data. Select the Working directory to where your data is Import all the R libraries Read the data from the CSV. The data above is spread across columns. To make plotting easier, we need to format the data in the required format. Plot data Display data Example: R library(ggplot2)library(reshape2)library(dplyr) covid1 =(read.csv(file="EUCOVIDdeaths.csv",header=TRUE)[,-c(2)]) head(covid1) covid_deaths <- melt(covid1,id.vars=c("Country"),value.name="value", variable.name="Day") head(covid_deaths) covid_plot <- ggplot(data=covid_deaths, aes(x=Day, y=value, group = Country, colour = Country))+ geom_line() +labs(y= "Deaths", x = "Day")covid_plot + ggtitle("Daily Deaths for European countries in March,2020")+geom_point() covid_plot Output: Daily Deaths timeseries plot with points Plot 2: Plotting covid deaths per capita. We will be using the same data as the previous example. But here we will be dealing with per capita data. R library(ggplot2)library(reshape2)library(dplyr) covid1 =(read.csv(file="EUCOVIDdeaths.csv",header=TRUE)[,-c(2)]) head(covid1) covid_perCapita <- covid1[,c(2:17)] / covid$PopulationM covid_perCapita$Country <- covid1$Country head(covid_perCapita) covid_perCapita_deaths <- melt(covid_perCapita,id.vars=c("Country"), value.name="value", variable.name="Day") covidPerCapitaPlot <- ggplot(data=covid_perCapita_deaths, aes(x=Day, y=value, group = Country, colour = Country)) + geom_line() +labs(y= "Deaths per Capita", x = "Day") + theme_bw(base_size = 16)+ theme(axis.text.x=element_text(angle=60,hjust=1))+ ggtitle("Day-wise Covid-Deaths per Capita in Europe in 2020") covid_perCapitaPlot Output: Capita Plot First install the package: hurricaneexposuredata Before installing the package, please check the R version. To check the R version in RStudio go to Tools -> Global Options. In the window that opens, in the Basic Tab, we see the R version. #If the R version is the greater than 4 install.packages(“hurricaneexposuredata”) #For R versions lower than 4.0, please install this way install.packages(‘hurricaneexposuredata’, repos=’https://geanders.github.io/drat/’, type=’source’) Example: R library(hurricaneexposuredata)library(hurricaneexposure) rain_data <- county_rain(counties = c("01001","36005", "36047", "36061","36085", "36081", "36119","22071", "51700"), start_year = 1995, end_year = 2005, rain_limit = 50, dist_limit = 500, days_included = c(-1, 0, 1)) ggplot(data = rain_data, aes(x=fips, y=tot_precip, group=storm_id, color=storm_id)) + geom_line() Output: surindertarika1234 Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 481, "s": 28, "text": "Time series data is hierarchical data. It is a series of data associated with a timestamp. An example of a time series is gold prices over a period or temperature range or precipitation during yearly storms. To visualize this data, R provides a handy library called ggplot. Using ggplot, we can see all sorts of plots. Along with ggplot, R also provides libraries to clean up data and transform or manipulate it to fit our visualization requirements." }, { "code": null, "e": 581, "s": 481, "text": "This article will look at one dataset from the R datasets and one dataset obtained from a CSV file." }, { "code": null, "e": 759, "s": 581, "text": "The dataset gives us the daily death counts from Covid-19 for all European Countries for March 2020. We will plot the number of deaths(y-axis) vs. day(x-axis) for every country." }, { "code": null, "e": 800, "s": 759, "text": "Data in use can be downloaded from here." }, { "code": null, "e": 826, "s": 800, "text": "Plot 1: Daily Death Count" }, { "code": null, "e": 865, "s": 826, "text": "The steps for plotting are as follows:" }, { "code": null, "e": 922, "s": 865, "text": "Open R Studio and open an R notebook (has more options)." }, { "code": null, "e": 990, "s": 922, "text": "Save this file as .rmd, preferably in the same folder as your data." }, { "code": null, "e": 1041, "s": 990, "text": "Select the Working directory to where your data is" }, { "code": null, "e": 1068, "s": 1041, "text": "Import all the R libraries" }, { "code": null, "e": 1096, "s": 1068, "text": "Read the data from the CSV." }, { "code": null, "e": 1213, "s": 1096, "text": "The data above is spread across columns. To make plotting easier, we need to format the data in the required format." }, { "code": null, "e": 1223, "s": 1213, "text": "Plot data" }, { "code": null, "e": 1236, "s": 1223, "text": "Display data" }, { "code": null, "e": 1245, "s": 1236, "text": "Example:" }, { "code": null, "e": 1247, "s": 1245, "text": "R" }, { "code": "library(ggplot2)library(reshape2)library(dplyr) covid1 =(read.csv(file=\"EUCOVIDdeaths.csv\",header=TRUE)[,-c(2)]) head(covid1) covid_deaths <- melt(covid1,id.vars=c(\"Country\"),value.name=\"value\", variable.name=\"Day\") head(covid_deaths) covid_plot <- ggplot(data=covid_deaths, aes(x=Day, y=value, group = Country, colour = Country))+ geom_line() +labs(y= \"Deaths\", x = \"Day\")covid_plot + ggtitle(\"Daily Deaths for European countries in March,2020\")+geom_point() covid_plot", "e": 1782, "s": 1247, "text": null }, { "code": null, "e": 1794, "s": 1786, "text": "Output:" }, { "code": null, "e": 1837, "s": 1796, "text": "Daily Deaths timeseries plot with points" }, { "code": null, "e": 1881, "s": 1839, "text": "Plot 2: Plotting covid deaths per capita." }, { "code": null, "e": 1989, "s": 1883, "text": "We will be using the same data as the previous example. But here we will be dealing with per capita data." }, { "code": null, "e": 1993, "s": 1991, "text": "R" }, { "code": "library(ggplot2)library(reshape2)library(dplyr) covid1 =(read.csv(file=\"EUCOVIDdeaths.csv\",header=TRUE)[,-c(2)]) head(covid1) covid_perCapita <- covid1[,c(2:17)] / covid$PopulationM covid_perCapita$Country <- covid1$Country head(covid_perCapita) covid_perCapita_deaths <- melt(covid_perCapita,id.vars=c(\"Country\"), value.name=\"value\", variable.name=\"Day\") covidPerCapitaPlot <- ggplot(data=covid_perCapita_deaths, aes(x=Day, y=value, group = Country, colour = Country)) + geom_line() +labs(y= \"Deaths per Capita\", x = \"Day\") + theme_bw(base_size = 16)+ theme(axis.text.x=element_text(angle=60,hjust=1))+ ggtitle(\"Day-wise Covid-Deaths per Capita in Europe in 2020\") covid_perCapitaPlot", "e": 2714, "s": 1993, "text": null }, { "code": null, "e": 2726, "s": 2718, "text": "Output:" }, { "code": null, "e": 2740, "s": 2728, "text": "Capita Plot" }, { "code": null, "e": 2791, "s": 2742, "text": "First install the package: hurricaneexposuredata" }, { "code": null, "e": 2985, "s": 2793, "text": "Before installing the package, please check the R version. To check the R version in RStudio go to Tools -> Global Options. In the window that opens, in the Basic Tab, we see the R version. " }, { "code": null, "e": 3029, "s": 2987, "text": "#If the R version is the greater than 4 " }, { "code": null, "e": 3071, "s": 3029, "text": "install.packages(“hurricaneexposuredata”)" }, { "code": null, "e": 3127, "s": 3071, "text": "#For R versions lower than 4.0, please install this way" }, { "code": null, "e": 3226, "s": 3127, "text": "install.packages(‘hurricaneexposuredata’, repos=’https://geanders.github.io/drat/’, type=’source’)" }, { "code": null, "e": 3237, "s": 3228, "text": "Example:" }, { "code": null, "e": 3241, "s": 3239, "text": "R" }, { "code": "library(hurricaneexposuredata)library(hurricaneexposure) rain_data <- county_rain(counties = c(\"01001\",\"36005\", \"36047\", \"36061\",\"36085\", \"36081\", \"36119\",\"22071\", \"51700\"), start_year = 1995, end_year = 2005, rain_limit = 50, dist_limit = 500, days_included = c(-1, 0, 1)) ggplot(data = rain_data, aes(x=fips, y=tot_precip, group=storm_id, color=storm_id)) + geom_line()", "e": 3752, "s": 3241, "text": null }, { "code": null, "e": 3764, "s": 3756, "text": "Output:" }, { "code": null, "e": 3787, "s": 3768, "text": "surindertarika1234" }, { "code": null, "e": 3794, "s": 3787, "text": "Picked" }, { "code": null, "e": 3803, "s": 3794, "text": "R-ggplot" }, { "code": null, "e": 3814, "s": 3803, "text": "R Language" } ]
Reflection in Golang
07 Sep, 2021 Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming. To understand Reflection better let us get a primer on empty interfaces first: “An interface that specifies zero methods is known as the empty interface.” The empty interface is extremely useful when we are declaring a function with unknown parameters and data types. Library methods such as Println, Printf take empty interfaces as arguments. The empty interface has certain hidden properties that give it functionality. The data is abstracted in the following way. Example 1: Go // Understanding Empty Interfaces in Golangpackage main import ( "fmt") func observe(i interface{}) { // using the format specifier // %T to check type in interface fmt.Printf("The type passed is: %T\n", i) // using the format specifier %#v // to check value in interface fmt.Printf("The value passed is: %#v \n", i) fmt.Println("-------------------------------------")} func main() { var value float64 = 15 value2 := "GeeksForGeeks" observe(value) observe(value2)} Output: The type passed is: float64 The value passed is: 15 ------------------------------------- The type passed is: string The value passed is: "GeeksForGeeks" ------------------------------------- Here we can clearly see that an empty interface will be able to take in any argument and adapt to its value and data type. This includes but is not limited to Structs and pointers to Structs. What is the need for reflection?Often times the data passed to these empty interfaces are not primitives. They might be structs as well for example. We need to perform procedures on such data without knowing their type or the values present in it. In such a situation in order to perform various operations on the struct, such as interpreting the data present in it to query a database or create a schema for a database we need to know the types present in it as well as the number of fields. These problems can be dealt with during run-time using reflection. The reflect Package:The foundation of Go reflection is based around Values, Types and Kinds.These are defined in the package and are of the type reflect.Value, reflect.Type and reflect.Kind and can be obtained using the methods reflect.ValueOf(x interface{}).reflect.TypeOf(x interface{}).Type.Kind(). reflect.ValueOf(x interface{}). reflect.TypeOf(x interface{}). Type.Kind(). The reflect packages offers us a number of other methods: NumField(): This method returns the number of fields present in a struct. If the passed argument is not of the Kind reflect.Struct then it panics.Field(): This method allows us to access each field in the struct using an Indexing variable. NumField(): This method returns the number of fields present in a struct. If the passed argument is not of the Kind reflect.Struct then it panics. Field(): This method allows us to access each field in the struct using an Indexing variable. In the following example we will find the difference between the Kind and the Type of a struct and another custom data type. In addition to that we will use the methods from reflect package to get and print the fields from the struct and the value from the custom data type. Example 2: Go // Example program to show difference between// Type and Kind and to demonstrate use of// Methods provided by Go reflect Packagepackage main import ( "fmt" "reflect") type details struct { fname string lname string age int balance float64} type myType string func showDetails(i, j interface{}) { t1 := reflect.TypeOf(i) k1 := t1.Kind() t2 := reflect.TypeOf(j) k2 := t2.Kind() fmt.Println("Type of first interface:", t1) fmt.Println("Kind of first interface:", k1) fmt.Println("Type of second interface:", t2) fmt.Println("Kind of second interface:", k2) fmt.Println("The values in the first argument are :") if reflect.ValueOf(i).Kind() == reflect.Struct { value := reflect.ValueOf(i) numberOfFields := value.NumField() for i := 0; i < numberOfFields; i++ { fmt.Printf("%d.Type:%T || Value:%#v\n", (i + 1), value.Field(i), value.Field(i)) fmt.Println("Kind is ", value.Field(i).Kind()) } } value := reflect.ValueOf(j) fmt.Printf("The Value passed in "+ "second parameter is %#v", value)} func main() { iD := myType("12345678") person := details{ fname: "Go", lname: "Geek", age: 32, balance: 33000.203, } showDetails(person, iD)} Output: Type of first interface: main.details Kind of first interface: struct Type of second interface: main.myType Kind of second interface: string The values in the first argument are : 1.Type:reflect.Value || Value:"Go" Kind is string 2.Type:reflect.Value || Value:"Geek" Kind is string 3.Type:reflect.Value || Value:32 Kind is int 4.Type:reflect.Value || Value:33000.203 Kind is float64 The Value passed in second parameter is "12345678" In the above example, we pass two arguments to the function showDetails() which takes empty interfaces as parameters. The arguments are: person, which is a struct.iD, which is a string. person, which is a struct. iD, which is a string. We have used the method reflect.TypeOf(i interface{}) and Type.Kind() methods to obtain those fields and we can see the difference in the output. The struct person is of Type main.details and Kind reflect.Struct. The variable iD is of Type main.myType and Kind string. Hence the distinction between Type and Kind becomes clear and is according to their definitions. This is a fundamental concept in reflection in Go Language. Further, we have used the methods reflect.ValueOf(), .NumField() and .Field() from the reflect package as well to obtain the values in the empty interface, the number of fields of the struct and then each field separately. This is possible due to the use of reflection during run-time which allows us to determine the Type and Kind of arguments. Note :The NumField() and .Field() are only applicable to structs. A panic will be caused if the element is not a struct. The format specifier %T cannot be used to print Kind. It will print reflect.Kind if we pass i.Kind() in a Printf statement with a %T, it will print reflect.Kind which is essentially the Type of all Kinds in Go.It is noteworthy that type of value.Field(i) is reflect.Value which is the Type and not the Kind. The Kind is displayed in the following line. Hence we see the importance and functionality of reflection in Go Lang. Knowing the types of variables during run-time enables us to write a lot of generic code. Therefore Reflection is an indispensable fundamental in Golang varshagumber28 simranarora5sos anikaseth98 Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Sep, 2021" }, { "code": null, "e": 401, "s": 28, "text": "Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming. To understand Reflection better let us get a primer on empty interfaces first:" }, { "code": null, "e": 477, "s": 401, "text": "“An interface that specifies zero methods is known as the empty interface.”" }, { "code": null, "e": 789, "s": 477, "text": "The empty interface is extremely useful when we are declaring a function with unknown parameters and data types. Library methods such as Println, Printf take empty interfaces as arguments. The empty interface has certain hidden properties that give it functionality. The data is abstracted in the following way." }, { "code": null, "e": 801, "s": 789, "text": "Example 1: " }, { "code": null, "e": 804, "s": 801, "text": "Go" }, { "code": "// Understanding Empty Interfaces in Golangpackage main import ( \"fmt\") func observe(i interface{}) { // using the format specifier // %T to check type in interface fmt.Printf(\"The type passed is: %T\\n\", i) // using the format specifier %#v // to check value in interface fmt.Printf(\"The value passed is: %#v \\n\", i) fmt.Println(\"-------------------------------------\")} func main() { var value float64 = 15 value2 := \"GeeksForGeeks\" observe(value) observe(value2)}", "e": 1317, "s": 804, "text": null }, { "code": null, "e": 1326, "s": 1317, "text": "Output: " }, { "code": null, "e": 1520, "s": 1326, "text": "The type passed is: float64\nThe value passed is: 15 \n-------------------------------------\nThe type passed is: string\nThe value passed is: \"GeeksForGeeks\" \n-------------------------------------" }, { "code": null, "e": 1712, "s": 1520, "text": "Here we can clearly see that an empty interface will be able to take in any argument and adapt to its value and data type. This includes but is not limited to Structs and pointers to Structs." }, { "code": null, "e": 2272, "s": 1712, "text": "What is the need for reflection?Often times the data passed to these empty interfaces are not primitives. They might be structs as well for example. We need to perform procedures on such data without knowing their type or the values present in it. In such a situation in order to perform various operations on the struct, such as interpreting the data present in it to query a database or create a schema for a database we need to know the types present in it as well as the number of fields. These problems can be dealt with during run-time using reflection." }, { "code": null, "e": 2501, "s": 2272, "text": "The reflect Package:The foundation of Go reflection is based around Values, Types and Kinds.These are defined in the package and are of the type reflect.Value, reflect.Type and reflect.Kind and can be obtained using the methods " }, { "code": null, "e": 2575, "s": 2501, "text": "reflect.ValueOf(x interface{}).reflect.TypeOf(x interface{}).Type.Kind()." }, { "code": null, "e": 2607, "s": 2575, "text": "reflect.ValueOf(x interface{})." }, { "code": null, "e": 2638, "s": 2607, "text": "reflect.TypeOf(x interface{})." }, { "code": null, "e": 2651, "s": 2638, "text": "Type.Kind()." }, { "code": null, "e": 2709, "s": 2651, "text": "The reflect packages offers us a number of other methods:" }, { "code": null, "e": 2949, "s": 2709, "text": "NumField(): This method returns the number of fields present in a struct. If the passed argument is not of the Kind reflect.Struct then it panics.Field(): This method allows us to access each field in the struct using an Indexing variable." }, { "code": null, "e": 3096, "s": 2949, "text": "NumField(): This method returns the number of fields present in a struct. If the passed argument is not of the Kind reflect.Struct then it panics." }, { "code": null, "e": 3190, "s": 3096, "text": "Field(): This method allows us to access each field in the struct using an Indexing variable." }, { "code": null, "e": 3465, "s": 3190, "text": "In the following example we will find the difference between the Kind and the Type of a struct and another custom data type. In addition to that we will use the methods from reflect package to get and print the fields from the struct and the value from the custom data type." }, { "code": null, "e": 3477, "s": 3465, "text": "Example 2: " }, { "code": null, "e": 3480, "s": 3477, "text": "Go" }, { "code": "// Example program to show difference between// Type and Kind and to demonstrate use of// Methods provided by Go reflect Packagepackage main import ( \"fmt\" \"reflect\") type details struct { fname string lname string age int balance float64} type myType string func showDetails(i, j interface{}) { t1 := reflect.TypeOf(i) k1 := t1.Kind() t2 := reflect.TypeOf(j) k2 := t2.Kind() fmt.Println(\"Type of first interface:\", t1) fmt.Println(\"Kind of first interface:\", k1) fmt.Println(\"Type of second interface:\", t2) fmt.Println(\"Kind of second interface:\", k2) fmt.Println(\"The values in the first argument are :\") if reflect.ValueOf(i).Kind() == reflect.Struct { value := reflect.ValueOf(i) numberOfFields := value.NumField() for i := 0; i < numberOfFields; i++ { fmt.Printf(\"%d.Type:%T || Value:%#v\\n\", (i + 1), value.Field(i), value.Field(i)) fmt.Println(\"Kind is \", value.Field(i).Kind()) } } value := reflect.ValueOf(j) fmt.Printf(\"The Value passed in \"+ \"second parameter is %#v\", value)} func main() { iD := myType(\"12345678\") person := details{ fname: \"Go\", lname: \"Geek\", age: 32, balance: 33000.203, } showDetails(person, iD)}", "e": 4809, "s": 3480, "text": null }, { "code": null, "e": 4818, "s": 4809, "text": "Output: " }, { "code": null, "e": 5257, "s": 4818, "text": "Type of first interface: main.details\nKind of first interface: struct\nType of second interface: main.myType\nKind of second interface: string\nThe values in the first argument are :\n\n1.Type:reflect.Value || Value:\"Go\"\nKind is string\n2.Type:reflect.Value || Value:\"Geek\"\nKind is string\n3.Type:reflect.Value || Value:32\nKind is int\n4.Type:reflect.Value || Value:33000.203\nKind is float64\nThe Value passed in second parameter is \"12345678\"" }, { "code": null, "e": 5394, "s": 5257, "text": "In the above example, we pass two arguments to the function showDetails() which takes empty interfaces as parameters. The arguments are:" }, { "code": null, "e": 5443, "s": 5394, "text": "person, which is a struct.iD, which is a string." }, { "code": null, "e": 5470, "s": 5443, "text": "person, which is a struct." }, { "code": null, "e": 5493, "s": 5470, "text": "iD, which is a string." }, { "code": null, "e": 5639, "s": 5493, "text": "We have used the method reflect.TypeOf(i interface{}) and Type.Kind() methods to obtain those fields and we can see the difference in the output." }, { "code": null, "e": 5706, "s": 5639, "text": "The struct person is of Type main.details and Kind reflect.Struct." }, { "code": null, "e": 5762, "s": 5706, "text": "The variable iD is of Type main.myType and Kind string." }, { "code": null, "e": 6965, "s": 5762, "text": "Hence the distinction between Type and Kind becomes clear and is according to their definitions. This is a fundamental concept in reflection in Go Language. Further, we have used the methods reflect.ValueOf(), .NumField() and .Field() from the reflect package as well to obtain the values in the empty interface, the number of fields of the struct and then each field separately. This is possible due to the use of reflection during run-time which allows us to determine the Type and Kind of arguments. Note :The NumField() and .Field() are only applicable to structs. A panic will be caused if the element is not a struct. The format specifier %T cannot be used to print Kind. It will print reflect.Kind if we pass i.Kind() in a Printf statement with a %T, it will print reflect.Kind which is essentially the Type of all Kinds in Go.It is noteworthy that type of value.Field(i) is reflect.Value which is the Type and not the Kind. The Kind is displayed in the following line. Hence we see the importance and functionality of reflection in Go Lang. Knowing the types of variables during run-time enables us to write a lot of generic code. Therefore Reflection is an indispensable fundamental in Golang " }, { "code": null, "e": 6980, "s": 6965, "text": "varshagumber28" }, { "code": null, "e": 6996, "s": 6980, "text": "simranarora5sos" }, { "code": null, "e": 7008, "s": 6996, "text": "anikaseth98" }, { "code": null, "e": 7015, "s": 7008, "text": "Picked" }, { "code": null, "e": 7027, "s": 7015, "text": "Go Language" } ]
Minimum operations required to make each row and column of matrix equals
20 Apr, 2022 Given a square matrix of size . Find minimum number of operation are required such that sum of elements on each row and column becomes equals. In one operation, increment any value of cell of matrix by 1. In first line print minimum operation required and in next ‘n’ lines print ‘n’ integers representing the final matrix after operation. Example: Input: 1 2 3 4 Output: 4 4 3 3 4 Explanation 1. Increment value of cell(0, 0) by 3 2. Increment value of cell(0, 1) by 1 Hence total 4 operation are required Input: 9 1 2 3 4 2 3 3 2 1 Output: 6 2 4 3 4 2 3 3 3 3 The approach is simple, let’s assume that maxSum is the maximum sum among all rows and columns. We just need to increment some cells such that the sum of any row or column becomes ‘maxSum’. Let’s say Xi is the total number of operation needed to make the sum on row ‘i’ equals to maxSum and Yj is the total number of operation needed to make the sum on column ‘j’ equals to maxSum. Since Xi = Yj so we need to work at any one of them according to the condition. In order to minimise Xi, we need to choose the maximum from rowSumi and colSumj as it will surely lead to minimum operation. After that, increment ‘i’ or ‘j’ according to the condition satisfied after increment.Below is the implementation of the above approach. C++ C Java Python 3 C# Javascript // C++ Program to Find minimum number of operation required// such that sum of elements on each row and column becomes// same*/#include <bits/stdc++.h>using namespace std; // Function to find minimum operation required to make sum// of each row and column equalsint findMinOpeartion(int matrix[][2], int n){ // Initialize the sumRow[] and sumCol[] array to 0 int sumRow[n], sumCol[n]; memset(sumRow, 0, sizeof(sumRow)); memset(sumCol, 0, sizeof(sumCol)); // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = max(maxSum, sumRow[i]); maxSum = max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row or // column int diff = min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, sumRow[] // and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count;} // Utility function to print matrixvoid printMatrix(int matrix[][2], int n){ for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) cout << matrix[i][j] << " "; cout << "\n"; }} // Driver codeint main(){ int matrix[][2] = { { 1, 2 }, { 3, 4 } }; cout << findMinOpeartion(matrix, 2) << "\n"; printMatrix(matrix, 2); return 0;} // This code is contributed by Sania Kumari Gupta // C Program to Find minimum number of operation required// such that sum of elements on each row and column becomes// same#include <stdio.h>#include <string.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // Find minimum between two numbers.int min(int num1, int num2){ return (num1 > num2) ? num2 : num1;} // Function to find minimum operation required to make sum// of each row and column equalsint findMinOpeartion(int matrix[][2], int n){ // Initialize the sumRow[] and sumCol[] array to 0 int sumRow[n], sumCol[n]; memset(sumRow, 0, sizeof(sumRow)); memset(sumCol, 0, sizeof(sumCol)); // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = max(maxSum, sumRow[i]); maxSum = max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row or // column int diff = min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, sumRow[] // and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count;} // Utility function to print matrixvoid printMatrix(int matrix[][2], int n){ for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) printf("%d ", matrix[i][j]); printf("\n"); }} // Driver codeint main(){ int matrix[][2] = { { 1, 2 }, { 3, 4 } }; printf("%d\n", findMinOpeartion(matrix, 2)); printMatrix(matrix, 2); return 0;} // This code is contributed by Sania Kumari Gupta // Java Program to Find minimum number of operation required// such that sum of elements on each row and column becomes// sameimport java.io.*; class GFG { // Function to find minimum operation required to make // sum of each row and column equals static int findMinOpeartion(int matrix[][], int n) { // Initialize the sumRow[] and sumCol[] array to 0 int[] sumRow = new int[n]; int[] sumCol = new int[n]; // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = Math.max(maxSum, sumRow[i]); maxSum = Math.max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row // or column int diff = Math.min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, // sumRow[] and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value // for next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to print matrix static void printMatrix(int matrix[][], int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) System.out.print(matrix[i][j] + " "); System.out.println(); } } /* Driver program */ public static void main(String[] args) { int matrix[][] = { { 1, 2 }, { 3, 4 } }; System.out.println(findMinOpeartion(matrix, 2)); printMatrix(matrix, 2); }} // This code is contributed by Sania Kumari Gupta # Python 3 Program to Find minimum# number of operation required such# that sum of elements on each row# and column becomes same # Function to find minimum operation# required to make sum of each row# and column equalsdef findMinOpeartion(matrix, n): # Initialize the sumRow[] and sumCol[] # array to 0 sumRow = [0] * n sumCol = [0] * n # Calculate sumRow[] and sumCol[] array for i in range(n): for j in range(n) : sumRow[i] += matrix[i][j] sumCol[j] += matrix[i][j] # Find maximum sum value in # either row or in column maxSum = 0 for i in range(n) : maxSum = max(maxSum, sumRow[i]) maxSum = max(maxSum, sumCol[i]) count = 0 i = 0 j = 0 while i < n and j < n : # Find minimum increment required # in either row or column diff = min(maxSum - sumRow[i], maxSum - sumCol[j]) # Add difference in corresponding # cell, sumRow[] and sumCol[] array matrix[i][j] += diff sumRow[i] += diff sumCol[j] += diff # Update the count variable count += diff # If ith row satisfied, increment # ith value for next iteration if (sumRow[i] == maxSum): i += 1 # If jth column satisfied, increment # jth value for next iteration if (sumCol[j] == maxSum): j += 1 return count # Utility function to print matrixdef printMatrix(matrix, n): for i in range(n) : for j in range(n): print(matrix[i][j], end = " ") print() # Driver codeif __name__ == "__main__": matrix = [[ 1, 2 ], [ 3, 4 ]] print(findMinOpeartion(matrix, 2)) printMatrix(matrix, 2) # This code is contributed# by ChitraNayal // C# Program to Find minimum// number of operation required// such that sum of elements on// each row and column becomes sameusing System; class GFG { // Function to find minimum // operation required // to make sum of each row // and column equals static int findMinOpeartion(int [,]matrix, int n) { // Initialize the sumRow[] // and sumCol[] array to 0 int[] sumRow = new int[n]; int[] sumCol = new int[n]; // Calculate sumRow[] and // sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i,j]; sumCol[j] += matrix[i,j]; } // Find maximum sum value // in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = Math.Max(maxSum, sumRow[i]); maxSum = Math.Max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment // required in either row // or column int diff = Math.Min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in // corresponding cell, // sumRow[] and sumCol[] // array matrix[i,j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count // variable count += diff; // If ith row satisfied, // increment ith value // for next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, // increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to // print matrix static void printMatrix(int [,]matrix, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) Console.Write(matrix[i,j] + " "); Console.WriteLine(); } } /* Driver program */ public static void Main() { int [,]matrix = {{1, 2}, {3, 4}}; Console.WriteLine(findMinOpeartion(matrix, 2)); printMatrix(matrix, 2); }} // This code is contributed by Vt_m. <script>// Javascript Program to Find minimum// number of operation required// such that sum of elements on// each row and column becomes same // Function to find minimum // operation required // to make sum of each row // and column equals function findMinOpeartion(matrix,n) { // Initialize the sumRow[] // and sumCol[] array to 0 let sumRow = new Array(n); let sumCol = new Array(n); for(let i=0;i<n;i++) { sumRow[i]=0; sumCol[i]=0; } // Calculate sumRow[] and // sumCol[] array for (let i = 0; i < n; ++i) for (let j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value // in either row or in column let maxSum = 0; for (let i = 0; i < n; ++i) { maxSum = Math.max(maxSum, sumRow[i]); maxSum = Math.max(maxSum, sumCol[i]); } let count = 0; for (let i = 0, j = 0; i < n && j < n;) { // Find minimum increment // required in either row // or column let diff = Math.min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in // corresponding cell, // sumRow[] and sumCol[] // array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count // variable count += diff; // If ith row satisfied, // increment ith value // for next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, // increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to // print matrix function printMatrix(matrix,n) { for (let i = 0; i < n; ++i) { for (let j = 0; j < n; ++j) document.write(matrix[i][j] + " "); document.write("<br>"); } } /* Driver program */ let matrix=[[1, 2],[3, 4]]; document.write(findMinOpeartion(matrix, 2)+"<br>"); printMatrix(matrix, 2); // This code is contributed by avanitrachhadiya2155</script> Output 4 4 3 3 4 Time complexity: O(n2) Auxiliary space: O(n) ukasp avanitrachhadiya2155 krisania804 FactSet Matrix FactSet Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Apr, 2022" }, { "code": null, "e": 403, "s": 52, "text": "Given a square matrix of size . Find minimum number of operation are required such that sum of elements on each row and column becomes equals. In one operation, increment any value of cell of matrix by 1. In first line print minimum operation required and in next ‘n’ lines print ‘n’ integers representing the final matrix after operation. Example: " }, { "code": null, "e": 623, "s": 403, "text": "Input: \n1 2\n3 4\nOutput: \n4\n4 3\n3 4\nExplanation\n1. Increment value of cell(0, 0) by 3\n2. Increment value of cell(0, 1) by 1\nHence total 4 operation are required\n\nInput: 9\n1 2 3\n4 2 3\n3 2 1\nOutput: \n6\n2 4 3 \n4 2 3 \n3 3 3 " }, { "code": null, "e": 1350, "s": 625, "text": "The approach is simple, let’s assume that maxSum is the maximum sum among all rows and columns. We just need to increment some cells such that the sum of any row or column becomes ‘maxSum’. Let’s say Xi is the total number of operation needed to make the sum on row ‘i’ equals to maxSum and Yj is the total number of operation needed to make the sum on column ‘j’ equals to maxSum. Since Xi = Yj so we need to work at any one of them according to the condition. In order to minimise Xi, we need to choose the maximum from rowSumi and colSumj as it will surely lead to minimum operation. After that, increment ‘i’ or ‘j’ according to the condition satisfied after increment.Below is the implementation of the above approach. " }, { "code": null, "e": 1354, "s": 1350, "text": "C++" }, { "code": null, "e": 1356, "s": 1354, "text": "C" }, { "code": null, "e": 1361, "s": 1356, "text": "Java" }, { "code": null, "e": 1370, "s": 1361, "text": "Python 3" }, { "code": null, "e": 1373, "s": 1370, "text": "C#" }, { "code": null, "e": 1384, "s": 1373, "text": "Javascript" }, { "code": "// C++ Program to Find minimum number of operation required// such that sum of elements on each row and column becomes// same*/#include <bits/stdc++.h>using namespace std; // Function to find minimum operation required to make sum// of each row and column equalsint findMinOpeartion(int matrix[][2], int n){ // Initialize the sumRow[] and sumCol[] array to 0 int sumRow[n], sumCol[n]; memset(sumRow, 0, sizeof(sumRow)); memset(sumCol, 0, sizeof(sumCol)); // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = max(maxSum, sumRow[i]); maxSum = max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row or // column int diff = min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, sumRow[] // and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count;} // Utility function to print matrixvoid printMatrix(int matrix[][2], int n){ for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) cout << matrix[i][j] << \" \"; cout << \"\\n\"; }} // Driver codeint main(){ int matrix[][2] = { { 1, 2 }, { 3, 4 } }; cout << findMinOpeartion(matrix, 2) << \"\\n\"; printMatrix(matrix, 2); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 3385, "s": 1384, "text": null }, { "code": "// C Program to Find minimum number of operation required// such that sum of elements on each row and column becomes// same#include <stdio.h>#include <string.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // Find minimum between two numbers.int min(int num1, int num2){ return (num1 > num2) ? num2 : num1;} // Function to find minimum operation required to make sum// of each row and column equalsint findMinOpeartion(int matrix[][2], int n){ // Initialize the sumRow[] and sumCol[] array to 0 int sumRow[n], sumCol[n]; memset(sumRow, 0, sizeof(sumRow)); memset(sumCol, 0, sizeof(sumCol)); // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = max(maxSum, sumRow[i]); maxSum = max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row or // column int diff = min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, sumRow[] // and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count;} // Utility function to print matrixvoid printMatrix(int matrix[][2], int n){ for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) printf(\"%d \", matrix[i][j]); printf(\"\\n\"); }} // Driver codeint main(){ int matrix[][2] = { { 1, 2 }, { 3, 4 } }; printf(\"%d\\n\", findMinOpeartion(matrix, 2)); printMatrix(matrix, 2); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 5593, "s": 3385, "text": null }, { "code": "// Java Program to Find minimum number of operation required// such that sum of elements on each row and column becomes// sameimport java.io.*; class GFG { // Function to find minimum operation required to make // sum of each row and column equals static int findMinOpeartion(int matrix[][], int n) { // Initialize the sumRow[] and sumCol[] array to 0 int[] sumRow = new int[n]; int[] sumCol = new int[n]; // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = Math.max(maxSum, sumRow[i]); maxSum = Math.max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row // or column int diff = Math.min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, // sumRow[] and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value // for next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to print matrix static void printMatrix(int matrix[][], int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) System.out.print(matrix[i][j] + \" \"); System.out.println(); } } /* Driver program */ public static void main(String[] args) { int matrix[][] = { { 1, 2 }, { 3, 4 } }; System.out.println(findMinOpeartion(matrix, 2)); printMatrix(matrix, 2); }} // This code is contributed by Sania Kumari Gupta", "e": 7823, "s": 5593, "text": null }, { "code": "# Python 3 Program to Find minimum# number of operation required such# that sum of elements on each row# and column becomes same # Function to find minimum operation# required to make sum of each row# and column equalsdef findMinOpeartion(matrix, n): # Initialize the sumRow[] and sumCol[] # array to 0 sumRow = [0] * n sumCol = [0] * n # Calculate sumRow[] and sumCol[] array for i in range(n): for j in range(n) : sumRow[i] += matrix[i][j] sumCol[j] += matrix[i][j] # Find maximum sum value in # either row or in column maxSum = 0 for i in range(n) : maxSum = max(maxSum, sumRow[i]) maxSum = max(maxSum, sumCol[i]) count = 0 i = 0 j = 0 while i < n and j < n : # Find minimum increment required # in either row or column diff = min(maxSum - sumRow[i], maxSum - sumCol[j]) # Add difference in corresponding # cell, sumRow[] and sumCol[] array matrix[i][j] += diff sumRow[i] += diff sumCol[j] += diff # Update the count variable count += diff # If ith row satisfied, increment # ith value for next iteration if (sumRow[i] == maxSum): i += 1 # If jth column satisfied, increment # jth value for next iteration if (sumCol[j] == maxSum): j += 1 return count # Utility function to print matrixdef printMatrix(matrix, n): for i in range(n) : for j in range(n): print(matrix[i][j], end = \" \") print() # Driver codeif __name__ == \"__main__\": matrix = [[ 1, 2 ], [ 3, 4 ]] print(findMinOpeartion(matrix, 2)) printMatrix(matrix, 2) # This code is contributed# by ChitraNayal", "e": 9601, "s": 7823, "text": null }, { "code": "// C# Program to Find minimum// number of operation required// such that sum of elements on// each row and column becomes sameusing System; class GFG { // Function to find minimum // operation required // to make sum of each row // and column equals static int findMinOpeartion(int [,]matrix, int n) { // Initialize the sumRow[] // and sumCol[] array to 0 int[] sumRow = new int[n]; int[] sumCol = new int[n]; // Calculate sumRow[] and // sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i,j]; sumCol[j] += matrix[i,j]; } // Find maximum sum value // in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = Math.Max(maxSum, sumRow[i]); maxSum = Math.Max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment // required in either row // or column int diff = Math.Min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in // corresponding cell, // sumRow[] and sumCol[] // array matrix[i,j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count // variable count += diff; // If ith row satisfied, // increment ith value // for next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, // increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to // print matrix static void printMatrix(int [,]matrix, int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) Console.Write(matrix[i,j] + \" \"); Console.WriteLine(); } } /* Driver program */ public static void Main() { int [,]matrix = {{1, 2}, {3, 4}}; Console.WriteLine(findMinOpeartion(matrix, 2)); printMatrix(matrix, 2); }} // This code is contributed by Vt_m.", "e": 12165, "s": 9601, "text": null }, { "code": "<script>// Javascript Program to Find minimum// number of operation required// such that sum of elements on// each row and column becomes same // Function to find minimum // operation required // to make sum of each row // and column equals function findMinOpeartion(matrix,n) { // Initialize the sumRow[] // and sumCol[] array to 0 let sumRow = new Array(n); let sumCol = new Array(n); for(let i=0;i<n;i++) { sumRow[i]=0; sumCol[i]=0; } // Calculate sumRow[] and // sumCol[] array for (let i = 0; i < n; ++i) for (let j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value // in either row or in column let maxSum = 0; for (let i = 0; i < n; ++i) { maxSum = Math.max(maxSum, sumRow[i]); maxSum = Math.max(maxSum, sumCol[i]); } let count = 0; for (let i = 0, j = 0; i < n && j < n;) { // Find minimum increment // required in either row // or column let diff = Math.min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in // corresponding cell, // sumRow[] and sumCol[] // array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count // variable count += diff; // If ith row satisfied, // increment ith value // for next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, // increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to // print matrix function printMatrix(matrix,n) { for (let i = 0; i < n; ++i) { for (let j = 0; j < n; ++j) document.write(matrix[i][j] + \" \"); document.write(\"<br>\"); } } /* Driver program */ let matrix=[[1, 2],[3, 4]]; document.write(findMinOpeartion(matrix, 2)+\"<br>\"); printMatrix(matrix, 2); // This code is contributed by avanitrachhadiya2155</script>", "e": 14698, "s": 12165, "text": null }, { "code": null, "e": 14715, "s": 14698, "text": "Output\n4\n4 3\n3 4" }, { "code": null, "e": 14761, "s": 14715, "text": "Time complexity: O(n2) Auxiliary space: O(n) " }, { "code": null, "e": 14767, "s": 14761, "text": "ukasp" }, { "code": null, "e": 14788, "s": 14767, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14800, "s": 14788, "text": "krisania804" }, { "code": null, "e": 14808, "s": 14800, "text": "FactSet" }, { "code": null, "e": 14815, "s": 14808, "text": "Matrix" }, { "code": null, "e": 14823, "s": 14815, "text": "FactSet" }, { "code": null, "e": 14830, "s": 14823, "text": "Matrix" } ]
Preprocessor Directives in C#
29 Mar, 2019 Preprocessor Directives in C# tell the compiler to process the given information before actual compilation of the program starts. It begins with a hashtag symbol (#) and since these preprocessors are not statements so no semi-colon is appended at the end. The C# compiler does not have a separate preprocessor, yet the directives are processed as if there was one. There cannot be anything else in a line other than the preprocessor directive. The Preprocessors used in C# are given below: Example 1: Using #define, #if, #else and #endif Let us understand this concept with a few examples. In the code given below, we are using #define to define a symbol called shape. So this means that ‘shape‘ evaluates to true. Inside main, we check if shape exists or not using #if. Since it does exists and the compiler knows it beforehand so the part #else will never be executed and is treated as a comment by the compiler. The #endif is used to indicate the end of the if derective. // C# Program to show the use of// preprocessor directives // Defining a symbol shape#define shape using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO; namespace Preprocessor { class Program { static void Main(string[] args) { // Checking if symbol shape exists or not #if (shape) Console.WriteLine("Shape Exists"); #else Console.WriteLine("Shape does not Exist"); // Ending the if directive #endif }}} Output: Shape Exists Example 2 : Using #warning and #define Consider another example. In the code given below, we deliberately remove the definitions of symbols shape and shape_. Since the compiler cannot find these it executes the #else directive. Here, we generate user defined warning and error. // C# program to show the Removal of// definition of shape and shape_ #undef shape_ using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO; namespace preprocessor2{ class Program { static void Main( string[] args ) { // Checking if shape exists #if (shape) Console.WriteLine("Shape Exists"); // Or if shape_ exists #elif (shape_) Console.WriteLine("Shape_ Exists" ); #else // using #warning to display message that // none of the symbols were found #warning "No Symbols found" // Generating user defined error #error "Check use of preprocessors" // Ending if #endif } }} This code will not compile as there exists an error in the code. Warnings and errors essentially do the same job but the error will stop the compilation process of the code. The visual studio will give you the following result: Example 3: Using #region and #endregion #region defines a set of instructions as a block of code and this block is compiled all at once by the compiler. #endregion marks the end of the block. The program below depicts the same. using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO; namespace preprocessor3{ class Program { static void Main( string[] args ) { char ch = 'y'; // Using #region to define a block of code #region if (ch == 'y' || ch == 'Y') Console.WriteLine( "Value of ch is 'y'" ); else Console.WriteLine( "Value of ch is unknown" ); // Ends the region #endregion } }} Value of ch is 'y' Example 4: Using #pragma warning and #pragma checksum In the code below we use the #pragma warning disable to disable all warnings. Inside main, we generate a user defined warning to check if it has been disabled or not. And #pragma checksum is used to aid the debugging of the file. // C# program to Disables all warnings #pragma warning disable using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace Preprocessor4 { class GFG { static void Main(string[] args) { // Creating a warning #warning "This is disabled" // Checksum is used for debugging // the file in consideration #pragma checksum "Program.cs" }}} The error list for the above code: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Mar, 2019" }, { "code": null, "e": 472, "s": 28, "text": "Preprocessor Directives in C# tell the compiler to process the given information before actual compilation of the program starts. It begins with a hashtag symbol (#) and since these preprocessors are not statements so no semi-colon is appended at the end. The C# compiler does not have a separate preprocessor, yet the directives are processed as if there was one. There cannot be anything else in a line other than the preprocessor directive." }, { "code": null, "e": 518, "s": 472, "text": "The Preprocessors used in C# are given below:" }, { "code": null, "e": 1003, "s": 518, "text": "Example 1: Using #define, #if, #else and #endif Let us understand this concept with a few examples. In the code given below, we are using #define to define a symbol called shape. So this means that ‘shape‘ evaluates to true. Inside main, we check if shape exists or not using #if. Since it does exists and the compiler knows it beforehand so the part #else will never be executed and is treated as a comment by the compiler. The #endif is used to indicate the end of the if derective." }, { "code": "// C# Program to show the use of// preprocessor directives // Defining a symbol shape#define shape using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO; namespace Preprocessor { class Program { static void Main(string[] args) { // Checking if symbol shape exists or not #if (shape) Console.WriteLine(\"Shape Exists\"); #else Console.WriteLine(\"Shape does not Exist\"); // Ending the if directive #endif }}}", "e": 1551, "s": 1003, "text": null }, { "code": null, "e": 1559, "s": 1551, "text": "Output:" }, { "code": null, "e": 1572, "s": 1559, "text": "Shape Exists" }, { "code": null, "e": 1850, "s": 1572, "text": "Example 2 : Using #warning and #define Consider another example. In the code given below, we deliberately remove the definitions of symbols shape and shape_. Since the compiler cannot find these it executes the #else directive. Here, we generate user defined warning and error." }, { "code": "// C# program to show the Removal of// definition of shape and shape_ #undef shape_ using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO; namespace preprocessor2{ class Program { static void Main( string[] args ) { // Checking if shape exists #if (shape) Console.WriteLine(\"Shape Exists\"); // Or if shape_ exists #elif (shape_) Console.WriteLine(\"Shape_ Exists\" ); #else // using #warning to display message that // none of the symbols were found #warning \"No Symbols found\" // Generating user defined error #error \"Check use of preprocessors\" // Ending if #endif } }}", "e": 2732, "s": 1850, "text": null }, { "code": null, "e": 2960, "s": 2732, "text": "This code will not compile as there exists an error in the code. Warnings and errors essentially do the same job but the error will stop the compilation process of the code. The visual studio will give you the following result:" }, { "code": null, "e": 3188, "s": 2960, "text": "Example 3: Using #region and #endregion #region defines a set of instructions as a block of code and this block is compiled all at once by the compiler. #endregion marks the end of the block. The program below depicts the same." }, { "code": "using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO; namespace preprocessor3{ class Program { static void Main( string[] args ) { char ch = 'y'; // Using #region to define a block of code #region if (ch == 'y' || ch == 'Y') Console.WriteLine( \"Value of ch is 'y'\" ); else Console.WriteLine( \"Value of ch is unknown\" ); // Ends the region #endregion } }}", "e": 3759, "s": 3188, "text": null }, { "code": null, "e": 3779, "s": 3759, "text": "Value of ch is 'y'\n" }, { "code": null, "e": 4063, "s": 3779, "text": "Example 4: Using #pragma warning and #pragma checksum In the code below we use the #pragma warning disable to disable all warnings. Inside main, we generate a user defined warning to check if it has been disabled or not. And #pragma checksum is used to aid the debugging of the file." }, { "code": "// C# program to Disables all warnings #pragma warning disable using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace Preprocessor4 { class GFG { static void Main(string[] args) { // Creating a warning #warning \"This is disabled\" // Checksum is used for debugging // the file in consideration #pragma checksum \"Program.cs\" }}}", "e": 4526, "s": 4063, "text": null }, { "code": null, "e": 4561, "s": 4526, "text": "The error list for the above code:" }, { "code": null, "e": 4564, "s": 4561, "text": "C#" } ]
Python PostgreSQL – Update Table
07 Dec, 2021 In this article, we will see how to Update data in PostgreSQL using python and Psycopg2. The update command is used to modify the existing record in the table. By default whole records of the specific attribute are modified, but to modify some particular row, we need to use the where clause along with the update clause. Syntax for Update Clause UPDATE table_name SET column1=value1,column2=value2,... Here we are going to see how to update the columns of the table. The table after modification looks like the table shown below. As we can see for every tuple state value is changed to Kashmir. Python3 # importing psycopg2 moduleimport psycopg2 # establishing the connectionconn = psycopg2.connect( database="postgres", user='postgres', password='password', host='localhost', port= '5432') # creating a cursor objectcursor = conn.cursor() # query to update table with where clausesql='''update Geeks set state='Kashmir'; ''' # execute the querycursor.execute(sql)print('table updated..') print('table after updation...')sql2='''select * from Geeks;'''cursor.execute(sql2); # print table after modificationprint(cursor.fetchall()) # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()# code Output table updated.. table after updation... [(1,'Babita','kashmir'),(2,'Anushka','Kashmir'),(3,'Anamika','Kashmir'), (4,'Sanaya','Kashmir'),(5,'Radha','Kashmir')] Here we will use the where clause along with the update table. Syntax: UPDATE Geeks set state=’Delhi’ where id=2; We can see state of the row having id 2 is changed from Hyderabad to Delhi. Python3 # importing psycopg2 moduleimport psycopg2 # establishing the connectionconn = psycopg2.connect( database="postgres", user='postgres', password='password', host='localhost', port= '5432') # create a cursor objectcursor = conn.cursor() # query to update tablesql='''update Geeks set state='Delhi' where id='2'; ''' # execute the querycursor.execute(sql)print("Table updated..") print('Table after updation...') # query to display Geeks tablesql2='select * from Geeks;' # execute querycursor.execute(sql2); # fetching all detailsprint(cursor.fetchall()); # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close() Output: Table updated.. Table after updation... [(1, 'Babita', 'Bihar'), (3, 'Anamika', 'Banglore'), (4, 'Sanaya', 'Pune'), (5, 'Radha', 'Chandigarh'), (2, 'Anushka', 'Delhi')] as5853535 avtarkumar719 Picked Python PostgreSQL Python Pyscopg2 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Dec, 2021" }, { "code": null, "e": 350, "s": 28, "text": "In this article, we will see how to Update data in PostgreSQL using python and Psycopg2. The update command is used to modify the existing record in the table. By default whole records of the specific attribute are modified, but to modify some particular row, we need to use the where clause along with the update clause." }, { "code": null, "e": 375, "s": 350, "text": "Syntax for Update Clause" }, { "code": null, "e": 431, "s": 375, "text": "UPDATE table_name SET column1=value1,column2=value2,..." }, { "code": null, "e": 625, "s": 431, "text": "Here we are going to see how to update the columns of the table. The table after modification looks like the table shown below. As we can see for every tuple state value is changed to Kashmir. " }, { "code": null, "e": 633, "s": 625, "text": "Python3" }, { "code": "# importing psycopg2 moduleimport psycopg2 # establishing the connectionconn = psycopg2.connect( database=\"postgres\", user='postgres', password='password', host='localhost', port= '5432') # creating a cursor objectcursor = conn.cursor() # query to update table with where clausesql='''update Geeks set state='Kashmir'; ''' # execute the querycursor.execute(sql)print('table updated..') print('table after updation...')sql2='''select * from Geeks;'''cursor.execute(sql2); # print table after modificationprint(cursor.fetchall()) # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()# code", "e": 1269, "s": 633, "text": null }, { "code": null, "e": 1276, "s": 1269, "text": "Output" }, { "code": null, "e": 1435, "s": 1276, "text": "table updated..\ntable after updation...\n[(1,'Babita','kashmir'),(2,'Anushka','Kashmir'),(3,'Anamika','Kashmir'),\n(4,'Sanaya','Kashmir'),(5,'Radha','Kashmir')]" }, { "code": null, "e": 1498, "s": 1435, "text": "Here we will use the where clause along with the update table." }, { "code": null, "e": 1549, "s": 1498, "text": "Syntax: UPDATE Geeks set state=’Delhi’ where id=2;" }, { "code": null, "e": 1625, "s": 1549, "text": "We can see state of the row having id 2 is changed from Hyderabad to Delhi." }, { "code": null, "e": 1633, "s": 1625, "text": "Python3" }, { "code": "# importing psycopg2 moduleimport psycopg2 # establishing the connectionconn = psycopg2.connect( database=\"postgres\", user='postgres', password='password', host='localhost', port= '5432') # create a cursor objectcursor = conn.cursor() # query to update tablesql='''update Geeks set state='Delhi' where id='2'; ''' # execute the querycursor.execute(sql)print(\"Table updated..\") print('Table after updation...') # query to display Geeks tablesql2='select * from Geeks;' # execute querycursor.execute(sql2); # fetching all detailsprint(cursor.fetchall()); # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()", "e": 2288, "s": 1633, "text": null }, { "code": null, "e": 2296, "s": 2288, "text": "Output:" }, { "code": null, "e": 2467, "s": 2296, "text": "Table updated..\nTable after updation...\n[(1, 'Babita', 'Bihar'), (3, 'Anamika', 'Banglore'), \n(4, 'Sanaya', 'Pune'), (5, 'Radha', 'Chandigarh'),\n (2, 'Anushka', 'Delhi')]" }, { "code": null, "e": 2477, "s": 2467, "text": "as5853535" }, { "code": null, "e": 2491, "s": 2477, "text": "avtarkumar719" }, { "code": null, "e": 2498, "s": 2491, "text": "Picked" }, { "code": null, "e": 2516, "s": 2498, "text": "Python PostgreSQL" }, { "code": null, "e": 2532, "s": 2516, "text": "Python Pyscopg2" }, { "code": null, "e": 2539, "s": 2532, "text": "Python" } ]
How to Generate Database Dump of MySQL Database in Linux?
30 Jun, 2021 We will learn how to Backup and Restore your MySQL Database with Mysqldump query in LINUX. We had always a need that if the production database is corrupted somehow, we should be able to recover it, for recovering we should always keep a backup of the database at particular instances. So, data rollback can be done. First, we will create a Database in our system. We will need LAMPP and APACHE Software for this purpose. Step 1: Create a database using the below command: CREATE DATABASE geeksforgeeks; Step 2: Use the database using the below command: USE geeksforgeeks; Step 3: Create a table in this database as shown below: CREATE TABLE employeeData(ID INT(10), Name VARCHAR(255), Designation VARCHAR(255), Address VARCHAR(255), Branch VARCHAR(255) ); Step 4: Describe this table to see if it is correctly created or not: DESC employeeData; Employee Data Table is successfully created Step 5: Insert some data in this table. INSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (1,"Devesh Pratap Singh","Software Engineer","Uttar Pradesh, India", "Noida"); INSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (2,"Megha Arele","Web Developer","Uttar Pradesh, India", "Noida"); INSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (3,"Aditya Srivastava","Research Analyst","Uttar Pradesh, India", "Noida"); INSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (4,"Tanishka Sharma","Jr. Architect","Uttar Pradesh, India", "Noida"); INSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (3,"Divyanshi Upadhyay","Jr. Architect","Uttar Pradesh, India", "Noida"); Step 6: Dump the data for backup for restoring purposes with the below command: mysqldump -u root -p geeksforgeeks > ~/Desktop/backup_db.sql After running this command you will get the dumped database on your desktop. Output File mysql Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 346, "s": 28, "text": "We will learn how to Backup and Restore your MySQL Database with Mysqldump query in LINUX. We had always a need that if the production database is corrupted somehow, we should be able to recover it, for recovering we should always keep a backup of the database at particular instances. So, data rollback can be done." }, { "code": null, "e": 451, "s": 346, "text": "First, we will create a Database in our system. We will need LAMPP and APACHE Software for this purpose." }, { "code": null, "e": 502, "s": 451, "text": "Step 1: Create a database using the below command:" }, { "code": null, "e": 533, "s": 502, "text": "CREATE DATABASE geeksforgeeks;" }, { "code": null, "e": 583, "s": 533, "text": "Step 2: Use the database using the below command:" }, { "code": null, "e": 602, "s": 583, "text": "USE geeksforgeeks;" }, { "code": null, "e": 658, "s": 602, "text": "Step 3: Create a table in this database as shown below:" }, { "code": null, "e": 846, "s": 658, "text": "CREATE TABLE employeeData(ID INT(10),\n Name VARCHAR(255),\n Designation VARCHAR(255),\n Address VARCHAR(255),\n Branch VARCHAR(255)\n );" }, { "code": null, "e": 916, "s": 846, "text": "Step 4: Describe this table to see if it is correctly created or not:" }, { "code": null, "e": 935, "s": 916, "text": "DESC employeeData;" }, { "code": null, "e": 979, "s": 935, "text": "Employee Data Table is successfully created" }, { "code": null, "e": 1019, "s": 979, "text": "Step 5: Insert some data in this table." }, { "code": null, "e": 1806, "s": 1019, "text": "INSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (1,\"Devesh Pratap Singh\",\"Software Engineer\",\"Uttar Pradesh, India\", \"Noida\");\nINSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (2,\"Megha Arele\",\"Web Developer\",\"Uttar Pradesh, India\", \"Noida\");\nINSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (3,\"Aditya Srivastava\",\"Research Analyst\",\"Uttar Pradesh, India\", \"Noida\");\nINSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (4,\"Tanishka Sharma\",\"Jr. Architect\",\"Uttar Pradesh, India\", \"Noida\");\nINSERT INTO `employeedata`(`ID`, `Name`, `Designation`, `Address`, `Branch`) VALUES (3,\"Divyanshi Upadhyay\",\"Jr. Architect\",\"Uttar Pradesh, India\", \"Noida\");" }, { "code": null, "e": 1886, "s": 1806, "text": "Step 6: Dump the data for backup for restoring purposes with the below command:" }, { "code": null, "e": 1947, "s": 1886, "text": "mysqldump -u root -p geeksforgeeks > ~/Desktop/backup_db.sql" }, { "code": null, "e": 2024, "s": 1947, "text": "After running this command you will get the dumped database on your desktop." }, { "code": null, "e": 2036, "s": 2024, "text": "Output File" }, { "code": null, "e": 2042, "s": 2036, "text": "mysql" }, { "code": null, "e": 2049, "s": 2042, "text": "Picked" }, { "code": null, "e": 2060, "s": 2049, "text": "Linux-Unix" } ]
PLSQL | CONCAT Function
18 Sep, 2019 The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The CONCAT function allows you to concatenate two strings together. To CONCAT more than two values, we can nest multiple CONCAT function calls. Syntax: CONCAT( string1, string2 ) Parameters Used: string1: It is used to specify the first string to concatenate.string2: It is used to specify the second string to concatenate. string1: It is used to specify the first string to concatenate. string2: It is used to specify the second string to concatenate. Supported Versions of Oracle/PLSQL: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Example-1: DECLARE Test_String string(10) := 'Hello '; Test_String2 string(10) := 'world!'; BEGIN dbms_output.put_line(CONCAT(Test_String, Test_String2)); END; Output: Hello world! Example-2: DECLARE Test_String string(10) := 'Geeks'; Test_String2 string(10) := 'For'; Test_String3 string(10) := 'Geeks'; BEGIN dbms_output.put_line(CONCAT(CONCAT(Test_String, Test_String2), Test_String3)); END; Output: GeeksForGeeks SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Sep, 2019" }, { "code": null, "e": 358, "s": 28, "text": "The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The CONCAT function allows you to concatenate two strings together. To CONCAT more than two values, we can nest multiple CONCAT function calls." }, { "code": null, "e": 366, "s": 358, "text": "Syntax:" }, { "code": null, "e": 393, "s": 366, "text": "CONCAT( string1, string2 )" }, { "code": null, "e": 410, "s": 393, "text": "Parameters Used:" }, { "code": null, "e": 538, "s": 410, "text": "string1: It is used to specify the first string to concatenate.string2: It is used to specify the second string to concatenate." }, { "code": null, "e": 602, "s": 538, "text": "string1: It is used to specify the first string to concatenate." }, { "code": null, "e": 667, "s": 602, "text": "string2: It is used to specify the second string to concatenate." }, { "code": null, "e": 703, "s": 667, "text": "Supported Versions of Oracle/PLSQL:" }, { "code": null, "e": 752, "s": 703, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 763, "s": 752, "text": "Oracle 12c" }, { "code": null, "e": 774, "s": 763, "text": "Oracle 11g" }, { "code": null, "e": 785, "s": 774, "text": "Oracle 10g" }, { "code": null, "e": 795, "s": 785, "text": "Oracle 9i" }, { "code": null, "e": 805, "s": 795, "text": "Oracle 8i" }, { "code": null, "e": 816, "s": 805, "text": "Example-1:" }, { "code": null, "e": 986, "s": 816, "text": "DECLARE \n Test_String string(10) := 'Hello ';\n Test_String2 string(10) := 'world!';\n \nBEGIN \n dbms_output.put_line(CONCAT(Test_String, Test_String2)); \n \nEND; " }, { "code": null, "e": 994, "s": 986, "text": "Output:" }, { "code": null, "e": 1008, "s": 994, "text": "Hello world! " }, { "code": null, "e": 1019, "s": 1008, "text": "Example-2:" }, { "code": null, "e": 1246, "s": 1019, "text": "DECLARE \n Test_String string(10) := 'Geeks';\n Test_String2 string(10) := 'For';\n Test_String3 string(10) := 'Geeks';\n \nBEGIN \n dbms_output.put_line(CONCAT(CONCAT(Test_String, Test_String2), Test_String3)); \n \nEND; " }, { "code": null, "e": 1254, "s": 1246, "text": "Output:" }, { "code": null, "e": 1269, "s": 1254, "text": "GeeksForGeeks " }, { "code": null, "e": 1280, "s": 1269, "text": "SQL-PL/SQL" }, { "code": null, "e": 1284, "s": 1280, "text": "SQL" }, { "code": null, "e": 1288, "s": 1284, "text": "SQL" } ]
INET_ATON() function in MySQL
14 Dec, 2020 INET_ATON() : This function in MySQL takes the dotted-quad representation of an IPv4 address as a string and returns the numeric value of the given IP address in form of an integer. If the input address is not a valid IPv4 address this function returns NULL. The return address is calculated by the following formula : If the given input IPv4 address is a.b.c.d then the return value a×2563+ b×2562+ c×2561 + d Syntax : INET_ATON(expr) Parameter : This method accepts only one parameter. expr – Input IPv4 address represented by a string. Returns : It returns the numeric value of a given IPv4 address. Example-1 : Checking the equivalent integer representation for the following address “1.6.5.0” with the help of INET_ATON Function. As it is a valid IPv4 address we will get results in an integer. SELECT INET_ATON('1.6.5.0') AS AddressInInteger ; Output : Example-2 : Checking the equivalent integer representation for the following address “::1.6” with the help of INET_ATON Function. As it is not a valid IPv4 address we will get NULL. SELECT INET_ATON('::1.6') AS AddressInInteger ; Output : Example -3 : Checking the equivalent integer representation for the following address “115.16.55.255” with the help of INET_ATON Function. As it is a valid IPv4 address we will get results in an integer. SELECT INET_ATON('15.16.55.255') AS AddressInInteger ; Output : Example-4 : Checking the equivalent integer representation for the following IPv6 address “fdfe::5a55:caff:fefa:9089” with the help of INET_ATON Function. SELECT INET_ATON('fdfe::5a55:caff:fefa:9089') AS AddressInInteger ; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Dec, 2020" }, { "code": null, "e": 42, "s": 28, "text": "INET_ATON() :" }, { "code": null, "e": 347, "s": 42, "text": "This function in MySQL takes the dotted-quad representation of an IPv4 address as a string and returns the numeric value of the given IP address in form of an integer. If the input address is not a valid IPv4 address this function returns NULL. The return address is calculated by the following formula :" }, { "code": null, "e": 439, "s": 347, "text": "If the given input IPv4 address is a.b.c.d then the return value a×2563+ b×2562+ c×2561 + d" }, { "code": null, "e": 448, "s": 439, "text": "Syntax :" }, { "code": null, "e": 464, "s": 448, "text": "INET_ATON(expr)" }, { "code": null, "e": 477, "s": 464, "text": "Parameter : " }, { "code": null, "e": 517, "s": 477, "text": "This method accepts only one parameter." }, { "code": null, "e": 568, "s": 517, "text": "expr – Input IPv4 address represented by a string." }, { "code": null, "e": 579, "s": 568, "text": "Returns : " }, { "code": null, "e": 633, "s": 579, "text": "It returns the numeric value of a given IPv4 address." }, { "code": null, "e": 645, "s": 633, "text": "Example-1 :" }, { "code": null, "e": 830, "s": 645, "text": "Checking the equivalent integer representation for the following address “1.6.5.0” with the help of INET_ATON Function. As it is a valid IPv4 address we will get results in an integer." }, { "code": null, "e": 881, "s": 830, "text": "SELECT INET_ATON('1.6.5.0') AS AddressInInteger ;" }, { "code": null, "e": 890, "s": 881, "text": "Output :" }, { "code": null, "e": 902, "s": 890, "text": "Example-2 :" }, { "code": null, "e": 1072, "s": 902, "text": "Checking the equivalent integer representation for the following address “::1.6” with the help of INET_ATON Function. As it is not a valid IPv4 address we will get NULL." }, { "code": null, "e": 1122, "s": 1072, "text": " SELECT INET_ATON('::1.6') AS AddressInInteger ;" }, { "code": null, "e": 1131, "s": 1122, "text": "Output :" }, { "code": null, "e": 1144, "s": 1131, "text": "Example -3 :" }, { "code": null, "e": 1335, "s": 1144, "text": "Checking the equivalent integer representation for the following address “115.16.55.255” with the help of INET_ATON Function. As it is a valid IPv4 address we will get results in an integer." }, { "code": null, "e": 1392, "s": 1335, "text": " SELECT INET_ATON('15.16.55.255') AS AddressInInteger ;" }, { "code": null, "e": 1401, "s": 1392, "text": "Output :" }, { "code": null, "e": 1413, "s": 1401, "text": "Example-4 :" }, { "code": null, "e": 1557, "s": 1413, "text": "Checking the equivalent integer representation for the following IPv6 address “fdfe::5a55:caff:fefa:9089” with the help of INET_ATON Function. " }, { "code": null, "e": 1626, "s": 1557, "text": "SELECT INET_ATON('fdfe::5a55:caff:fefa:9089') AS AddressInInteger ;" }, { "code": null, "e": 1635, "s": 1626, "text": "Output :" }, { "code": null, "e": 1644, "s": 1635, "text": "DBMS-SQL" }, { "code": null, "e": 1650, "s": 1644, "text": "mysql" }, { "code": null, "e": 1654, "s": 1650, "text": "SQL" }, { "code": null, "e": 1658, "s": 1654, "text": "SQL" } ]
How to wrap text inside and outside box using CSS ?
24 Jun, 2021 In this article, we are going to cover how one can wrap the text inside and outside the box using the CSS properties. Approach: We will be using the “overflow-wrap” property. This property comes into the picture when the length of the content exceeds the parent component length. The “overflow-wrap” property can have mainly five values. normal break-word inherit initial unset The “normal” value will break lines according to the normal line breaking rules of the browser. The “inherit” will inherit the property of the parent element. But the value we are looking for is the “break-word“. The “break-word” property will break any string or word which exceeds the boundary of the parent block or division and will try to fit the content into the block providing a new line. We will give the height and width property to fix value and not to auto, as auto increases the width based on the content length. HTML code: We have created one div with the class name “box” which is responsible for giving the fixed height, width, and overflow conditions. Inside this div box, we have our content <p> tag which is holding string values. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> body { background-color: #242B2E; color: white; } .box { margin: 30px; height: 100px; width: 100px; background-color: #FF6666; overflow-wrap: break-word; } .p { color: white; margin: 5px; padding: 10px; } </style></head> <body> <div class="box"> <p> try to read this word chekolosvakialRegion </p> </div></body> </html> Class box without overflow condition: If the CSS used above is changed to the following for the class “box“. In the above, we have not given any overflow conditions in the class box, so the normal behavior will be followed, and it will not break the lines until the break line is not specified which is white space. In this case, our content will overflow the box. Output: content exceeding the boundaries Class box with overflow condition: If the above CSS is modified with the following code. After providing the overflow condition on the parent block box, we achieve the word wrapping on the content. Whenever the <p> tag content tries to exceed the boundary our overflow-wrap: break-word will break the word “chekolosvakialRegion” and tries to fit in the box. Output: overflow-wrap: break-word We have successfully wrapped the content inside and outside the box using CSS property. CSS-Properties CSS-Questions HTML-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and 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 ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 146, "s": 28, "text": "In this article, we are going to cover how one can wrap the text inside and outside the box using the CSS properties." }, { "code": null, "e": 366, "s": 146, "text": "Approach: We will be using the “overflow-wrap” property. This property comes into the picture when the length of the content exceeds the parent component length. The “overflow-wrap” property can have mainly five values." }, { "code": null, "e": 373, "s": 366, "text": "normal" }, { "code": null, "e": 384, "s": 373, "text": "break-word" }, { "code": null, "e": 392, "s": 384, "text": "inherit" }, { "code": null, "e": 400, "s": 392, "text": "initial" }, { "code": null, "e": 406, "s": 400, "text": "unset" }, { "code": null, "e": 620, "s": 406, "text": "The “normal” value will break lines according to the normal line breaking rules of the browser. The “inherit” will inherit the property of the parent element. But the value we are looking for is the “break-word“. " }, { "code": null, "e": 804, "s": 620, "text": "The “break-word” property will break any string or word which exceeds the boundary of the parent block or division and will try to fit the content into the block providing a new line." }, { "code": null, "e": 935, "s": 804, "text": "We will give the height and width property to fix value and not to auto, as auto increases the width based on the content length. " }, { "code": null, "e": 1159, "s": 935, "text": "HTML code: We have created one div with the class name “box” which is responsible for giving the fixed height, width, and overflow conditions. Inside this div box, we have our content <p> tag which is holding string values." }, { "code": null, "e": 1164, "s": 1159, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> body { background-color: #242B2E; color: white; } .box { margin: 30px; height: 100px; width: 100px; background-color: #FF6666; overflow-wrap: break-word; } .p { color: white; margin: 5px; padding: 10px; } </style></head> <body> <div class=\"box\"> <p> try to read this word chekolosvakialRegion </p> </div></body> </html>", "e": 1906, "s": 1164, "text": null }, { "code": null, "e": 2015, "s": 1906, "text": "Class box without overflow condition: If the CSS used above is changed to the following for the class “box“." }, { "code": null, "e": 2272, "s": 2015, "text": "In the above, we have not given any overflow conditions in the class box, so the normal behavior will be followed, and it will not break the lines until the break line is not specified which is white space. In this case, our content will overflow the box. " }, { "code": null, "e": 2280, "s": 2272, "text": "Output:" }, { "code": null, "e": 2313, "s": 2280, "text": "content exceeding the boundaries" }, { "code": null, "e": 2402, "s": 2313, "text": "Class box with overflow condition: If the above CSS is modified with the following code." }, { "code": null, "e": 2672, "s": 2402, "text": "After providing the overflow condition on the parent block box, we achieve the word wrapping on the content. Whenever the <p> tag content tries to exceed the boundary our overflow-wrap: break-word will break the word “chekolosvakialRegion” and tries to fit in the box. " }, { "code": null, "e": 2680, "s": 2672, "text": "Output:" }, { "code": null, "e": 2707, "s": 2680, "text": "overflow-wrap: break-word " }, { "code": null, "e": 2795, "s": 2707, "text": "We have successfully wrapped the content inside and outside the box using CSS property." }, { "code": null, "e": 2810, "s": 2795, "text": "CSS-Properties" }, { "code": null, "e": 2824, "s": 2810, "text": "CSS-Questions" }, { "code": null, "e": 2839, "s": 2824, "text": "HTML-Questions" }, { "code": null, "e": 2846, "s": 2839, "text": "Picked" }, { "code": null, "e": 2850, "s": 2846, "text": "CSS" }, { "code": null, "e": 2855, "s": 2850, "text": "HTML" }, { "code": null, "e": 2872, "s": 2855, "text": "Web Technologies" }, { "code": null, "e": 2877, "s": 2872, "text": "HTML" }, { "code": null, "e": 2975, "s": 2877, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3014, "s": 2975, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3053, "s": 3014, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3092, "s": 3053, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3121, "s": 3092, "text": "Form validation using jQuery" }, { "code": null, "e": 3158, "s": 3121, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3182, "s": 3158, "text": "REST API (Introduction)" }, { "code": null, "e": 3235, "s": 3182, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3295, "s": 3235, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3356, "s": 3295, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Remote Method Invocation in Java
22 Mar, 2022 Remote Method Invocation (RMI) is an API that allows an object to invoke a method on an object that exists in another address space, which could be on the same machine or on a remote machine. Through RMI, an object running in a JVM present on a computer (Client-side) can invoke methods on an object present in another JVM (Server-side). RMI creates a public remote server object that enables client and server-side communications through simple method calls on the server object. Stub Object: The stub object on the client machine builds an information block and sends this information to the server. The block consists of An identifier of the remote object to be used Method name which is to be invoked Parameters to the remote JVM Skeleton Object: The skeleton object passes the request from the stub object to the remote object. It performs the following tasks It calls the desired method on the real object present on the server. It forwards the parameters received from the stub object to the method. The communication between client and server is handled by using two intermediate objects: Stub object (on client side) and Skeleton object (on server-side) as also can be depicted from below media as follows: These are the steps to be followed sequentially to implement Interface as defined below as follows: Defining a remote interfaceImplementing the remote interfaceCreating Stub and Skeleton objects from the implementation class using rmic (RMI compiler)Start the rmiregistryCreate and execute the server application programCreate and execute the client application program. Defining a remote interface Implementing the remote interface Creating Stub and Skeleton objects from the implementation class using rmic (RMI compiler) Start the rmiregistry Create and execute the server application program Create and execute the client application program. Step 1: Defining the remote interface The first thing to do is to create an interface that will provide the description of the methods that can be invoked by remote clients. This interface should extend the Remote interface and the method prototype within the interface should throw the RemoteException. Example: Java // Creating a Search interfaceimport java.rmi.*;public interface Search extends Remote{ // Declaring the method prototype public String query(String search) throws RemoteException;} Step 2: Implementing the remote interfaceThe next step is to implement the remote interface. To implement the remote interface, the class should extend to UnicastRemoteObject class of java.rmi package. Also, a default constructor needs to be created to throw the java.rmi.RemoteException from its parent constructor in class. Java // Java program to implement the Search interfaceimport java.rmi.*;import java.rmi.server.*;public class SearchQuery extends UnicastRemoteObject implements Search{ // Default constructor to throw RemoteException // from its parent constructor SearchQuery() throws RemoteException { super(); } // Implementation of the query interface public String query(String search) throws RemoteException { String result; if (search.equals("Reflection in Java")) result = "Found"; else result = "Not Found"; return result; }} Step 3: Creating Stub and Skeleton objects from the implementation class using rmicThe rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton objects. Its prototype is rmic classname. For above program the following command need to be executed at the command promptrmic SearchQuery.Step 4: Start the rmiregistryStart the registry service by issuing the following command at the command prompt start rmiregistryStep 5: Create and execute the server application programThe next step is to create the server application program and execute it on a separate command prompt. The server program uses createRegistry method of LocateRegistry class to create rmiregistry within the server JVM with the port number passed as an argument. The rebind method of Naming class is used to bind the remote object to the new name. Java // Java program for server applicationimport java.rmi.*;import java.rmi.registry.*;public class SearchServer{ public static void main(String args[]) { try { // Create an object of the interface // implementation class Search obj = new SearchQuery(); // rmiregistry within the server JVM with // port number 1900 LocateRegistry.createRegistry(1900); // Binds the remote object by the name // geeksforgeeks Naming.rebind("rmi://localhost:1900"+ "/geeksforgeeks",obj); } catch(Exception ae) { System.out.println(ae); } }} Step 6: Create and execute the client application programThe last step is to create the client application program and execute it on a separate command prompt . The lookup method of the Naming class is used to get the reference of the Stub object. Java // Java program for client applicationimport java.rmi.*;public class ClientRequest{ public static void main(String args[]) { String answer,value="Reflection in Java"; try { // lookup method to find reference of remote object Search access = (Search)Naming.lookup("rmi://localhost:1900"+ "/geeksforgeeks"); answer = access.query(value); System.out.println("Article on " + value + " " + answer+" at GeeksforGeeks"); } catch(Exception ae) { System.out.println(ae); } }} Note: The above client and server program is executed on the same machine so localhost is used. In order to access the remote object from another machine, localhost is to be replaced with the IP address where the remote object is present. save the files respectively as per class name as Search.java , SearchQuery.java , SearchServer.java & ClientRequest.javaImportant Observations: RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the distributed applications in java.Stub and Skeleton objects are used for communication between the client and server-side. RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the distributed applications in java. Stub and Skeleton objects are used for communication between the client and server-side. This article is contributed by Aakash Ojha. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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. solankimayank challiyilshrra18ce Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Mar, 2022" }, { "code": null, "e": 533, "s": 52, "text": "Remote Method Invocation (RMI) is an API that allows an object to invoke a method on an object that exists in another address space, which could be on the same machine or on a remote machine. Through RMI, an object running in a JVM present on a computer (Client-side) can invoke methods on an object present in another JVM (Server-side). RMI creates a public remote server object that enables client and server-side communications through simple method calls on the server object." }, { "code": null, "e": 654, "s": 533, "text": "Stub Object: The stub object on the client machine builds an information block and sends this information to the server." }, { "code": null, "e": 676, "s": 654, "text": "The block consists of" }, { "code": null, "e": 722, "s": 676, "text": "An identifier of the remote object to be used" }, { "code": null, "e": 757, "s": 722, "text": "Method name which is to be invoked" }, { "code": null, "e": 786, "s": 757, "text": "Parameters to the remote JVM" }, { "code": null, "e": 917, "s": 786, "text": "Skeleton Object: The skeleton object passes the request from the stub object to the remote object. It performs the following tasks" }, { "code": null, "e": 987, "s": 917, "text": "It calls the desired method on the real object present on the server." }, { "code": null, "e": 1059, "s": 987, "text": "It forwards the parameters received from the stub object to the method." }, { "code": null, "e": 1268, "s": 1059, "text": "The communication between client and server is handled by using two intermediate objects: Stub object (on client side) and Skeleton object (on server-side) as also can be depicted from below media as follows:" }, { "code": null, "e": 1368, "s": 1268, "text": "These are the steps to be followed sequentially to implement Interface as defined below as follows:" }, { "code": null, "e": 1639, "s": 1368, "text": "Defining a remote interfaceImplementing the remote interfaceCreating Stub and Skeleton objects from the implementation class using rmic (RMI compiler)Start the rmiregistryCreate and execute the server application programCreate and execute the client application program." }, { "code": null, "e": 1667, "s": 1639, "text": "Defining a remote interface" }, { "code": null, "e": 1701, "s": 1667, "text": "Implementing the remote interface" }, { "code": null, "e": 1792, "s": 1701, "text": "Creating Stub and Skeleton objects from the implementation class using rmic (RMI compiler)" }, { "code": null, "e": 1814, "s": 1792, "text": "Start the rmiregistry" }, { "code": null, "e": 1864, "s": 1814, "text": "Create and execute the server application program" }, { "code": null, "e": 1915, "s": 1864, "text": "Create and execute the client application program." }, { "code": null, "e": 1953, "s": 1915, "text": "Step 1: Defining the remote interface" }, { "code": null, "e": 2219, "s": 1953, "text": "The first thing to do is to create an interface that will provide the description of the methods that can be invoked by remote clients. This interface should extend the Remote interface and the method prototype within the interface should throw the RemoteException." }, { "code": null, "e": 2228, "s": 2219, "text": "Example:" }, { "code": null, "e": 2233, "s": 2228, "text": "Java" }, { "code": "// Creating a Search interfaceimport java.rmi.*;public interface Search extends Remote{ // Declaring the method prototype public String query(String search) throws RemoteException;}", "e": 2421, "s": 2233, "text": null }, { "code": null, "e": 2747, "s": 2421, "text": "Step 2: Implementing the remote interfaceThe next step is to implement the remote interface. To implement the remote interface, the class should extend to UnicastRemoteObject class of java.rmi package. Also, a default constructor needs to be created to throw the java.rmi.RemoteException from its parent constructor in class." }, { "code": null, "e": 2752, "s": 2747, "text": "Java" }, { "code": "// Java program to implement the Search interfaceimport java.rmi.*;import java.rmi.server.*;public class SearchQuery extends UnicastRemoteObject implements Search{ // Default constructor to throw RemoteException // from its parent constructor SearchQuery() throws RemoteException { super(); } // Implementation of the query interface public String query(String search) throws RemoteException { String result; if (search.equals(\"Reflection in Java\")) result = \"Found\"; else result = \"Not Found\"; return result; }}", "e": 3399, "s": 2752, "text": null }, { "code": null, "e": 3994, "s": 3399, "text": "Step 3: Creating Stub and Skeleton objects from the implementation class using rmicThe rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton objects. Its prototype is rmic classname. For above program the following command need to be executed at the command promptrmic SearchQuery.Step 4: Start the rmiregistryStart the registry service by issuing the following command at the command prompt start rmiregistryStep 5: Create and execute the server application programThe next step is to create the server application program and execute it on a separate command prompt." }, { "code": null, "e": 4152, "s": 3994, "text": "The server program uses createRegistry method of LocateRegistry class to create rmiregistry within the server JVM with the port number passed as an argument." }, { "code": null, "e": 4237, "s": 4152, "text": "The rebind method of Naming class is used to bind the remote object to the new name." }, { "code": null, "e": 4242, "s": 4237, "text": "Java" }, { "code": "// Java program for server applicationimport java.rmi.*;import java.rmi.registry.*;public class SearchServer{ public static void main(String args[]) { try { // Create an object of the interface // implementation class Search obj = new SearchQuery(); // rmiregistry within the server JVM with // port number 1900 LocateRegistry.createRegistry(1900); // Binds the remote object by the name // geeksforgeeks Naming.rebind(\"rmi://localhost:1900\"+ \"/geeksforgeeks\",obj); } catch(Exception ae) { System.out.println(ae); } }}", "e": 4951, "s": 4242, "text": null }, { "code": null, "e": 5199, "s": 4951, "text": "Step 6: Create and execute the client application programThe last step is to create the client application program and execute it on a separate command prompt . The lookup method of the Naming class is used to get the reference of the Stub object." }, { "code": null, "e": 5204, "s": 5199, "text": "Java" }, { "code": "// Java program for client applicationimport java.rmi.*;public class ClientRequest{ public static void main(String args[]) { String answer,value=\"Reflection in Java\"; try { // lookup method to find reference of remote object Search access = (Search)Naming.lookup(\"rmi://localhost:1900\"+ \"/geeksforgeeks\"); answer = access.query(value); System.out.println(\"Article on \" + value + \" \" + answer+\" at GeeksforGeeks\"); } catch(Exception ae) { System.out.println(ae); } }}", "e": 5863, "s": 5204, "text": null }, { "code": null, "e": 6102, "s": 5863, "text": "Note: The above client and server program is executed on the same machine so localhost is used. In order to access the remote object from another machine, localhost is to be replaced with the IP address where the remote object is present." }, { "code": null, "e": 6151, "s": 6102, "text": "save the files respectively as per class name as" }, { "code": null, "e": 6246, "s": 6151, "text": "Search.java , SearchQuery.java , SearchServer.java & ClientRequest.javaImportant Observations:" }, { "code": null, "e": 6454, "s": 6246, "text": "RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the distributed applications in java.Stub and Skeleton objects are used for communication between the client and server-side." }, { "code": null, "e": 6574, "s": 6454, "text": "RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the distributed applications in java." }, { "code": null, "e": 6663, "s": 6574, "text": "Stub and Skeleton objects are used for communication between the client and server-side." }, { "code": null, "e": 7054, "s": 6663, "text": "This article is contributed by Aakash Ojha. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 7068, "s": 7054, "text": "solankimayank" }, { "code": null, "e": 7087, "s": 7068, "text": "challiyilshrra18ce" }, { "code": null, "e": 7092, "s": 7087, "text": "Java" }, { "code": null, "e": 7097, "s": 7092, "text": "Java" } ]
Visualize Graphs in Python
17 May, 2022 Prerequisites: Graph Data Structure And Algorithms A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. In this tutorial we are going to visualize undirected Graphs in Python with the help of networkx library. Installation: To install this module type the below command in the terminal. pip install networkx Below is the implementation. # First networkx library is imported # along with matplotlibimport networkx as nximport matplotlib.pyplot as plt # Defining a Classclass GraphVisualization: def __init__(self): # visual is a list which stores all # the set of edges that constitutes a # graph self.visual = [] # addEdge function inputs the vertices of an # edge and appends it to the visual list def addEdge(self, a, b): temp = [a, b] self.visual.append(temp) # In visualize function G is an object of # class Graph given by networkx G.add_edges_from(visual) # creates a graph with a given list # nx.draw_networkx(G) - plots the graph # plt.show() - displays the graph def visualize(self): G = nx.Graph() G.add_edges_from(self.visual) nx.draw_networkx(G) plt.show() # Driver codeG = GraphVisualization()G.addEdge(0, 2)G.addEdge(1, 2)G.addEdge(1, 3)G.addEdge(5, 3)G.addEdge(3, 4)G.addEdge(1, 0)G.visualize() Output: graph-basics Python-matplotlib python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n17 May, 2022" }, { "code": null, "e": 105, "s": 54, "text": "Prerequisites: Graph Data Structure And Algorithms" }, { "code": null, "e": 301, "s": 105, "text": "A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph." }, { "code": null, "e": 407, "s": 301, "text": "In this tutorial we are going to visualize undirected Graphs in Python with the help of networkx library." }, { "code": null, "e": 421, "s": 407, "text": "Installation:" }, { "code": null, "e": 484, "s": 421, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 505, "s": 484, "text": "pip install networkx" }, { "code": null, "e": 534, "s": 505, "text": "Below is the implementation." }, { "code": "# First networkx library is imported # along with matplotlibimport networkx as nximport matplotlib.pyplot as plt # Defining a Classclass GraphVisualization: def __init__(self): # visual is a list which stores all # the set of edges that constitutes a # graph self.visual = [] # addEdge function inputs the vertices of an # edge and appends it to the visual list def addEdge(self, a, b): temp = [a, b] self.visual.append(temp) # In visualize function G is an object of # class Graph given by networkx G.add_edges_from(visual) # creates a graph with a given list # nx.draw_networkx(G) - plots the graph # plt.show() - displays the graph def visualize(self): G = nx.Graph() G.add_edges_from(self.visual) nx.draw_networkx(G) plt.show() # Driver codeG = GraphVisualization()G.addEdge(0, 2)G.addEdge(1, 2)G.addEdge(1, 3)G.addEdge(5, 3)G.addEdge(3, 4)G.addEdge(1, 0)G.visualize()", "e": 1546, "s": 534, "text": null }, { "code": null, "e": 1554, "s": 1546, "text": "Output:" }, { "code": null, "e": 1567, "s": 1554, "text": "graph-basics" }, { "code": null, "e": 1585, "s": 1567, "text": "Python-matplotlib" }, { "code": null, "e": 1600, "s": 1585, "text": "python-utility" }, { "code": null, "e": 1607, "s": 1600, "text": "Python" }, { "code": null, "e": 1705, "s": 1607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1723, "s": 1705, "text": "Python Dictionary" }, { "code": null, "e": 1765, "s": 1723, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1787, "s": 1765, "text": "Enumerate() in Python" }, { "code": null, "e": 1822, "s": 1787, "text": "Read a file line by line in Python" }, { "code": null, "e": 1848, "s": 1822, "text": "Python String | replace()" }, { "code": null, "e": 1880, "s": 1848, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1909, "s": 1880, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1936, "s": 1909, "text": "Python Classes and Objects" }, { "code": null, "e": 1966, "s": 1936, "text": "Iterate over a list in Python" } ]
Simplification and Approximation - GeeksforGeeks
13 May, 2016 10152 = (1000+15)2 = 10002 + 152 +2 x 1000 x 15 =1000000 + 225 + 30000 =1030225 10152 = (1000+15)2 = 10002 + 152 +2 x 1000 x 15 =1000000 + 225 + 30000 =1030225 103 x 103 + 97 x 97 = (100+3)2 + (100-3)2 = 2 (1002 + 32 ) [ (X +Y)2 + ( X – Y)2 = 2 ( X2 + Y2 ) ] = 2 (10000 + 9 ) = 2 x 10009 = 20018 9848 x 125 = 9848 x (250 / 2) = 4924 x (500 / 2) = 2462 x (1000 / 2) = 1231 x (1000) = 1231000 Let X=500 & Y=12 Now, (X + Y)2 + (X – Y)2 = 2 ( X2 + Y2 ) = 2 ( 5002 + 122 ) = 2 ( 250000 + 144 ) = 2 * 250144 = 500288 Let (x / √216) = (√96 / x) Then x2 = √(216 x 96) = √(36 x 2 x 3 x 16 x 2 x 3) = √(62 x 42 x 22 x 32) = 6 x 4 x 2 x 3 = 144 Or x = 12 Given series is a G. P. with a = 7, r = 7 and n = 6 ∴ Sn = a(rn-1) / (r-1) ∴ Sn = 7(76-1) / 6 Sn = = 137256 1 1 <- CARRY 5 X 8 + 3 Y 4 + 2 Z 1 -------- 11 0 3 -------- In 267 unit digit is 7 and cyclicity of 7 is 4. So, (267)153 can be written as (267)Rem(153)/4 = (267)1 Unit digit of (267)1 = 7. similarly for 66666 unit digit is 6 and cyclicity for 6 is 1. Unit digit for (66666)72 = 6. Therefore , Unit digit of the resultant is 7 * 6 = 2 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies Types of Distributed System SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Java Threads Top 20 Puzzles Commonly Asked During SDE Interviews Optimization of Basic Blocks Tejas Networks Interview Experience for R&D Engineer TCS NQT Coding Sheet
[ { "code": null, "e": 29577, "s": 29549, "text": "\n13 May, 2016" }, { "code": null, "e": 29657, "s": 29577, "text": "10152 = (1000+15)2\n= 10002 + 152 +2 x 1000 x 15\n=1000000 + 225 + 30000\n=1030225" }, { "code": null, "e": 29676, "s": 29657, "text": "10152 = (1000+15)2" }, { "code": null, "e": 29705, "s": 29676, "text": "= 10002 + 152 +2 x 1000 x 15" }, { "code": null, "e": 29728, "s": 29705, "text": "=1000000 + 225 + 30000" }, { "code": null, "e": 29737, "s": 29728, "text": "=1030225" }, { "code": null, "e": 29875, "s": 29737, "text": "103 x 103 + 97 x 97\n= (100+3)2 + (100-3)2\n= 2 (1002 + 32 ) \n[ (X +Y)2 + ( X – Y)2 = 2 ( X2 + Y2 ) ]\n= 2 (10000 + 9 )\n= 2 x 10009\n= 20018" }, { "code": null, "e": 30014, "s": 29875, "text": "9848 x 125 = 9848 x (250 / 2)\n = 4924 x (500 / 2)\n = 2462 x (1000 / 2)\n = 1231 x (1000)\n = 1231000" }, { "code": null, "e": 30157, "s": 30014, "text": "Let X=500 & Y=12\nNow, (X + Y)2 + (X – Y)2 = 2 ( X2 + Y2 )\n\t\t = 2 ( 5002 + 122 )\n \t\t\t= 2 ( 250000 + 144 )\n \t\t\t= 2 * 250144\n \t\t\t= 500288\n" }, { "code": null, "e": 30320, "s": 30157, "text": "Let (x / √216) = (√96 / x)\n\nThen x2 = √(216 x 96)\n = √(36 x 2 x 3 x 16 x 2 x 3)\n = √(62 x 42 x 22 x 32)\n = 6 x 4 x 2 x 3\n = 144\nOr x = 12\n" }, { "code": null, "e": 30433, "s": 30320, "text": "Given series is a G. P. with a = 7, r = 7 and n = 6\n\n∴ Sn = a(rn-1) / (r-1)\n\n∴ Sn = 7(76-1) / 6\n\n Sn = = 137256" }, { "code": null, "e": 30503, "s": 30433, "text": " 1 1 <- CARRY\n\n 5 X 8\n+ 3 Y 4\n+ 2 Z 1\n--------\n 11 0 3\n--------\n" }, { "code": null, "e": 30780, "s": 30503, "text": "In 267 unit digit is 7 and cyclicity of 7 is 4.\nSo, (267)153 can be written as (267)Rem(153)/4 = (267)1 \nUnit digit of (267)1 = 7.\nsimilarly for 66666 unit digit is 6 and cyclicity for 6 is 1.\nUnit digit for (66666)72 = 6.\n\nTherefore , Unit digit of the resultant is 7 * 6 = 2" }, { "code": null, "e": 30878, "s": 30780, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 30952, "s": 30878, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 31005, "s": 30952, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 31033, "s": 31005, "text": "Types of Distributed System" }, { "code": null, "e": 31082, "s": 31033, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31107, "s": 31082, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31120, "s": 31107, "text": "Java Threads" }, { "code": null, "e": 31172, "s": 31120, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 31201, "s": 31172, "text": "Optimization of Basic Blocks" }, { "code": null, "e": 31255, "s": 31201, "text": "Tejas Networks Interview Experience for R&D Engineer" } ]
Java Swing | JSeparator with examples
22 Jul, 2021 JSeparator is a part of Java Swing framework. It is used to create a dividing line between two components. More specifically, it is mainly used to create dividing lines between menu items in a JMenu. In JMenu or JPopupMenu addSeparartor function can also be used to create a separator. Constructor of the class are: separator(): Creates a new horizontal separator.JSeparator(int o): Creates a new separator with the specified horizontal or vertical orientation. separator(): Creates a new horizontal separator. JSeparator(int o): Creates a new separator with the specified horizontal or vertical orientation. Commonly used methods: Below programs will illustrate the use of JSeparartor 1. Program to create a vertical separator: In this program we create a frame which is named f with a title “separator” (frame is the container for other components). We create a panel to hold the labels and the separator. We set the orientation of the separator to vertical (using setOrientation(SwingConstants.VERTICAL)) and add the separator and the labels to the panel (using add() function)and add the panel to the frame. We set grid layout (using new GridLayout(400,400))for the panel with 1 row and 0 columns. We set the size of the frame using setSize(400,400) to 400,400. We use the show() function to display the frame. Java // java Program to create a vertical separatorimport java.awt.*;import javax.swing.*;class separator extends JFrame{ // constructor for the class separator() { } // main class public static void main(String args[]) { // create a frame JFrame f = new JFrame("separator"); // create a panel JPanel p =new JPanel(); // create a label JLabel l = new JLabel("this is label 1"); JLabel l1 = new JLabel("this is label 2"); // create a separator JSeparator s = new JSeparator(); // set layout as vertical s.setOrientation(SwingConstants.VERTICAL); p.add(l); p.add(s); p.add(l1); // set layout p.setLayout(new GridLayout(1,0)); f.add(p); // show the frame f.setSize(400,400); f.show(); }} Output: 2. Program to create a horizontal separator: In this program, we create a frame which is named f with a title “separator” (frame is the container for other components). We create a panel to hold the labels and the separator. We set the orientation of the separator to horizontal(using setOrientation(SwingConstants.HORIZONTAL)) and add the separator and the labels to the panel (using add() function)and add the panel to the frame. We set grid layout (using new GridLayout(400,400)) for the panel with 0 row and 1 columns. We set the size of the frame using setSize(400,400) to 400,400 . We use the show() function to display the frame. Java // java Program to create a HORIZONTAL separatorimport java.awt.*;import javax.swing.*;class separator_1 extends JFrame{ // constructor for the class separator_1() { } // main class public static void main(String args[]) { // create a frame JFrame f = new JFrame("separator"); // create a panel JPanel p =new JPanel(); // create a label JLabel l = new JLabel("this is label 1"); JLabel l1 = new JLabel("this is label 2"); // create a separator JSeparator s = new JSeparator(); // set layout as vertical s.setOrientation(SwingConstants.HORIZONTAL); p.add(l); p.add(s); p.add(l1); // set layout p.setLayout(new GridLayout(0,1)); f.add(p); // show the frame f.setSize(400,400); f.show(); }} Output: 3. Program to create a separator using addSeparator function: In this program we create a frame which is named f with a title “separator” (frame is the container for other components). To illustrate the use of the add separator function we will create a JMenuBar mb. Then create a JMenu to hold the menuitems. We will create two JMenuItems and add a separator in between them by using addSeparator() function. We will add the menu to menubar and menubar to the frame using add() and addMenuBar() functions respectively. We set the size of the frame using setSize(400,400) to 400,400. We use the show() function to display the frame. Java // java Program to create a separator// using addSeparator functionimport java.awt.*;import javax.swing.*;class separator extends JFrame{ // constructor for the class separator() { } // main class public static void main(String args[]) { // create a frame JFrame f = new JFrame("separator"); // create a menubar JMenuBar mb =new JMenuBar(); // create a menu JMenu m = new JMenu("menu"); // create menuitems JMenuItem m1= new JMenuItem("item 1"); JMenuItem m2= new JMenuItem("item 2"); // add menuitems m.add(m1); m.addSeparator(); m.add(m2); // add menu mb.add(m); f.setJMenuBar(mb); // show the frame f.setSize(400,400); f.show(); }} Output: ManasChhabra2 anikakapoor sweetyty java-swing Java 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": "\n22 Jul, 2021" }, { "code": null, "e": 314, "s": 28, "text": "JSeparator is a part of Java Swing framework. It is used to create a dividing line between two components. More specifically, it is mainly used to create dividing lines between menu items in a JMenu. In JMenu or JPopupMenu addSeparartor function can also be used to create a separator." }, { "code": null, "e": 345, "s": 314, "text": "Constructor of the class are: " }, { "code": null, "e": 491, "s": 345, "text": "separator(): Creates a new horizontal separator.JSeparator(int o): Creates a new separator with the specified horizontal or vertical orientation." }, { "code": null, "e": 540, "s": 491, "text": "separator(): Creates a new horizontal separator." }, { "code": null, "e": 638, "s": 540, "text": "JSeparator(int o): Creates a new separator with the specified horizontal or vertical orientation." }, { "code": null, "e": 662, "s": 638, "text": "Commonly used methods: " }, { "code": null, "e": 717, "s": 662, "text": "Below programs will illustrate the use of JSeparartor " }, { "code": null, "e": 1346, "s": 717, "text": "1. Program to create a vertical separator: In this program we create a frame which is named f with a title “separator” (frame is the container for other components). We create a panel to hold the labels and the separator. We set the orientation of the separator to vertical (using setOrientation(SwingConstants.VERTICAL)) and add the separator and the labels to the panel (using add() function)and add the panel to the frame. We set grid layout (using new GridLayout(400,400))for the panel with 1 row and 0 columns. We set the size of the frame using setSize(400,400) to 400,400. We use the show() function to display the frame." }, { "code": null, "e": 1351, "s": 1346, "text": "Java" }, { "code": "// java Program to create a vertical separatorimport java.awt.*;import javax.swing.*;class separator extends JFrame{ // constructor for the class separator() { } // main class public static void main(String args[]) { // create a frame JFrame f = new JFrame(\"separator\"); // create a panel JPanel p =new JPanel(); // create a label JLabel l = new JLabel(\"this is label 1\"); JLabel l1 = new JLabel(\"this is label 2\"); // create a separator JSeparator s = new JSeparator(); // set layout as vertical s.setOrientation(SwingConstants.VERTICAL); p.add(l); p.add(s); p.add(l1); // set layout p.setLayout(new GridLayout(1,0)); f.add(p); // show the frame f.setSize(400,400); f.show(); }}", "e": 2272, "s": 1351, "text": null }, { "code": null, "e": 2281, "s": 2272, "text": "Output: " }, { "code": null, "e": 2918, "s": 2281, "text": "2. Program to create a horizontal separator: In this program, we create a frame which is named f with a title “separator” (frame is the container for other components). We create a panel to hold the labels and the separator. We set the orientation of the separator to horizontal(using setOrientation(SwingConstants.HORIZONTAL)) and add the separator and the labels to the panel (using add() function)and add the panel to the frame. We set grid layout (using new GridLayout(400,400)) for the panel with 0 row and 1 columns. We set the size of the frame using setSize(400,400) to 400,400 . We use the show() function to display the frame." }, { "code": null, "e": 2923, "s": 2918, "text": "Java" }, { "code": "// java Program to create a HORIZONTAL separatorimport java.awt.*;import javax.swing.*;class separator_1 extends JFrame{ // constructor for the class separator_1() { } // main class public static void main(String args[]) { // create a frame JFrame f = new JFrame(\"separator\"); // create a panel JPanel p =new JPanel(); // create a label JLabel l = new JLabel(\"this is label 1\"); JLabel l1 = new JLabel(\"this is label 2\"); // create a separator JSeparator s = new JSeparator(); // set layout as vertical s.setOrientation(SwingConstants.HORIZONTAL); p.add(l); p.add(s); p.add(l1); // set layout p.setLayout(new GridLayout(0,1)); f.add(p); // show the frame f.setSize(400,400); f.show(); }}", "e": 3852, "s": 2923, "text": null }, { "code": null, "e": 3861, "s": 3852, "text": "Output: " }, { "code": null, "e": 4494, "s": 3861, "text": "3. Program to create a separator using addSeparator function: In this program we create a frame which is named f with a title “separator” (frame is the container for other components). To illustrate the use of the add separator function we will create a JMenuBar mb. Then create a JMenu to hold the menuitems. We will create two JMenuItems and add a separator in between them by using addSeparator() function. We will add the menu to menubar and menubar to the frame using add() and addMenuBar() functions respectively. We set the size of the frame using setSize(400,400) to 400,400. We use the show() function to display the frame." }, { "code": null, "e": 4499, "s": 4494, "text": "Java" }, { "code": "// java Program to create a separator// using addSeparator functionimport java.awt.*;import javax.swing.*;class separator extends JFrame{ // constructor for the class separator() { } // main class public static void main(String args[]) { // create a frame JFrame f = new JFrame(\"separator\"); // create a menubar JMenuBar mb =new JMenuBar(); // create a menu JMenu m = new JMenu(\"menu\"); // create menuitems JMenuItem m1= new JMenuItem(\"item 1\"); JMenuItem m2= new JMenuItem(\"item 2\"); // add menuitems m.add(m1); m.addSeparator(); m.add(m2); // add menu mb.add(m); f.setJMenuBar(mb); // show the frame f.setSize(400,400); f.show(); }}", "e": 5359, "s": 4499, "text": null }, { "code": null, "e": 5369, "s": 5359, "text": "Output: " }, { "code": null, "e": 5385, "s": 5371, "text": "ManasChhabra2" }, { "code": null, "e": 5397, "s": 5385, "text": "anikakapoor" }, { "code": null, "e": 5406, "s": 5397, "text": "sweetyty" }, { "code": null, "e": 5417, "s": 5406, "text": "java-swing" }, { "code": null, "e": 5422, "s": 5417, "text": "Java" }, { "code": null, "e": 5427, "s": 5422, "text": "Java" }, { "code": null, "e": 5525, "s": 5427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5540, "s": 5525, "text": "Stream In Java" }, { "code": null, "e": 5561, "s": 5540, "text": "Introduction to Java" }, { "code": null, "e": 5582, "s": 5561, "text": "Constructors in Java" }, { "code": null, "e": 5601, "s": 5582, "text": "Exceptions in Java" }, { "code": null, "e": 5618, "s": 5601, "text": "Generics in Java" }, { "code": null, "e": 5648, "s": 5618, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5674, "s": 5648, "text": "Java Programming Examples" }, { "code": null, "e": 5690, "s": 5674, "text": "Strings in Java" }, { "code": null, "e": 5727, "s": 5690, "text": "Differences between JDK, JRE and JVM" } ]
GATE | GATE CS 2019 | Question 19
14 Feb, 2019 Let G be an undirected complete graph on n vertices, where n > 2. Then, the number of different Hamiltonian cycles in G is equal to (A) n!(B) n – 1!(C) 1(D) (n-1)! / 2Answer: (D)Explanation: A simple circuit in a graph G that passes through every vertex exactly once is called a Hamiltonian circuit. In an undirected complete graph on n vertices, there are n permutations are possible to visit every node. But from these permutations, there are: n different places (i.e., nodes) you can start;2 (clockwise or anticlockwise) different directions you can travel. n different places (i.e., nodes) you can start; 2 (clockwise or anticlockwise) different directions you can travel. So any one of these n! cycles is in a set of 2n cycles which all contain the same set of edges. So there are, = (n)! / (2n) = (n−1)! / 2 distinct Hamilton cycles. Option (D) is correct.Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2004 | Question 31
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Feb, 2019" }, { "code": null, "e": 160, "s": 28, "text": "Let G be an undirected complete graph on n vertices, where n > 2. Then, the number of different Hamiltonian cycles in G is equal to" }, { "code": null, "e": 328, "s": 160, "text": "(A) n!(B) n – 1!(C) 1(D) (n-1)! / 2Answer: (D)Explanation: A simple circuit in a graph G that passes through every vertex exactly once is called a Hamiltonian circuit." }, { "code": null, "e": 474, "s": 328, "text": "In an undirected complete graph on n vertices, there are n permutations are possible to visit every node. But from these permutations, there are:" }, { "code": null, "e": 589, "s": 474, "text": "n different places (i.e., nodes) you can start;2 (clockwise or anticlockwise) different directions you can travel." }, { "code": null, "e": 637, "s": 589, "text": "n different places (i.e., nodes) you can start;" }, { "code": null, "e": 705, "s": 637, "text": "2 (clockwise or anticlockwise) different directions you can travel." }, { "code": null, "e": 815, "s": 705, "text": "So any one of these n! cycles is in a set of 2n cycles which all contain the same set of edges. So there are," }, { "code": null, "e": 869, "s": 815, "text": "= (n)! / (2n)\n= (n−1)! / 2 distinct Hamilton cycles. " }, { "code": null, "e": 913, "s": 869, "text": "Option (D) is correct.Quiz of this Question" }, { "code": null, "e": 918, "s": 913, "text": "GATE" }, { "code": null, "e": 1016, "s": 918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1058, "s": 1016, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1120, "s": 1058, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1162, "s": 1120, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 1196, "s": 1162, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1238, "s": 1196, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1272, "s": 1238, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 1314, "s": 1272, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1356, "s": 1314, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 1390, "s": 1356, "text": "GATE | GATE CS 1996 | Question 63" } ]
How to Remove Firebase Authentication in Android Studio?
29 Dec, 2021 Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps, such as: A blended environment where one can develop for all Android devices Apply Changes to push code and resource changes to the running app without restarting the app A flexible Gradle-based build system A fast and feature-rich emulator GitHub and Code template integration to assist you to develop common app features and importing sample code Extensive testing tools and frameworks C++ and NDK support Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine, and many more. Here, we are going to Remove Firebase Authentication in Android Studio. We are going to remove the firebase project connected to our app. This feature can be implemented when want to change the firebase project connected to our app. We can simply remove the connect project and then we can add another project with our app. Step 1: Go to the top and Click on Project Step 2: Here Go to the google-services.json file Step 3: Here, Right Click on it and then Select Show in Explorer and then close Android Studio of our current app. Then delete this file from your folder Step 4: Now, Move to build.gradle (project) and remove this line classpath 'com.google.gms:google-services:4.2.0' Remove this line also from the build.gradle (app) implementation 'com.google.firebase:firebase-database:19.0.0' implementation 'com.google.firebase:firebase-storage:19.1.1' implementation 'com.google.firebase:firebase-auth:19.0.0' Remove this line also from the build.gradle (app) apply plugin: 'com.google.gms.google-services' Now we have successfully removed the firebase project from our app. Now we can either add another Firebase project or leave. Android-Studio Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2021" }, { "code": null, "e": 293, "s": 28, "text": "Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps, such as:" }, { "code": null, "e": 361, "s": 293, "text": "A blended environment where one can develop for all Android devices" }, { "code": null, "e": 455, "s": 361, "text": "Apply Changes to push code and resource changes to the running app without restarting the app" }, { "code": null, "e": 492, "s": 455, "text": "A flexible Gradle-based build system" }, { "code": null, "e": 525, "s": 492, "text": "A fast and feature-rich emulator" }, { "code": null, "e": 633, "s": 525, "text": "GitHub and Code template integration to assist you to develop common app features and importing sample code" }, { "code": null, "e": 672, "s": 633, "text": "Extensive testing tools and frameworks" }, { "code": null, "e": 692, "s": 672, "text": "C++ and NDK support" }, { "code": null, "e": 818, "s": 692, "text": "Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine, and many more." }, { "code": null, "e": 1142, "s": 818, "text": "Here, we are going to Remove Firebase Authentication in Android Studio. We are going to remove the firebase project connected to our app. This feature can be implemented when want to change the firebase project connected to our app. We can simply remove the connect project and then we can add another project with our app." }, { "code": null, "e": 1185, "s": 1142, "text": "Step 1: Go to the top and Click on Project" }, { "code": null, "e": 1234, "s": 1185, "text": "Step 2: Here Go to the google-services.json file" }, { "code": null, "e": 1388, "s": 1234, "text": "Step 3: Here, Right Click on it and then Select Show in Explorer and then close Android Studio of our current app. Then delete this file from your folder" }, { "code": null, "e": 1453, "s": 1388, "text": "Step 4: Now, Move to build.gradle (project) and remove this line" }, { "code": null, "e": 1502, "s": 1453, "text": "classpath 'com.google.gms:google-services:4.2.0'" }, { "code": null, "e": 1552, "s": 1502, "text": "Remove this line also from the build.gradle (app)" }, { "code": null, "e": 1733, "s": 1552, "text": "implementation 'com.google.firebase:firebase-database:19.0.0'\nimplementation 'com.google.firebase:firebase-storage:19.1.1'\nimplementation 'com.google.firebase:firebase-auth:19.0.0'" }, { "code": null, "e": 1783, "s": 1733, "text": "Remove this line also from the build.gradle (app)" }, { "code": null, "e": 1830, "s": 1783, "text": "apply plugin: 'com.google.gms.google-services'" }, { "code": null, "e": 1955, "s": 1830, "text": "Now we have successfully removed the firebase project from our app. Now we can either add another Firebase project or leave." }, { "code": null, "e": 1970, "s": 1955, "text": "Android-Studio" }, { "code": null, "e": 1978, "s": 1970, "text": "Android" }, { "code": null, "e": 1986, "s": 1978, "text": "Android" } ]
Why Java Collections Cannot Directly Store Primitives Types?
02 Jun, 2021 Primitive types are the most basic data types available within the Java language. Such types serve only one purpose — containing pure, simple values of a kind. Since java is a Statically typed language where each variable and expression type is already known at compile-time, thus you can not define a new operation for such primitive types. Illustration: Invalid : vector.addElement(3) ; Valid : vector.addElelment("3") ; Conclusion: Java primitive types are not referenced types. For example, int is not an Object. Java does generics using type-erasure of reference types. For example, A List<?> is really a List<Object> at run-time. Collections are the framework used to store and manipulate a group of objects. Java Collection means a single unit of objects. Since the above two statements are true, generic Java collections can not store primitive types directly. Wrapper Class provides a way to use primitive data types (int, boolean, etc..) as objects or a Wrapper class is a class whose object wraps or contains primitive data types. It gives birth to two concepts as follows: AutoboxingUnboxing Autoboxing Unboxing Autoboxing is the automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For instance: Conversion of int to Integer Conversion of long to Long Conversion of double to Double, etc. Unboxing is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc. Illustration: Autoboxing Java // Importing input output classesimport java.io.*; class GFG { // Main driver method public static void main(String args[]) { // Custom input Integer i = new Integer(21); // Boxing Integer j = 5; System.out.println("i=" + i + "\n j=" + j); }} Output: i=21 j=5 Illustration 2: Unboxing Java // Import input output classesimport java.io.*; // Classpublic class GFG { // MAin driver method public static void main(String args[]) { // Custom input Integer i = new Integer(50); // Unboxing int a = i; // Unboxing int b = i.intValue(); // Print and display System.out.println("a=" + a + "\nb=" + b); }} Output: a=50 b=50 Implementation: While using the collection java compiler create a wrapper Object from the primitive type and adds it to the collection using generics. Example 1: Java // Java Program to illustrate Collections// are not directly storing primitives types // Importing input output classesimport java.io.*;// Importing all classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of elements of Integer type. List<Integer> list = new ArrayList<Integer>(); // Iterating over elements of List object for (int i = 0; i < 10; i++) { // Adding the int primitives type values // If elements are added using add() method // then compiler automatically treats as // add(Integer.valueOf(i)) list.add(i); // This is what compiler does and // hence the goal achieved. // Print the primitive values System.out.println(i); } }} 0 1 2 3 4 5 6 7 8 9 Example 2: Collections to store Primitive datatype Java // Java Program to illustrate Collections// are not directly storing primitives types // Importing Map and HashMap classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of Map type Map map = new HashMap(); // Creating int wrapper object // Custom input Integer var = new Integer(21); // Storing int to map map.put("key", var); // Getting int value from map Integer refVar = (Integer)map.get("key"); // Get the integer value from wrapper object int i = refVar.intValue(); // Display message for successful compilation System.out.print("Successfully compiled and executed"); }} Output: Successfully compiled and executed saurabh1990aror Java-Collections Picked Technical Scripter 2020 Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2021" }, { "code": null, "e": 370, "s": 28, "text": "Primitive types are the most basic data types available within the Java language. Such types serve only one purpose — containing pure, simple values of a kind. Since java is a Statically typed language where each variable and expression type is already known at compile-time, thus you can not define a new operation for such primitive types." }, { "code": null, "e": 384, "s": 370, "text": "Illustration:" }, { "code": null, "e": 453, "s": 384, "text": "Invalid : vector.addElement(3) ;\nValid : vector.addElelment(\"3\") ;" }, { "code": null, "e": 465, "s": 453, "text": "Conclusion:" }, { "code": null, "e": 547, "s": 465, "text": "Java primitive types are not referenced types. For example, int is not an Object." }, { "code": null, "e": 666, "s": 547, "text": "Java does generics using type-erasure of reference types. For example, A List<?> is really a List<Object> at run-time." }, { "code": null, "e": 899, "s": 666, "text": "Collections are the framework used to store and manipulate a group of objects. Java Collection means a single unit of objects. Since the above two statements are true, generic Java collections can not store primitive types directly." }, { "code": null, "e": 1115, "s": 899, "text": "Wrapper Class provides a way to use primitive data types (int, boolean, etc..) as objects or a Wrapper class is a class whose object wraps or contains primitive data types. It gives birth to two concepts as follows:" }, { "code": null, "e": 1134, "s": 1115, "text": "AutoboxingUnboxing" }, { "code": null, "e": 1145, "s": 1134, "text": "Autoboxing" }, { "code": null, "e": 1154, "s": 1145, "text": "Unboxing" }, { "code": null, "e": 1303, "s": 1154, "text": "Autoboxing is the automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For instance:" }, { "code": null, "e": 1332, "s": 1303, "text": "Conversion of int to Integer" }, { "code": null, "e": 1359, "s": 1332, "text": "Conversion of long to Long" }, { "code": null, "e": 1396, "s": 1359, "text": "Conversion of double to Double, etc." }, { "code": null, "e": 1641, "s": 1396, "text": "Unboxing is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc." }, { "code": null, "e": 1666, "s": 1641, "text": "Illustration: Autoboxing" }, { "code": null, "e": 1671, "s": 1666, "text": "Java" }, { "code": "// Importing input output classesimport java.io.*; class GFG { // Main driver method public static void main(String args[]) { // Custom input Integer i = new Integer(21); // Boxing Integer j = 5; System.out.println(\"i=\" + i + \"\\n j=\" + j); }}", "e": 1964, "s": 1671, "text": null }, { "code": null, "e": 1972, "s": 1964, "text": "Output:" }, { "code": null, "e": 1981, "s": 1972, "text": "i=21\nj=5" }, { "code": null, "e": 2007, "s": 1981, "text": "Illustration 2: Unboxing " }, { "code": null, "e": 2012, "s": 2007, "text": "Java" }, { "code": "// Import input output classesimport java.io.*; // Classpublic class GFG { // MAin driver method public static void main(String args[]) { // Custom input Integer i = new Integer(50); // Unboxing int a = i; // Unboxing int b = i.intValue(); // Print and display System.out.println(\"a=\" + a + \"\\nb=\" + b); }}", "e": 2392, "s": 2012, "text": null }, { "code": null, "e": 2401, "s": 2392, "text": "Output: " }, { "code": null, "e": 2411, "s": 2401, "text": "a=50\nb=50" }, { "code": null, "e": 2562, "s": 2411, "text": "Implementation: While using the collection java compiler create a wrapper Object from the primitive type and adds it to the collection using generics." }, { "code": null, "e": 2574, "s": 2562, "text": "Example 1: " }, { "code": null, "e": 2579, "s": 2574, "text": "Java" }, { "code": "// Java Program to illustrate Collections// are not directly storing primitives types // Importing input output classesimport java.io.*;// Importing all classes from// java.util packageimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of elements of Integer type. List<Integer> list = new ArrayList<Integer>(); // Iterating over elements of List object for (int i = 0; i < 10; i++) { // Adding the int primitives type values // If elements are added using add() method // then compiler automatically treats as // add(Integer.valueOf(i)) list.add(i); // This is what compiler does and // hence the goal achieved. // Print the primitive values System.out.println(i); } }}", "e": 3474, "s": 2579, "text": null }, { "code": null, "e": 3494, "s": 3474, "text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9" }, { "code": null, "e": 3546, "s": 3494, "text": "Example 2: Collections to store Primitive datatype " }, { "code": null, "e": 3551, "s": 3546, "text": "Java" }, { "code": "// Java Program to illustrate Collections// are not directly storing primitives types // Importing Map and HashMap classes// from java.util packageimport java.util.HashMap;import java.util.Map; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of Map type Map map = new HashMap(); // Creating int wrapper object // Custom input Integer var = new Integer(21); // Storing int to map map.put(\"key\", var); // Getting int value from map Integer refVar = (Integer)map.get(\"key\"); // Get the integer value from wrapper object int i = refVar.intValue(); // Display message for successful compilation System.out.print(\"Successfully compiled and executed\"); }}", "e": 4393, "s": 3551, "text": null }, { "code": null, "e": 4402, "s": 4393, "text": "Output: " }, { "code": null, "e": 4437, "s": 4402, "text": "Successfully compiled and executed" }, { "code": null, "e": 4455, "s": 4439, "text": "saurabh1990aror" }, { "code": null, "e": 4472, "s": 4455, "text": "Java-Collections" }, { "code": null, "e": 4479, "s": 4472, "text": "Picked" }, { "code": null, "e": 4503, "s": 4479, "text": "Technical Scripter 2020" }, { "code": null, "e": 4508, "s": 4503, "text": "Java" }, { "code": null, "e": 4527, "s": 4508, "text": "Technical Scripter" }, { "code": null, "e": 4532, "s": 4527, "text": "Java" }, { "code": null, "e": 4549, "s": 4532, "text": "Java-Collections" } ]
C# | How to get the HashCode of the tuple?
30 Apr, 2019 A tuple is a data structure which gives you the easiest way to represent a data set. You can also get the hash code of the tuple by using the GetHashCode Method. This method will return the hash code of the given tuple object. Syntax: public override int GetHashCode (); Return Type: The return type of this method is System.Int32. It will return 32-bit signed integer hash code. Example 1: // C# program to illustrate the // use of GetHashCode methodusing System; class GFG { // Main Method static public void Main() { // creating different tuples using Create Method var tu1 = Tuple.Create(23, 45, 78, 89, 56); var tu2 = Tuple.Create(34, 45); var tu3 = Tuple.Create(45, 454, 454, 545, 4, 544, 54, 56); var tu4 = Tuple.Create(44, 58, 66, 32); // Get the hash code of the Tuples // Using GetHashCode method Console.WriteLine("HashCode for tu1: " + tu1.GetHashCode()); Console.WriteLine("HashCode for tu2: " + tu2.GetHashCode()); Console.WriteLine("HashCode for tu3: " + tu3.GetHashCode()); Console.WriteLine("HashCode for tu4: " + tu4.GetHashCode()); }} HashCode for tu1: 712149 HashCode for tu2: 1103 HashCode for tu3: 1582758 HashCode for tu4: 45300 Example 2: // C# program to illustrate the use // of the GetHashCode methodusing System; class GFG { // Main Method static public void Main() { // Creating different Tuples // using Create Method var t1 = Tuple.Create(64, 76, 78, Tuple.Create(12, 34, 56, 78)); var t2 = Tuple.Create(78, 34, 86, Tuple.Create(23, 56)); var t3 = Tuple.Create(34, 78, Tuple.Create(12, 34, 56, 78)); var t4 = Tuple.Create(12, 34, 56, 34, 56, 65, 78, Tuple.Create(24, 45, 67, 78, 89, 88)); // Get the hash code of the Tuples // Using GetHashCode method Console.WriteLine("HashCode for t1: " + t1.GetHashCode()); Console.WriteLine("HashCode for t2: " + t2.GetHashCode()); Console.WriteLine("HashCode for t3: " + t3.GetHashCode()); Console.WriteLine("HashCode for t4: " + t4.GetHashCode()); }} HashCode for t1: 78746 HashCode for t2: 83573 HashCode for t3: 47540 HashCode for t4: 672122 CSharp-Tuple C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2019" }, { "code": null, "e": 255, "s": 28, "text": "A tuple is a data structure which gives you the easiest way to represent a data set. You can also get the hash code of the tuple by using the GetHashCode Method. This method will return the hash code of the given tuple object." }, { "code": null, "e": 263, "s": 255, "text": "Syntax:" }, { "code": null, "e": 299, "s": 263, "text": "public override int GetHashCode ();" }, { "code": null, "e": 408, "s": 299, "text": "Return Type: The return type of this method is System.Int32. It will return 32-bit signed integer hash code." }, { "code": null, "e": 419, "s": 408, "text": "Example 1:" }, { "code": "// C# program to illustrate the // use of GetHashCode methodusing System; class GFG { // Main Method static public void Main() { // creating different tuples using Create Method var tu1 = Tuple.Create(23, 45, 78, 89, 56); var tu2 = Tuple.Create(34, 45); var tu3 = Tuple.Create(45, 454, 454, 545, 4, 544, 54, 56); var tu4 = Tuple.Create(44, 58, 66, 32); // Get the hash code of the Tuples // Using GetHashCode method Console.WriteLine(\"HashCode for tu1: \" + tu1.GetHashCode()); Console.WriteLine(\"HashCode for tu2: \" + tu2.GetHashCode()); Console.WriteLine(\"HashCode for tu3: \" + tu3.GetHashCode()); Console.WriteLine(\"HashCode for tu4: \" + tu4.GetHashCode()); }}", "e": 1178, "s": 419, "text": null }, { "code": null, "e": 1277, "s": 1178, "text": "HashCode for tu1: 712149\nHashCode for tu2: 1103\nHashCode for tu3: 1582758\nHashCode for tu4: 45300\n" }, { "code": null, "e": 1288, "s": 1277, "text": "Example 2:" }, { "code": "// C# program to illustrate the use // of the GetHashCode methodusing System; class GFG { // Main Method static public void Main() { // Creating different Tuples // using Create Method var t1 = Tuple.Create(64, 76, 78, Tuple.Create(12, 34, 56, 78)); var t2 = Tuple.Create(78, 34, 86, Tuple.Create(23, 56)); var t3 = Tuple.Create(34, 78, Tuple.Create(12, 34, 56, 78)); var t4 = Tuple.Create(12, 34, 56, 34, 56, 65, 78, Tuple.Create(24, 45, 67, 78, 89, 88)); // Get the hash code of the Tuples // Using GetHashCode method Console.WriteLine(\"HashCode for t1: \" + t1.GetHashCode()); Console.WriteLine(\"HashCode for t2: \" + t2.GetHashCode()); Console.WriteLine(\"HashCode for t3: \" + t3.GetHashCode()); Console.WriteLine(\"HashCode for t4: \" + t4.GetHashCode()); }}", "e": 2174, "s": 1288, "text": null }, { "code": null, "e": 2268, "s": 2174, "text": "HashCode for t1: 78746\nHashCode for t2: 83573\nHashCode for t3: 47540\nHashCode for t4: 672122\n" }, { "code": null, "e": 2281, "s": 2268, "text": "CSharp-Tuple" }, { "code": null, "e": 2284, "s": 2281, "text": "C#" } ]
How to remove an added list items using JavaScript ?
06 Jul, 2021 In the following article, we dynamically add and remove list items using JavaScript. We are using JavaScript to add and/or remove list items dynamically which means that if we run our webpage it will show the option of adding and removing items using buttons. Approach: In the webpage, one input text box is given for the user entry to add a list item. Two buttons are given to add a list item and also remove a list item. The list items are added or removed using JavaScript functions addItem() and removeItem(). The list items are created using document.createElement() method and to create a text node, document.createTextNode() method is used and then this node is appended using appendChild() method. The list item is deleted using the removeChild() method. The in-built functions used are listed below. Create new elements: We can create new elements using the document.createElement() function. It will create elements dynamically. Append element: We can append elements using the function appendchild(). Create text node: We can create a text node using the document.createTextNode() element. HTML consists of both an element node and a text node. So createTextNode() method creates a text node with the specified text. Remove existing element: We can remove a child from the created list by using removechild() function. Example: The following code demonstrates the addition and deletion of list items using JavaScript functions. HTML <!DOCTYPE html><html lang="en"> <head> <style> #candidate { border-radius: 20%; border-color: aquamarine; box-sizing: border-box; } .buttonClass { border-radius: 20%; border-color: aqua; border-style: inherit; } button:hover { background-color: green; } </style></head> <body> <ul id="list"></ul> <input type="text" id="candidate" /> <button onclick="addItem()" class="buttonClass"> Add item</button> <button onclick="removeItem()" class="buttonClass"> Remove item</button> <script> function addItem() { var a = document.getElementById("list"); var candidate = document.getElementById("candidate"); var li = document.createElement("li"); li.setAttribute('id', candidate.value); li.appendChild(document.createTextNode(candidate.value)); a.appendChild(li); } // Creating a function to remove item from list function removeItem() { // Declaring a variable to get select element var a = document.getElementById("list"); var candidate = document.getElementById("candidate"); var item = document.getElementById(candidate.value); a.removeChild(item); } </script></body> </html> Output: Now, click on add item to add any item to the list. Click on remove item to delete any item from the list. as5853535 CSS-Misc HTML-Misc JavaScript-Misc Picked Technical Scripter 2020 CSS HTML JavaScript Technical Scripter 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 ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery 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": "\n06 Jul, 2021" }, { "code": null, "e": 289, "s": 28, "text": "In the following article, we dynamically add and remove list items using JavaScript. We are using JavaScript to add and/or remove list items dynamically which means that if we run our webpage it will show the option of adding and removing items using buttons." }, { "code": null, "e": 794, "s": 289, "text": " Approach: In the webpage, one input text box is given for the user entry to add a list item. Two buttons are given to add a list item and also remove a list item. The list items are added or removed using JavaScript functions addItem() and removeItem(). The list items are created using document.createElement() method and to create a text node, document.createTextNode() method is used and then this node is appended using appendChild() method. The list item is deleted using the removeChild() method." }, { "code": null, "e": 840, "s": 794, "text": "The in-built functions used are listed below." }, { "code": null, "e": 970, "s": 840, "text": "Create new elements: We can create new elements using the document.createElement() function. It will create elements dynamically." }, { "code": null, "e": 1044, "s": 970, "text": "Append element: We can append elements using the function appendchild(). " }, { "code": null, "e": 1261, "s": 1044, "text": "Create text node: We can create a text node using the document.createTextNode() element. HTML consists of both an element node and a text node. So createTextNode() method creates a text node with the specified text." }, { "code": null, "e": 1363, "s": 1261, "text": "Remove existing element: We can remove a child from the created list by using removechild() function." }, { "code": null, "e": 1472, "s": 1363, "text": "Example: The following code demonstrates the addition and deletion of list items using JavaScript functions." }, { "code": null, "e": 1477, "s": 1472, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> #candidate { border-radius: 20%; border-color: aquamarine; box-sizing: border-box; } .buttonClass { border-radius: 20%; border-color: aqua; border-style: inherit; } button:hover { background-color: green; } </style></head> <body> <ul id=\"list\"></ul> <input type=\"text\" id=\"candidate\" /> <button onclick=\"addItem()\" class=\"buttonClass\"> Add item</button> <button onclick=\"removeItem()\" class=\"buttonClass\"> Remove item</button> <script> function addItem() { var a = document.getElementById(\"list\"); var candidate = document.getElementById(\"candidate\"); var li = document.createElement(\"li\"); li.setAttribute('id', candidate.value); li.appendChild(document.createTextNode(candidate.value)); a.appendChild(li); } // Creating a function to remove item from list function removeItem() { // Declaring a variable to get select element var a = document.getElementById(\"list\"); var candidate = document.getElementById(\"candidate\"); var item = document.getElementById(candidate.value); a.removeChild(item); } </script></body> </html>", "e": 2876, "s": 1477, "text": null }, { "code": null, "e": 2991, "s": 2876, "text": "Output: Now, click on add item to add any item to the list. Click on remove item to delete any item from the list." }, { "code": null, "e": 3001, "s": 2991, "text": "as5853535" }, { "code": null, "e": 3010, "s": 3001, "text": "CSS-Misc" }, { "code": null, "e": 3020, "s": 3010, "text": "HTML-Misc" }, { "code": null, "e": 3036, "s": 3020, "text": "JavaScript-Misc" }, { "code": null, "e": 3043, "s": 3036, "text": "Picked" }, { "code": null, "e": 3067, "s": 3043, "text": "Technical Scripter 2020" }, { "code": null, "e": 3071, "s": 3067, "text": "CSS" }, { "code": null, "e": 3076, "s": 3071, "text": "HTML" }, { "code": null, "e": 3087, "s": 3076, "text": "JavaScript" }, { "code": null, "e": 3106, "s": 3087, "text": "Technical Scripter" }, { "code": null, "e": 3123, "s": 3106, "text": "Web Technologies" }, { "code": null, "e": 3128, "s": 3123, "text": "HTML" }, { "code": null, "e": 3226, "s": 3128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3265, "s": 3226, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3304, "s": 3265, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3343, "s": 3304, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3380, "s": 3343, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3409, "s": 3380, "text": "Form validation using jQuery" }, { "code": null, "e": 3433, "s": 3409, "text": "REST API (Introduction)" }, { "code": null, "e": 3486, "s": 3433, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3546, "s": 3486, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3607, "s": 3546, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python | Pandas DataFrame.reset_index()
17 Sep, 2018 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 reset_index() is a method to reset index of a Data Frame. reset_index() method sets a list of integer ranging from 0 to length of data as index. Syntax:DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”) Parameters:level: int, string or a list to select and remove passed column from index.drop: Boolean value, Adds the replaced index column to the data if False.inplace: Boolean value, make changes in the original data frame itself if True.col_level: Select in which column level to insert the labels.col_fill: Object, to determine how the other levels are named. Return type: DataFrame To download the CSV file used, Click Here.Example #1: Resetting indexIn this example, to reset index, First name column have been set as index column first and then using reset index a new index have been generated. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # setting first name as index columndata.set_index(["First Name"], inplace = True, append = True, drop = True) # resetting indexdata.reset_index(inplace = True) # displaydata.head() Output:As show in the output images, A new index label named level_0 has been generated.Before reset –After reset – Example #2: Operation on Multi level IndexIn this example, 2 columns(First name and Gender) are added to the index column and later one level is removed by using reset_index() method. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # setting first name as index columndata.set_index(["First Name", "Gender"], inplace = True, append = True, drop = True) # resetting indexdata.reset_index(level = 2, inplace = True, col_level = 1) # displaydata.head() Output:As shown in the output image, The gender column in the index column was replaced as it’s level was 2. Before reset –After reset – Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Sep, 2018" }, { "code": null, "e": 266, "s": 52, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 418, "s": 266, "text": "Pandas reset_index() is a method to reset index of a Data Frame. reset_index() method sets a list of integer ranging from 0 to length of data as index." }, { "code": null, "e": 511, "s": 418, "text": "Syntax:DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”)" }, { "code": null, "e": 873, "s": 511, "text": "Parameters:level: int, string or a list to select and remove passed column from index.drop: Boolean value, Adds the replaced index column to the data if False.inplace: Boolean value, make changes in the original data frame itself if True.col_level: Select in which column level to insert the labels.col_fill: Object, to determine how the other levels are named." }, { "code": null, "e": 896, "s": 873, "text": "Return type: DataFrame" }, { "code": null, "e": 1112, "s": 896, "text": "To download the CSV file used, Click Here.Example #1: Resetting indexIn this example, to reset index, First name column have been set as index column first and then using reset index a new index have been generated." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # setting first name as index columndata.set_index([\"First Name\"], inplace = True, append = True, drop = True) # resetting indexdata.reset_index(inplace = True) # displaydata.head()", "e": 1436, "s": 1112, "text": null }, { "code": null, "e": 1552, "s": 1436, "text": "Output:As show in the output images, A new index label named level_0 has been generated.Before reset –After reset –" }, { "code": null, "e": 1738, "s": 1554, "text": "Example #2: Operation on Multi level IndexIn this example, 2 columns(First name and Gender) are added to the index column and later one level is removed by using reset_index() method." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # setting first name as index columndata.set_index([\"First Name\", \"Gender\"], inplace = True, append = True, drop = True) # resetting indexdata.reset_index(level = 2, inplace = True, col_level = 1) # displaydata.head()", "e": 2107, "s": 1738, "text": null }, { "code": null, "e": 2216, "s": 2107, "text": "Output:As shown in the output image, The gender column in the index column was replaced as it’s level was 2." }, { "code": null, "e": 2244, "s": 2216, "text": "Before reset –After reset –" }, { "code": null, "e": 2268, "s": 2244, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2300, "s": 2268, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2314, "s": 2300, "text": "Python-pandas" }, { "code": null, "e": 2321, "s": 2314, "text": "Python" }, { "code": null, "e": 2419, "s": 2321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2437, "s": 2419, "text": "Python Dictionary" }, { "code": null, "e": 2479, "s": 2437, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2501, "s": 2479, "text": "Enumerate() in Python" }, { "code": null, "e": 2533, "s": 2501, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2562, "s": 2533, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2592, "s": 2562, "text": "Iterate over a list in Python" }, { "code": null, "e": 2619, "s": 2592, "text": "Python Classes and Objects" }, { "code": null, "e": 2655, "s": 2619, "text": "Convert integer to string in Python" }, { "code": null, "e": 2686, "s": 2655, "text": "Python | os.path.join() method" } ]
Python | Merge two text files
19 Jul, 2019 Given two text files, the task is to merge the data and store in a new text file. Let’s see how can we do this task using Python. To merge two files in Python, we are asking user to enter the name of the primary and second file and make a new file to put the unified content of the two data into this freshly created file. In order to do this task, we have to import shutil & pathlib libraries. You can install the libraries using this command – pip install shutil pip install pathlib Also, place the two text files on the Desktop. First text file: Second text file: Below is the Python implementation – import shutilfrom pathlib import Path firstfile = Path(r'C:\Users\Sohom\Desktop\GFG.txt')secondfile = Path(r'C:\Users\Sohom\Desktop\CSE.txt') newfile = input("Enter the name of the new file: ")print()print("The merged content of the 2 files will be in", newfile) with open(newfile, "wb") as wfd: for f in [firstfile, secondfile]: with open(f, "rb") as fd: shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10) print("\nThe content is merged successfully.!")print("Do you want to view it ? (y / n): ") check = input()if check == 'n': exit()else: print() c = open(newfile, "r") print(c.read()) c.close() Output: The updated merged text file: python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2019" }, { "code": null, "e": 158, "s": 28, "text": "Given two text files, the task is to merge the data and store in a new text file. Let’s see how can we do this task using Python." }, { "code": null, "e": 351, "s": 158, "text": "To merge two files in Python, we are asking user to enter the name of the primary and second file and make a new file to put the unified content of the two data into this freshly created file." }, { "code": null, "e": 474, "s": 351, "text": "In order to do this task, we have to import shutil & pathlib libraries. You can install the libraries using this command –" }, { "code": null, "e": 513, "s": 474, "text": "pip install shutil\npip install pathlib" }, { "code": null, "e": 560, "s": 513, "text": "Also, place the two text files on the Desktop." }, { "code": null, "e": 577, "s": 560, "text": "First text file:" }, { "code": null, "e": 595, "s": 577, "text": "Second text file:" }, { "code": null, "e": 632, "s": 595, "text": "Below is the Python implementation –" }, { "code": "import shutilfrom pathlib import Path firstfile = Path(r'C:\\Users\\Sohom\\Desktop\\GFG.txt')secondfile = Path(r'C:\\Users\\Sohom\\Desktop\\CSE.txt') newfile = input(\"Enter the name of the new file: \")print()print(\"The merged content of the 2 files will be in\", newfile) with open(newfile, \"wb\") as wfd: for f in [firstfile, secondfile]: with open(f, \"rb\") as fd: shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10) print(\"\\nThe content is merged successfully.!\")print(\"Do you want to view it ? (y / n): \") check = input()if check == 'n': exit()else: print() c = open(newfile, \"r\") print(c.read()) c.close()", "e": 1270, "s": 632, "text": null }, { "code": null, "e": 1278, "s": 1270, "text": "Output:" }, { "code": null, "e": 1308, "s": 1278, "text": "The updated merged text file:" }, { "code": null, "e": 1323, "s": 1308, "text": "python-utility" }, { "code": null, "e": 1330, "s": 1323, "text": "Python" }, { "code": null, "e": 1346, "s": 1330, "text": "Python Programs" }, { "code": null, "e": 1444, "s": 1346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1462, "s": 1444, "text": "Python Dictionary" }, { "code": null, "e": 1504, "s": 1462, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1526, "s": 1504, "text": "Enumerate() in Python" }, { "code": null, "e": 1552, "s": 1526, "text": "Python String | replace()" }, { "code": null, "e": 1584, "s": 1552, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1627, "s": 1584, "text": "Python program to convert a list to string" }, { "code": null, "e": 1649, "s": 1627, "text": "Defaultdict in Python" }, { "code": null, "e": 1688, "s": 1649, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1726, "s": 1688, "text": "Python | Convert a list to dictionary" } ]
Python - Get the Index of first element greater than K
The values of items in a python list are not necessarily in any sorted order. More over there may be situation when we are interested only in certain values greater than a specific value. In this article we will see how we can get the Using enumeration we get both the index and value of the elements in the list. Then we apply the greater than condition to get only the first element where the condition is satisfied. The next function goes through each list element one by one. Live Demo List = [21,10,24,40.5,11] print("Given list: " + str(List)) #Using next() + enumerate() result = next(k for k, value in enumerate(List) if value > 25)print("Index is: ",result) Running the above code gives us the following result Given list: [21, 10, 24, 40.5, 11] Index is: 3 In the next example we take a lambda function to compare the given value with value at each index and then filter out those which satisfy the required condition. From the list of elements satisfying the required condition, we choose the first element at index 0 for our answer. Live Demo List = [21,10,24,40.5,11] print("Given list: " + str(List)) #Using filter() + lambda result = list(filter(lambda k: k > 25, List))[0] print("Index is: ",List.index(result)) Running the above code gives us the following result Given list: [21, 10, 24, 40.5, 11] Index is: 3 In the next example we take a similar approach but use map instead of filter. The map function is used to loop through each of the elements. Whenever the condition becomes true that index is captured. Live Demo List = [21,10,24,40.5,11] print("Given list: " + str(List)) result = list(map(lambda k: k > 25, List)).index(True) print("Index is: ",(result)) Running the above code gives us the following result Given list: [21, 10, 24, 40.5, 11] Index is: 3
[ { "code": null, "e": 1422, "s": 1187, "text": "The values of items in a python list are not necessarily in any sorted order. More over there may be situation when we are interested only in certain values greater than a specific value. In this article we will see how we can get the" }, { "code": null, "e": 1667, "s": 1422, "text": "Using enumeration we get both the index and value of the elements in the list. Then we apply the greater than condition to get only the first element where the condition is satisfied. The next function goes through each list element one by one." }, { "code": null, "e": 1678, "s": 1667, "text": " Live Demo" }, { "code": null, "e": 1855, "s": 1678, "text": "List = [21,10,24,40.5,11]\nprint(\"Given list: \" + str(List))\n#Using next() + enumerate()\nresult = next(k for k, value in enumerate(List)\nif value > 25)print(\"Index is: \",result)" }, { "code": null, "e": 1908, "s": 1855, "text": "Running the above code gives us the following result" }, { "code": null, "e": 1955, "s": 1908, "text": "Given list: [21, 10, 24, 40.5, 11]\nIndex is: 3" }, { "code": null, "e": 2233, "s": 1955, "text": "In the next example we take a lambda function to compare the given value with value at each index and then filter out those which satisfy the required condition. From the list of elements satisfying the required condition, we choose the first element at index 0 for our answer." }, { "code": null, "e": 2244, "s": 2233, "text": " Live Demo" }, { "code": null, "e": 2417, "s": 2244, "text": "List = [21,10,24,40.5,11]\nprint(\"Given list: \" + str(List))\n#Using filter() + lambda\nresult = list(filter(lambda k: k > 25, List))[0]\nprint(\"Index is: \",List.index(result))" }, { "code": null, "e": 2470, "s": 2417, "text": "Running the above code gives us the following result" }, { "code": null, "e": 2517, "s": 2470, "text": "Given list: [21, 10, 24, 40.5, 11]\nIndex is: 3" }, { "code": null, "e": 2718, "s": 2517, "text": "In the next example we take a similar approach but use map instead of filter. The map function is used to loop through each of the elements. Whenever the condition becomes true that index is captured." }, { "code": null, "e": 2729, "s": 2718, "text": " Live Demo" }, { "code": null, "e": 2873, "s": 2729, "text": "List = [21,10,24,40.5,11]\nprint(\"Given list: \" + str(List))\nresult = list(map(lambda k: k > 25, List)).index(True)\nprint(\"Index is: \",(result))" }, { "code": null, "e": 2926, "s": 2873, "text": "Running the above code gives us the following result" }, { "code": null, "e": 2973, "s": 2926, "text": "Given list: [21, 10, 24, 40.5, 11]\nIndex is: 3" } ]
Output of Java Programs | Set 37 (If-else)
25 Sep, 2017 Prerequisite: if else, for loops 1. What will be the output for the following program? publicclass Test {public static void main(String[] args) { for (;;) System.out.println("GEEKS"); }} Options:1.GEEKS2.Compile time error3.Run time Exception4.GEEKS (Infinitely) The answer is option (4) Explanation: In the above example, we are using for loop. In for loop if we did not provide any initialization, condition-check and increment/decrement part then it will go to infinite loop if we did not provide any condition in statement. 2. What will be the output for the following program? class Test {public static void main(String[] args) { for (int i = 0; i < 3 System.out.println("GEEKS"); }} Options:1.GEEKS GEEKS GEEKS2.Compile time error3.GEEKS (Infinitely)4.No output The answer is option (3) Explanation: When we are not taking any statement in increment/decrement section therefore overtime it does not increment/decrement the value of I and the condition always true. That’s why it results into GEEKS (Infinitely). 3. What will be the output for the following program? class Test {public static void main(String[] args) { boolean b = true; if (b = false) { System.out.println("HELLO"); } else { System.out.println("BYE"); } }} Option:1.HELLO2.BYE3.Compile time error: re- initialization4.No output The answer is option (2) Explanation : In the condition of if statement, we assigning are false to b which return a boolean value which is false. Therefore the control goes to the else part and the output is BYE. 4. What will be the output for the following program? publicclass Test {public static void main(String[] args) { int a = 10, b = 20; if (a < b) { if (a > b) { System.out.println("HELLO GEEKS"); } else { System.out.println("WELCOME"); } } }} Option:1.HELLO GEEKS2.WELCOME3.Compile time error4.HELLO GEEKS WELCOME The answer is option (2) Explanation: Here we are defining nested if and a single else part. In java, there is no dangling else problem in java. Every else is mapped to the nearest if statement. Therefore the else part belongs to if(x>y) in the above program, which returns false that’s why control goes to else part and the output is WELCOME. 5. What will be the output for the following program? class Test {public static void main(String[] args) { for (int i = 0;; i++) { System.out.println("HIII"); } System.out.println("BYE"); }} Options:1. HIII2. HIII(infinitely)3. BYE4. Compile time error The answer is option (4) Explanation: In the above for loop it will go for infinite loop and the above program does not give any chance to the next lines of the program. That’s why compiler will give compile time error saying error: unreachable statement. This article is contributed by Bishal Kumar Dubey. 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. Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of C++ programs | Set 50 Runtime Errors C++ Programming Multiple Choice Questions Different ways to copy a string in C/C++ Output of C Programs | Set 2 Output of C++ Program | Set 1 Output of Python Program | Set 1 Output of C++ programs | Set 47 (Pointers) Output of C programs | Set 59 (Loops and Control Statements) Output of C Programs | Set 3
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Sep, 2017" }, { "code": null, "e": 85, "s": 52, "text": "Prerequisite: if else, for loops" }, { "code": null, "e": 139, "s": 85, "text": "1. What will be the output for the following program?" }, { "code": "publicclass Test {public static void main(String[] args) { for (;;) System.out.println(\"GEEKS\"); }}", "e": 266, "s": 139, "text": null }, { "code": null, "e": 342, "s": 266, "text": "Options:1.GEEKS2.Compile time error3.Run time Exception4.GEEKS (Infinitely)" }, { "code": null, "e": 367, "s": 342, "text": "The answer is option (4)" }, { "code": null, "e": 607, "s": 367, "text": "Explanation: In the above example, we are using for loop. In for loop if we did not provide any initialization, condition-check and increment/decrement part then it will go to infinite loop if we did not provide any condition in statement." }, { "code": null, "e": 661, "s": 607, "text": "2. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { for (int i = 0; i < 3 System.out.println(\"GEEKS\"); }}", "e": 795, "s": 661, "text": null }, { "code": null, "e": 874, "s": 795, "text": "Options:1.GEEKS GEEKS GEEKS2.Compile time error3.GEEKS (Infinitely)4.No output" }, { "code": null, "e": 900, "s": 874, "text": " The answer is option (3)" }, { "code": null, "e": 1125, "s": 900, "text": "Explanation: When we are not taking any statement in increment/decrement section therefore overtime it does not increment/decrement the value of I and the condition always true. That’s why it results into GEEKS (Infinitely)." }, { "code": null, "e": 1179, "s": 1125, "text": "3. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { boolean b = true; if (b = false) { System.out.println(\"HELLO\"); } else { System.out.println(\"BYE\"); } }}", "e": 1396, "s": 1179, "text": null }, { "code": null, "e": 1467, "s": 1396, "text": "Option:1.HELLO2.BYE3.Compile time error: re- initialization4.No output" }, { "code": null, "e": 1492, "s": 1467, "text": "The answer is option (2)" }, { "code": null, "e": 1680, "s": 1492, "text": "Explanation : In the condition of if statement, we assigning are false to b which return a boolean value which is false. Therefore the control goes to the else part and the output is BYE." }, { "code": null, "e": 1734, "s": 1680, "text": "4. What will be the output for the following program?" }, { "code": "publicclass Test {public static void main(String[] args) { int a = 10, b = 20; if (a < b) { if (a > b) { System.out.println(\"HELLO GEEKS\"); } else { System.out.println(\"WELCOME\"); } } }}", "e": 2014, "s": 1734, "text": null }, { "code": null, "e": 2085, "s": 2014, "text": "Option:1.HELLO GEEKS2.WELCOME3.Compile time error4.HELLO GEEKS WELCOME" }, { "code": null, "e": 2111, "s": 2085, "text": " The answer is option (2)" }, { "code": null, "e": 2430, "s": 2111, "text": "Explanation: Here we are defining nested if and a single else part. In java, there is no dangling else problem in java. Every else is mapped to the nearest if statement. Therefore the else part belongs to if(x>y) in the above program, which returns false that’s why control goes to else part and the output is WELCOME." }, { "code": null, "e": 2484, "s": 2430, "text": "5. What will be the output for the following program?" }, { "code": "class Test {public static void main(String[] args) { for (int i = 0;; i++) { System.out.println(\"HIII\"); } System.out.println(\"BYE\"); }}", "e": 2662, "s": 2484, "text": null }, { "code": null, "e": 2724, "s": 2662, "text": "Options:1. HIII2. HIII(infinitely)3. BYE4. Compile time error" }, { "code": null, "e": 2750, "s": 2724, "text": " The answer is option (4)" }, { "code": null, "e": 2981, "s": 2750, "text": "Explanation: In the above for loop it will go for infinite loop and the above program does not give any chance to the next lines of the program. That’s why compiler will give compile time error saying error: unreachable statement." }, { "code": null, "e": 3287, "s": 2981, "text": "This article is contributed by Bishal Kumar Dubey. 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." }, { "code": null, "e": 3412, "s": 3287, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3424, "s": 3412, "text": "Java-Output" }, { "code": null, "e": 3439, "s": 3424, "text": "Program Output" }, { "code": null, "e": 3537, "s": 3439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3569, "s": 3537, "text": "Output of C++ programs | Set 50" }, { "code": null, "e": 3584, "s": 3569, "text": "Runtime Errors" }, { "code": null, "e": 3626, "s": 3584, "text": "C++ Programming Multiple Choice Questions" }, { "code": null, "e": 3667, "s": 3626, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 3696, "s": 3667, "text": "Output of C Programs | Set 2" }, { "code": null, "e": 3726, "s": 3696, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 3759, "s": 3726, "text": "Output of Python Program | Set 1" }, { "code": null, "e": 3802, "s": 3759, "text": "Output of C++ programs | Set 47 (Pointers)" }, { "code": null, "e": 3863, "s": 3802, "text": "Output of C programs | Set 59 (Loops and Control Statements)" } ]
Storage Management
19 Jun, 2019 Storage Management is defined as it refers to the management of the data storage equipment’s that are used to store the user/computer generated data. Hence it is a tool or set of processes used by an administrator to keep your data and storage equipment’s safe. Storage management is a process for users to optimize the use of storage devices and to protect the integrity of data for any media on which it resides and the category of storage management generally contain the different type of subcategories covering aspects such as security, virtualization and more, as well as different types of provisioning or automation, which is generally made up the entire storage management software market. Storage management key attributes:Storage management has some key attribute which is generally used to manage the storage capacity of the system. These are given below: 1. Performance 2. Reliability 3. Recoverability 4. Capacity Feature of Storage management:There is some feature of storage management which is provided for storage capacity. These are given below: Storage management is a process that is used to optimize the use of storage devices.Storage management must be allocated and managed as a resource in order to truly benefit a corporation.Storage management is generally a basic system component of information systems.It is used to improve the performance of their data storage resources. Storage management is a process that is used to optimize the use of storage devices. Storage management must be allocated and managed as a resource in order to truly benefit a corporation. Storage management is generally a basic system component of information systems. It is used to improve the performance of their data storage resources. Advantage of storage management:There are some advantage of storage management which are given below: It is very simple to managed a storage capacity. It is generally take a less time. It is improve the performance of system. In virtualization and automation technologies can help an organization improve its agility. Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Electronic Mail Advantages and Disadvantages of OOP Communication Models in IoT (Internet of Things ) Cloud Computing Analog to Digital Conversion Hypervisor Characteristics of Cloud Computing Introduction to Deep Learning array::size() in C++ STL Bubble Sort algorithm using JavaScript
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jun, 2019" }, { "code": null, "e": 316, "s": 54, "text": "Storage Management is defined as it refers to the management of the data storage equipment’s that are used to store the user/computer generated data. Hence it is a tool or set of processes used by an administrator to keep your data and storage equipment’s safe." }, { "code": null, "e": 753, "s": 316, "text": "Storage management is a process for users to optimize the use of storage devices and to protect the integrity of data for any media on which it resides and the category of storage management generally contain the different type of subcategories covering aspects such as security, virtualization and more, as well as different types of provisioning or automation, which is generally made up the entire storage management software market." }, { "code": null, "e": 922, "s": 753, "text": "Storage management key attributes:Storage management has some key attribute which is generally used to manage the storage capacity of the system. These are given below:" }, { "code": null, "e": 983, "s": 922, "text": "1. Performance\n2. Reliability\n3. Recoverability\n4. Capacity " }, { "code": null, "e": 1120, "s": 983, "text": "Feature of Storage management:There is some feature of storage management which is provided for storage capacity. These are given below:" }, { "code": null, "e": 1458, "s": 1120, "text": "Storage management is a process that is used to optimize the use of storage devices.Storage management must be allocated and managed as a resource in order to truly benefit a corporation.Storage management is generally a basic system component of information systems.It is used to improve the performance of their data storage resources." }, { "code": null, "e": 1543, "s": 1458, "text": "Storage management is a process that is used to optimize the use of storage devices." }, { "code": null, "e": 1647, "s": 1543, "text": "Storage management must be allocated and managed as a resource in order to truly benefit a corporation." }, { "code": null, "e": 1728, "s": 1647, "text": "Storage management is generally a basic system component of information systems." }, { "code": null, "e": 1799, "s": 1728, "text": "It is used to improve the performance of their data storage resources." }, { "code": null, "e": 1901, "s": 1799, "text": "Advantage of storage management:There are some advantage of storage management which are given below:" }, { "code": null, "e": 1950, "s": 1901, "text": "It is very simple to managed a storage capacity." }, { "code": null, "e": 1984, "s": 1950, "text": "It is generally take a less time." }, { "code": null, "e": 2025, "s": 1984, "text": "It is improve the performance of system." }, { "code": null, "e": 2117, "s": 2025, "text": "In virtualization and automation technologies can help an organization improve its agility." }, { "code": null, "e": 2122, "s": 2117, "text": "Misc" }, { "code": null, "e": 2127, "s": 2122, "text": "Misc" }, { "code": null, "e": 2132, "s": 2127, "text": "Misc" }, { "code": null, "e": 2230, "s": 2132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2262, "s": 2230, "text": "Introduction to Electronic Mail" }, { "code": null, "e": 2298, "s": 2262, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 2348, "s": 2298, "text": "Communication Models in IoT (Internet of Things )" }, { "code": null, "e": 2364, "s": 2348, "text": "Cloud Computing" }, { "code": null, "e": 2393, "s": 2364, "text": "Analog to Digital Conversion" }, { "code": null, "e": 2404, "s": 2393, "text": "Hypervisor" }, { "code": null, "e": 2439, "s": 2404, "text": "Characteristics of Cloud Computing" }, { "code": null, "e": 2469, "s": 2439, "text": "Introduction to Deep Learning" }, { "code": null, "e": 2494, "s": 2469, "text": "array::size() in C++ STL" } ]
Java Program to Convert Binary to Hexadecimal
20 May, 2021 The Hexadecimal number system as the name suggests comprises 16 entities. These 16 entities consist of 10 digits, 0-9 representing the first 10 numbers of the hexadecimal system as well. For the remaining 6 numbers, we use English alphabets ranging from A through F to represent the numbers 10 to 15. It should be noted that the lowest number in the hexadecimal system is 0 with the highest being 15 represented by F. A hexadecimal number can be derived from a binary number by clubbing 4 digits to constitute a single character of the hexadecimal number. Example: Input: 11011111 Output: DF Input: 10001101 Output: 8D In the above example, the binary number 10001101 can be broken down into chunks of 4 bits such as 1000 and 1101 which act as 2 characters for the corresponding hexadecimal number. The resultant hexadecimal number would be 8D where every character is determined by calculating its corresponding value in the decimal system and replacing it with an alphabet if it is a two-digit number in this case D which represents 13. The hexadecimal system is also referred to as base-16. For the conversion of binary to hexadecimal, we are going to use the following two approaches : Using the toHexString() builtin java methodRepeatedly getting the remainder and dividing the converted decimal number by 16 Using the toHexString() builtin java method Repeatedly getting the remainder and dividing the converted decimal number by 16 Approach 1: Using this approach, we first convert the binary number to a decimal number which is stored as an Integer. Then, we simply use the toHexString() method of java to generate the desired output string. Syntax : public static String toHexString(int num) Parameter: num – This parameter specifies the number which is to be converted to a Hexadecimal string. The data-type is int. Return Value: The function returns a string representation of the int argument as an unsigned integer in base 16. Algorithm : Convert the binary number to a decimal number.To convert the binary number to a decimal number, first, extract each digit using by getting the remainder by dividing by 10.Next, multiply this digit with increasing powers of 2.Keep on dividing the original binary number by 10 to eliminate the last digit in each iteration.After having gotten the decimal number, just use the toHexString() method to get the desired output. Convert the binary number to a decimal number. To convert the binary number to a decimal number, first, extract each digit using by getting the remainder by dividing by 10. Next, multiply this digit with increasing powers of 2. Keep on dividing the original binary number by 10 to eliminate the last digit in each iteration. After having gotten the decimal number, just use the toHexString() method to get the desired output. Example: Java // Java program to convert binary to hexadecimal class GFG { // method to convert binary to decimal int binaryToDecimal(long binary) { // variable to store the converted // binary number int decimalNumber = 0, i = 0; // loop to extract the digits of the binary while (binary > 0) { // extracting the digits by getting // remainder on dividing by 10 and // multiplying by increasing integral // powers of 2 decimalNumber += Math.pow(2, i++) * (binary % 10); // updating the binary by eliminating // the last digit on division by 10 binary /= 10; } // returning the decimal number return decimalNumber; } // method to convert decimal to hexadecimal String decimalToHex(long binary) { // variable to store the output of the // binaryToDecimal() method int decimalNumber = binaryToDecimal(binary); // converting the integer to the desired // hex string using toHexString() method String hexNumber = Integer.toHexString(decimalNumber); // converting the string to uppercase // for uniformity hexNumber = hexNumber.toUpperCase(); // returning the final hex string return hexNumber; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); long num = 10011110; // calling and printing the output // of decimalToHex() method System.out.println("Inputted number : " +num); System.out.println(ob.decimalToHex(10011110)); }} Inputted number : 10011110 9E Approach 2: Under the second approach, we again first convert the binary number to a decimal number. Then we continuously divide and get the remainder of this decimal number to get the single character for each set of 4 bits we can find in the original binary number. Algorithm: Convert the binary to a decimal using steps 2-4 in the above algorithm.Next, run a while loop with the terminating condition that the decimal number becomes 0 and the updating condition that the decimal number is divided by 16 in each iteration.In each iteration get the remainder by dividing the number by 16.Constitute a new String and keep on adding characters which are the remaining on dividing by 16.If the remainder is greater than or equal to 10 replace it with alphabets A-F depending on the remainder. Convert the binary to a decimal using steps 2-4 in the above algorithm. Next, run a while loop with the terminating condition that the decimal number becomes 0 and the updating condition that the decimal number is divided by 16 in each iteration. In each iteration get the remainder by dividing the number by 16. Constitute a new String and keep on adding characters which are the remaining on dividing by 16. If the remainder is greater than or equal to 10 replace it with alphabets A-F depending on the remainder. Example: Java // Java program to convert binary to hexadecimal class GFG { // method to convert binary to decimal int binaryToDecimal(long binary) { // variable to store the converted binary int decimalNumber = 0, i = 0; // loop to extract digits of the binary while (binary > 0) { // extracting each digit of the binary // by getting the remainder of division // by 10 and multiplying it by // increasing integral powers of 2 decimalNumber += Math.pow(2, i++) * (binary % 10); // update condition of dividing the // binary by 10 binary /= 10; } // returning the decimal return decimalNumber; } // method to convert decimal to hex String decimalToHex(long binary) { // variable to store the output of // binaryToDecimal() method int decimalNumber = binaryToDecimal(binary); // character array to represent double // digit remainders char arr[] = { 'A', 'B', 'C', 'D', 'E', 'F' }; // variable to store the remainder on // division by 16 int remainder, i = 0; // declaring the string that stores the // final hex string String hexNumber = ""; // loop to convert decimal to hex while (decimalNumber != 0) { // calculating the remainder of decimal // by dividing by 16 remainder = decimalNumber % 16; // checking if the remainder is >= 10 if (remainder >= 10) // replacing with the corresponding // alphabet from the array hexNumber = arr[remainder - 10] + hexNumber; else hexNumber = remainder + hexNumber; // update condition of dividing the // number by 16 decimalNumber /= 16; } // returning the hex string return hexNumber; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); long num =11000011; // printing and calling the // decimalToHex() method System.out.println("Input : "+num); System.out.println("Output : " +ob.decimalToHex(num)); }} Input : 11000011 Output : C3 Code_Mech Picked Java Java Programs 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 Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 53, "s": 25, "text": "\n20 May, 2021" }, { "code": null, "e": 609, "s": 53, "text": "The Hexadecimal number system as the name suggests comprises 16 entities. These 16 entities consist of 10 digits, 0-9 representing the first 10 numbers of the hexadecimal system as well. For the remaining 6 numbers, we use English alphabets ranging from A through F to represent the numbers 10 to 15. It should be noted that the lowest number in the hexadecimal system is 0 with the highest being 15 represented by F. A hexadecimal number can be derived from a binary number by clubbing 4 digits to constitute a single character of the hexadecimal number." }, { "code": null, "e": 618, "s": 609, "text": "Example:" }, { "code": null, "e": 674, "s": 618, "text": "Input: 11011111\nOutput: DF\n \nInput: 10001101\nOutput: 8D" }, { "code": null, "e": 854, "s": 674, "text": "In the above example, the binary number 10001101 can be broken down into chunks of 4 bits such as 1000 and 1101 which act as 2 characters for the corresponding hexadecimal number." }, { "code": null, "e": 1149, "s": 854, "text": "The resultant hexadecimal number would be 8D where every character is determined by calculating its corresponding value in the decimal system and replacing it with an alphabet if it is a two-digit number in this case D which represents 13. The hexadecimal system is also referred to as base-16." }, { "code": null, "e": 1245, "s": 1149, "text": "For the conversion of binary to hexadecimal, we are going to use the following two approaches :" }, { "code": null, "e": 1369, "s": 1245, "text": "Using the toHexString() builtin java methodRepeatedly getting the remainder and dividing the converted decimal number by 16" }, { "code": null, "e": 1413, "s": 1369, "text": "Using the toHexString() builtin java method" }, { "code": null, "e": 1494, "s": 1413, "text": "Repeatedly getting the remainder and dividing the converted decimal number by 16" }, { "code": null, "e": 1506, "s": 1494, "text": "Approach 1:" }, { "code": null, "e": 1705, "s": 1506, "text": "Using this approach, we first convert the binary number to a decimal number which is stored as an Integer. Then, we simply use the toHexString() method of java to generate the desired output string." }, { "code": null, "e": 1714, "s": 1705, "text": "Syntax :" }, { "code": null, "e": 1756, "s": 1714, "text": "public static String toHexString(int num)" }, { "code": null, "e": 1767, "s": 1756, "text": "Parameter:" }, { "code": null, "e": 1881, "s": 1767, "text": "num – This parameter specifies the number which is to be converted to a Hexadecimal string. The data-type is int." }, { "code": null, "e": 1995, "s": 1881, "text": "Return Value: The function returns a string representation of the int argument as an unsigned integer in base 16." }, { "code": null, "e": 2007, "s": 1995, "text": "Algorithm :" }, { "code": null, "e": 2429, "s": 2007, "text": "Convert the binary number to a decimal number.To convert the binary number to a decimal number, first, extract each digit using by getting the remainder by dividing by 10.Next, multiply this digit with increasing powers of 2.Keep on dividing the original binary number by 10 to eliminate the last digit in each iteration.After having gotten the decimal number, just use the toHexString() method to get the desired output." }, { "code": null, "e": 2476, "s": 2429, "text": "Convert the binary number to a decimal number." }, { "code": null, "e": 2602, "s": 2476, "text": "To convert the binary number to a decimal number, first, extract each digit using by getting the remainder by dividing by 10." }, { "code": null, "e": 2657, "s": 2602, "text": "Next, multiply this digit with increasing powers of 2." }, { "code": null, "e": 2754, "s": 2657, "text": "Keep on dividing the original binary number by 10 to eliminate the last digit in each iteration." }, { "code": null, "e": 2855, "s": 2754, "text": "After having gotten the decimal number, just use the toHexString() method to get the desired output." }, { "code": null, "e": 2864, "s": 2855, "text": "Example:" }, { "code": null, "e": 2869, "s": 2864, "text": "Java" }, { "code": "// Java program to convert binary to hexadecimal class GFG { // method to convert binary to decimal int binaryToDecimal(long binary) { // variable to store the converted // binary number int decimalNumber = 0, i = 0; // loop to extract the digits of the binary while (binary > 0) { // extracting the digits by getting // remainder on dividing by 10 and // multiplying by increasing integral // powers of 2 decimalNumber += Math.pow(2, i++) * (binary % 10); // updating the binary by eliminating // the last digit on division by 10 binary /= 10; } // returning the decimal number return decimalNumber; } // method to convert decimal to hexadecimal String decimalToHex(long binary) { // variable to store the output of the // binaryToDecimal() method int decimalNumber = binaryToDecimal(binary); // converting the integer to the desired // hex string using toHexString() method String hexNumber = Integer.toHexString(decimalNumber); // converting the string to uppercase // for uniformity hexNumber = hexNumber.toUpperCase(); // returning the final hex string return hexNumber; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); long num = 10011110; // calling and printing the output // of decimalToHex() method System.out.println(\"Inputted number : \" +num); System.out.println(ob.decimalToHex(10011110)); }}", "e": 4583, "s": 2869, "text": null }, { "code": null, "e": 4613, "s": 4583, "text": "Inputted number : 10011110\n9E" }, { "code": null, "e": 4626, "s": 4613, "text": "Approach 2: " }, { "code": null, "e": 4715, "s": 4626, "text": "Under the second approach, we again first convert the binary number to a decimal number." }, { "code": null, "e": 4882, "s": 4715, "text": "Then we continuously divide and get the remainder of this decimal number to get the single character for each set of 4 bits we can find in the original binary number." }, { "code": null, "e": 4894, "s": 4882, "text": "Algorithm: " }, { "code": null, "e": 5406, "s": 4894, "text": "Convert the binary to a decimal using steps 2-4 in the above algorithm.Next, run a while loop with the terminating condition that the decimal number becomes 0 and the updating condition that the decimal number is divided by 16 in each iteration.In each iteration get the remainder by dividing the number by 16.Constitute a new String and keep on adding characters which are the remaining on dividing by 16.If the remainder is greater than or equal to 10 replace it with alphabets A-F depending on the remainder." }, { "code": null, "e": 5478, "s": 5406, "text": "Convert the binary to a decimal using steps 2-4 in the above algorithm." }, { "code": null, "e": 5653, "s": 5478, "text": "Next, run a while loop with the terminating condition that the decimal number becomes 0 and the updating condition that the decimal number is divided by 16 in each iteration." }, { "code": null, "e": 5719, "s": 5653, "text": "In each iteration get the remainder by dividing the number by 16." }, { "code": null, "e": 5816, "s": 5719, "text": "Constitute a new String and keep on adding characters which are the remaining on dividing by 16." }, { "code": null, "e": 5922, "s": 5816, "text": "If the remainder is greater than or equal to 10 replace it with alphabets A-F depending on the remainder." }, { "code": null, "e": 5932, "s": 5922, "text": "Example: " }, { "code": null, "e": 5937, "s": 5932, "text": "Java" }, { "code": "// Java program to convert binary to hexadecimal class GFG { // method to convert binary to decimal int binaryToDecimal(long binary) { // variable to store the converted binary int decimalNumber = 0, i = 0; // loop to extract digits of the binary while (binary > 0) { // extracting each digit of the binary // by getting the remainder of division // by 10 and multiplying it by // increasing integral powers of 2 decimalNumber += Math.pow(2, i++) * (binary % 10); // update condition of dividing the // binary by 10 binary /= 10; } // returning the decimal return decimalNumber; } // method to convert decimal to hex String decimalToHex(long binary) { // variable to store the output of // binaryToDecimal() method int decimalNumber = binaryToDecimal(binary); // character array to represent double // digit remainders char arr[] = { 'A', 'B', 'C', 'D', 'E', 'F' }; // variable to store the remainder on // division by 16 int remainder, i = 0; // declaring the string that stores the // final hex string String hexNumber = \"\"; // loop to convert decimal to hex while (decimalNumber != 0) { // calculating the remainder of decimal // by dividing by 16 remainder = decimalNumber % 16; // checking if the remainder is >= 10 if (remainder >= 10) // replacing with the corresponding // alphabet from the array hexNumber = arr[remainder - 10] + hexNumber; else hexNumber = remainder + hexNumber; // update condition of dividing the // number by 16 decimalNumber /= 16; } // returning the hex string return hexNumber; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); long num =11000011; // printing and calling the // decimalToHex() method System.out.println(\"Input : \"+num); System.out.println(\"Output : \" +ob.decimalToHex(num)); }}", "e": 8302, "s": 5937, "text": null }, { "code": null, "e": 8331, "s": 8302, "text": "Input : 11000011\nOutput : C3" }, { "code": null, "e": 8343, "s": 8333, "text": "Code_Mech" }, { "code": null, "e": 8350, "s": 8343, "text": "Picked" }, { "code": null, "e": 8355, "s": 8350, "text": "Java" }, { "code": null, "e": 8369, "s": 8355, "text": "Java Programs" }, { "code": null, "e": 8374, "s": 8369, "text": "Java" }, { "code": null, "e": 8472, "s": 8374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8523, "s": 8472, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 8554, "s": 8523, "text": "How to iterate any Map in Java" }, { "code": null, "e": 8573, "s": 8554, "text": "Interfaces in Java" }, { "code": null, "e": 8603, "s": 8573, "text": "HashMap in Java with Examples" }, { "code": null, "e": 8618, "s": 8603, "text": "Stream In Java" }, { "code": null, "e": 8646, "s": 8618, "text": "Initializing a List in Java" }, { "code": null, "e": 8672, "s": 8646, "text": "Java Programming Examples" }, { "code": null, "e": 8716, "s": 8672, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 8750, "s": 8716, "text": "Convert Double to Integer in Java" } ]
Minimum number of deletions to make a string palindrome
01 Jun, 2022 Given a string of size ‘n’. The task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome. Note: The order of characters should be maintained. Examples : Input : aebcbda Output : 2 Remove characters 'e' and 'd' Resultant string will be 'abcba' which is a palindromic string Input : geeksforgeeks Output : 8 A simple solution is to remove all subsequences one by one and check if the remaining string is palindrome or not. The time complexity of this solution is exponential. An efficient approach uses the concept of finding the length of the longest palindromic subsequence of a given sequence. Algorithm: 1. str is the given string. 2. n length of str 3. len be the length of the longest palindromic subsequence of str 4. minimum number of deletions min = n – len Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation to find// minimum number of deletions// to make a string palindromic#include <bits/stdc++.h>using namespace std; // Returns the length of// the longest palindromic// subsequence in 'str'int lps(string str){ int n = str.size(); // Create a table to store // results of subproblems int L[n][n]; // Strings of length 1 // are palindrome of length 1 for (int i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that // the lower diagonal values // of table are useless and // not filled in the process. // c1 is length of substring for (int cl = 2; cl <= n; cl++) { for (int i = 0; i < n - cl + 1; i++) { int j = i + cl - 1; if (str[i] == str[j] && cl == 2) L[i][j] = 2; else if (str[i] == str[j]) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = max(L[i][j - 1], L[i + 1][j]); } } // length of longest // palindromic subseq return L[0][n - 1];} // function to calculate// minimum number of deletionsint minimumNumberOfDeletions(string str){ int n = str.size(); // Find longest palindromic // subsequence int len = lps(str); // After removing characters // other than the lps, we // get palindrome. return (n - len);} // Driver Codeint main(){ string str = "geeksforgeeks"; cout << "Minimum number of deletions = " << minimumNumberOfDeletions(str); return 0;} // Java implementation to// find minimum number of// deletions to make a// string palindromicclass GFG{ // Returns the length of // the longest palindromic // subsequence in 'str' static int lps(String str) { int n = str.length(); // Create a table to store // results of subproblems int L[][] = new int[n][n]; // Strings of length 1 // are palindrome of length 1 for (int i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note // that the lower diagonal // values of table are useless // and not filled in the process. // c1 is length of substring for (int cl = 2; cl <= n; cl++) { for (int i = 0; i < n - cl + 1; i++) { int j = i + cl - 1; if (str.charAt(i) == str.charAt(j) && cl == 2) L[i][j] = 2; else if (str.charAt(i) == str.charAt(j)) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = Integer.max(L[i][j - 1], L[i + 1][j]); } } // length of longest // palindromic subsequence return L[0][n - 1]; } // function to calculate minimum // number of deletions static int minimumNumberOfDeletions(String str) { int n = str.length(); // Find longest palindromic // subsequence int len = lps(str); // After removing characters // other than the lps, we get // palindrome. return (n - len); } // Driver Code public static void main(String[] args) { String str = "geeksforgeeks"; System.out.println("Minimum number " + "of deletions = "+ minimumNumberOfDeletions(str)); }} // This code is contributed by Sumit Ghosh # Python3 implementation to find# minimum number of deletions# to make a string palindromic # Returns the length of# the longest palindromic# subsequence in 'str'def lps(str): n = len(str) # Create a table to store # results of subproblems L = [[0 for x in range(n)]for y in range(n)] # Strings of length 1 # are palindrome of length 1 for i in range(n): L[i][i] = 1 # Build the table. Note that # the lower diagonal values # of table are useless and # not filled in the process. # c1 is length of substring for cl in range( 2, n+1): for i in range(n - cl + 1): j = i + cl - 1 if (str[i] == str[j] and cl == 2): L[i][j] = 2 elif (str[i] == str[j]): L[i][j] = L[i + 1][j - 1] + 2 else: L[i][j] = max(L[i][j - 1],L[i + 1][j]) # length of longest # palindromic subseq return L[0][n - 1] # function to calculate# minimum number of deletionsdef minimumNumberOfDeletions( str): n = len(str) # Find longest palindromic # subsequence l = lps(str) # After removing characters # other than the lps, we # get palindrome. return (n - l) # Driver Codeif __name__ == "__main__": str = "geeksforgeeks" print( "Minimum number of deletions = " , minimumNumberOfDeletions(str)) // C# implementation to find// minimum number of deletions// to make a string palindromicusing System; class GFG{ // Returns the length of // the longest palindromic // subsequence in 'str' static int lps(String str) { int n = str.Length; // Create a table to store // results of subproblems int [,]L = new int[n, n]; // Strings of length 1 // are palindrome of length 1 for (int i = 0; i < n; i++) L[i, i] = 1; // Build the table. Note // that the lower diagonal // values of table are useless // and not filled in the process. // c1 is length of substring for (int cl = 2; cl <= n; cl++) { for (int i = 0; i < n - cl + 1; i++) { int j = i + cl - 1; if (str[i] == str[j] && cl == 2) L[i, j] = 2; else if (str[i] == str[j]) L[i, j] = L[i + 1, j - 1] + 2; else L[i, j] = Math.Max(L[i, j - 1], L[i + 1, j]); } } // length of longest // palindromic subsequence return L[0, n - 1]; } // function to calculate minimum // number of deletions static int minimumNumberOfDeletions(string str) { int n = str.Length; // Find longest palindromic // subsequence int len = lps(str); // After removing characters // other than the lps, we get // palindrome. return (n - len); } // Driver Code public static void Main() { string str = "geeksforgeeks"; Console.Write("Minimum number of" + " deletions = " + minimumNumberOfDeletions(str)); }} // This code is contributed by nitin mittal. <?php// PHP implementation to find// minimum number of deletions// to make a string palindromic // Returns the length of// the longest palindromic// subsequence in 'str'function lps($str){ $n = strlen($str); // Create a table to store // results of subproblems $L; // Strings of length 1 // are palindrome of length 1 for ($i = 0; $i < $n; $i++) $L[$i][$i] = 1; // Build the table. Note that // the lower diagonal values // of table are useless and // not filled in the process. // c1 is length of substring for ($cl = 2; $cl <= $n; $cl++) { for ( $i = 0; $i < $n -$cl + 1; $i++) { $j = $i + $cl - 1; if ($str[$i] == $str[$j] && $cl == 2) $L[$i][$j] = 2; else if ($str[$i] == $str[$j]) $L[$i][$j] = $L[$i + 1][$j - 1] + 2; else $L[$i][$j] = max($L[$i][$j - 1], $L[$i + 1][$j]); } } // length of longest // palindromic subseq return $L[0][$n - 1];} // function to calculate minimum// number of deletionsfunction minimumNumberOfDeletions($str){ $n = strlen($str); // Find longest // palindromic subsequence $len = lps($str); // After removing characters // other than the lps, we get // palindrome. return ($n - $len);} // Driver Code{ $str = "geeksforgeeks"; echo "Minimum number of deletions = ", minimumNumberOfDeletions($str); return 0;} // This code is contributed by nitin mittal.?> <script> // JavaScript implementation to // find minimum number of // deletions to make a // string palindromic // Returns the length of // the longest palindromic // subsequence in 'str' function lps(str) { let n = str.length; // Create a table to store // results of subproblems let L = new Array(n); for (let i = 0; i < n; i++) { L[i] = new Array(n); for (let j = 0; j < n; j++) { L[i][j] = 0; } } // Strings of length 1 // are palindrome of length 1 for (let i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note // that the lower diagonal // values of table are useless // and not filled in the process. // c1 is length of substring for (let cl = 2; cl <= n; cl++) { for (let i = 0; i < n - cl + 1; i++) { let j = i + cl - 1; if (str[i] == str[j] && cl == 2) L[i][j] = 2; else if (str[i] == str[j]) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = Math.max(L[i][j - 1], L[i + 1][j]); } } // length of longest // palindromic subsequence return L[0][n - 1]; } // function to calculate minimum // number of deletions function minimumNumberOfDeletions(str) { let n = str.length; // Find longest palindromic // subsequence let len = lps(str); // After removing characters // other than the lps, we get // palindrome. return (n - len); } let str = "geeksforgeeks"; document.write("Minimum number " + "of deletions = "+ minimumNumberOfDeletions(str)); </script> Minimum number of deletions = 8 Time Complexity: O(n2) Another Approach: Take two indexes first as ‘i’ and last as a ‘j’ now compare the character at the index ‘i’ and ‘j’ if characters are equal, then recursively call the function by incrementing ‘i’ by ‘1’ and decrementing ‘j’ by ‘1’ recursively call the function by incrementing ‘i’ by ‘1’ and decrementing ‘j’ by ‘1’ else recursively call the two functions, the first increment ‘i’ by ‘1’ keeping ‘j’ constant, second decrement ‘j’ by ‘1’ keeping ‘i’ constant.take a minimum of both and return by adding ‘1’ recursively call the two functions, the first increment ‘i’ by ‘1’ keeping ‘j’ constant, second decrement ‘j’ by ‘1’ keeping ‘i’ constant. take a minimum of both and return by adding ‘1’ Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for above approach#include <iostream>using namespace std; // Function to return minimum// Element between two valuesint min(int x, int y){ return (x < y) ? x : y;} // Utility function for calculating// Minimum element to deleteint utility_fun_for_del(string str, int i, int j){ if (i >= j) return 0; // Condition to compare characters if (str[i] == str[j]) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + min(utility_fun_for_del(str, i + 1, j), utility_fun_for_del(str, i, j - 1));} // Function to calculate the minimum// Element required to delete for// Making string palindromeint min_ele_del(string str){ // Utility function call return utility_fun_for_del(str, 0, str.length() - 1);} // Driver codeint main(){ string str = "abefbac"; cout << "Minimum element of deletions = " << min_ele_del(str) << endl; return 0;} // This code is contributed by MOHAMMAD MUDASSIR // Java program for above approachimport java.io.*;import java.util.*; class GFG{ // Function to return minimum// Element between two valuespublic static int min(int x, int y){ return (x < y) ? x : y;} // Utility function for calculating// Minimum element to deletepublic static int utility_fun_for_del(String str, int i, int j){ if (i >= j) return 0; // Condition to compare characters if (str.charAt(i) == str.charAt(j)) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + Math.min(utility_fun_for_del(str, i + 1, j), utility_fun_for_del(str, i, j - 1));} // Function to calculate the minimum// Element required to delete for// Making string palindromepublic static int min_ele_del(String str){ // Utility function call return utility_fun_for_del(str, 0, str.length() - 1);} // Driver Codepublic static void main(String[] args){ String str = "abefbac"; System.out.println("Minimum element of deletions = " + min_ele_del(str));}} // This code is contributed by divyeshrabadiya07 # Python3 program for above approach # Utility function for calculating# Minimum element to deletedef utility_fun_for_del(Str, i, j): if (i >= j): return 0 # Condition to compare characters if (Str[i] == Str[j]): # Recursive function call return utility_fun_for_del(Str, i + 1, j - 1) # Return value, incrementing by 1 # return minimum Element between two values return (1 + min(utility_fun_for_del(Str, i + 1, j), utility_fun_for_del(Str, i, j - 1))) # Function to calculate the minimum# Element required to delete for# Making string palindromedef min_ele_del(Str): # Utility function call return utility_fun_for_del(Str, 0, len(Str) - 1) # Driver codeStr = "abefbac" print("Minimum element of deletions =", min_ele_del(Str)) # This code is contributed by avanitrachhadiya2155 // C# program for above approachusing System;using System.Collections.Generic; class GFG{ // Function to return minimum// Element between two valuesstatic int min(int x, int y){ return (x < y) ? x : y;} // Utility function for calculating// Minimum element to deletestatic int utility_fun_for_del(string str, int i, int j){ if (i >= j) return 0; // Condition to compare characters if (str[i] == str[j]) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + Math.Min(utility_fun_for_del( str, i + 1, j), utility_fun_for_del( str, i, j - 1));} // Function to calculate the minimum// Element required to delete for// Making string palindromestatic int min_ele_del(string str){ // Utility function call return utility_fun_for_del(str, 0, str.Length - 1);} // Driver code static void Main(){ string str = "abefbac"; Console.WriteLine("Minimum element of " + "deletions = " + min_ele_del(str));}} // This code is contributed by divyesh072019 <script> // Javascript program for above approach // Function to return minimum // Element between two values function min(x, y) { return (x < y) ? x : y; } // Utility function for calculating // Minimum element to delete function utility_fun_for_del(str, i, j) { if (i >= j) return 0; // Condition to compare characters if (str[i] == str[j]) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + Math.min(utility_fun_for_del( str, i + 1, j), utility_fun_for_del( str, i, j - 1)); } // Function to calculate the minimum // Element required to delete for // Making string palindrome function min_ele_del(str) { // Utility function call return utility_fun_for_del(str, 0, str.length - 1); } let str = "abefbac"; document.write("Minimum element of " + "deletions = " + min_ele_del(str)); // This code is contributed by mukesh07.</script> Minimum element of deletions = 2 Approach: Top-down dynamic programming We will first define the DP table and initialize it with -1 throughout the table. Follow the below approach now, Define the function transformation to calculate the Minimum number of deletions and insertions to transform one string into anotherWe write the condition for base casesChecking the wanted conditionIf the condition is satisfied we increment the value and store the value in the tableIf the recursive call is being solved earlier than we directly utilize the value from the tableElse store the max transformation from the subsequenceWe will continue the process till we reach the base conditionReturn the DP [-1][-1] Define the function transformation to calculate the Minimum number of deletions and insertions to transform one string into another We write the condition for base cases Checking the wanted condition If the condition is satisfied we increment the value and store the value in the table If the recursive call is being solved earlier than we directly utilize the value from the table Else store the max transformation from the subsequence We will continue the process till we reach the base condition Return the DP [-1][-1] Below is the implementation: C++ Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std; int dp[2000][2000]; // Function definitionint transformation(string s1, string s2, int i, int j){ // Base cases if (i >= (s1.size()) || j >= (s2.size())) return 0; // Checking the ndesired condition if (s1[i] == s2[j]) { // If yes increment the count dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if (dp[i][j] != -1) { // Return the value form the table return dp[i][j]; } // Else store the max transformation // from the subsequence else dp[i][j] = max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); // Return the dp [-1][-1] return dp[s1.size() - 1][s2.size() - 1];} // Driver codeint main(){ string s1 = "geeksforgeeks"; string s2 = "geeks"; int i = 0; int j = 0; // Initialize the array with -1 memset(dp, -1, sizeof dp); cout << "MINIMUM NUMBER OF DELETIONS: " << (s1.size()) - transformation(s1, s2, 0, 0) << endl; cout << "MINIMUM NUMBER OF INSERTIONS: " << (s2.size()) - transformation(s1, s2, 0, 0) << endl; cout << ("LCS LENGTH: ") << transformation(s1, s2, 0, 0);} // This code is contributed by Stream_Cipher import java.util.*;public class GFG{ static int dp[][] = new int[2000][2000]; // Function definition public static int transformation(String s1, String s2, int i, int j) { // Base cases if(i >= s1.length() || j >= s2.length()) { return 0; } // Checking the ndesired condition if(s1.charAt(i) == s2.charAt(j)) { // If yes increment the count dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if(dp[i][j] != -1) { // Return the value form the table return dp[i][j]; } // Else store the max transformation // from the subsequence else { dp[i][j] = Math.max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); } // Return the dp [-1][-1] return dp[s1.length() - 1][s2.length() - 1]; } // Driver code public static void main(String []args) { String s1 = "geeksforgeeks"; String s2 = "geeks"; int i = 0; int j = 0; // Initialize the array with -1 for (int[] row: dp) {Arrays.fill(row, -1);} System.out.println("MINIMUM NUMBER OF DELETIONS: " + (s1.length() - transformation(s1, s2, 0, 0))); System.out.println("MINIMUM NUMBER OF INSERTIONS: " + (s2.length() - transformation(s1, s2, 0, 0))); System.out.println("LCS LENGTH: " + transformation(s1, s2, 0, 0)); }} // This code is contributed by avanitrachhadiya2155 # function definitiondef transformation(s1,s2,i,j,dp): # base cases if i>=len(s1) or j>=len(s2): return 0 # checking the ndesired condition if s1[i]==s2[j]: # if yes increment the count dp[i][j]=1+transformation(s1,s2,i+1,j+1,dp) # if no if dp[i][j]!=-1: #return the value form the table return dp[i][j] # else store the max transformation # from the subsequence else: dp[i][j]=max(transformation(s1,s2,i,j+i,dp), transformation(s1,s2,i+1,j,dp)) # return the dp [-1][-1] return dp[-1][-1] s1 = "geeksforgeeks"s2 = "geeks"i=0j=0 #initialize the array with -1dp=[[-1 for _ in range(len(s1)+1)] for _ in range(len(s2)+1)]print("MINIMUM NUMBER OF DELETIONS: ", len(s1)-transformation(s1,s2,0,0,dp), end=" ")print("MINIMUM NUMBER OF INSERTIONS: ", len(s2)-transformation(s1,s2,0,0,dp), end=" " )print("LCS LENGTH: ",transformation(s1,s2,0,0,dp)) #code contributed by saikumar kudikala using System; class GFG{ static int[,] dp = new int[2000, 2000]; // Function definitionstatic int transformation(string s1, string s2, int i, int j ){ // Base cases if (i >= (s1.Length) || j >= (s2.Length)) { return 0; } // Checking the ndesired condition if (s1[i] == s2[j]) { // If yes increment the count dp[i, j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if (dp[i, j] != -1) { // Return the value form the table return dp[i, j]; } // Else store the max transformation // from the subsequence else { dp[i, j] = Math.Max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); } // Return the dp [-1][-1] return dp[s1.Length - 1, s2.Length - 1];} // Driver codestatic public void Main(){ string s1 = "geeksforgeeks"; string s2 = "geeks"; // Initialize the array with -1 for(int m = 0; m < 2000; m++ ) { for(int n = 0; n < 2000; n++) { dp[m, n] = -1; } } Console.WriteLine("MINIMUM NUMBER OF DELETIONS: " + (s1.Length-transformation(s1, s2, 0, 0))); Console.WriteLine("MINIMUM NUMBER OF INSERTIONS: " + (s2.Length-transformation(s1, s2, 0, 0))); Console.WriteLine("LCS LENGTH: " + transformation(s1, s2, 0, 0));}} // This code is contributed by rag2127 <script> let dp = new Array(2000); // Function definitionfunction transformation(s1, s2, i, j){ // Base cases if(i >= s1.length || j >= s2.length) { return 0; } // Checking the ndesired condition if (s1[i] == s2[j]) { // If yes increment the count dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if (dp[i][j] != -1) { // Return the value form the table return dp[i][j]; } // Else store the max transformation // from the subsequence else { dp[i][j] = Math.max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); } // Return the dp [-1][-1] return dp[s1.length - 1][s2.length - 1];} // Driver codelet s1 = "geeksforgeeks";let s2 = "geeks";let i = 0;let j = 0; // Initialize the array with -1for(let row = 0; row < dp.length; row++){ dp[row] = new Array(dp.length); for(let column = 0; column < dp.length; column++) { dp[row][column] = -1; }} document.write("MINIMUM NUMBER OF DELETIONS: " + (s1.length - transformation(s1, s2, 0, 0)));document.write(" MINIMUM NUMBER OF INSERTIONS: " + (s2.length - transformation(s1, s2, 0, 0)));document.write(" LCS LENGTH: " + transformation(s1, s2, 0, 0)); // This code is contributed by rameshtravel07 </script> Output: MINIMUM NUMBER OF DELETIONS: 8 MINIMUM NUMBER OF INSERTIONS: 0 LCS LENGTH: 5 Time Complexity: O(N^K) Space Complexity: O(N) This article is contributed by Ayush Jauhari. 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. nitin mittal ukasp MohammadMudassir avanitrachhadiya2155 saikumarkudikala Stream_Cipher divyeshrabadiya07 divyesh072019 rag2127 anikaseth98 mukesh07 rameshtravel07 decode2207 adnanirshad158 gabaa406 kashishsoda sumitgumber28 simmytarika5 kothavvsaakash Amazon palindrome Dynamic Programming Strings Amazon Strings Dynamic Programming palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Program for Fibonacci numbers Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3 Find if there is a path between two vertices in an undirected graph 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": 54, "s": 26, "text": "\n01 Jun, 2022" }, { "code": null, "e": 210, "s": 54, "text": "Given a string of size ‘n’. The task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome. " }, { "code": null, "e": 263, "s": 210, "text": "Note: The order of characters should be maintained. " }, { "code": null, "e": 275, "s": 263, "text": "Examples : " }, { "code": null, "e": 429, "s": 275, "text": "Input : aebcbda\nOutput : 2\nRemove characters 'e' and 'd'\nResultant string will be 'abcba'\nwhich is a palindromic string\n\nInput : geeksforgeeks\nOutput : 8" }, { "code": null, "e": 597, "s": 429, "text": "A simple solution is to remove all subsequences one by one and check if the remaining string is palindrome or not. The time complexity of this solution is exponential." }, { "code": null, "e": 719, "s": 597, "text": "An efficient approach uses the concept of finding the length of the longest palindromic subsequence of a given sequence. " }, { "code": null, "e": 731, "s": 719, "text": "Algorithm: " }, { "code": null, "e": 759, "s": 731, "text": "1. str is the given string." }, { "code": null, "e": 778, "s": 759, "text": "2. n length of str" }, { "code": null, "e": 847, "s": 778, "text": "3. len be the length of the longest palindromic subsequence of str" }, { "code": null, "e": 894, "s": 847, "text": "4. minimum number of deletions min = n – len" }, { "code": null, "e": 945, "s": 894, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 949, "s": 945, "text": "C++" }, { "code": null, "e": 954, "s": 949, "text": "Java" }, { "code": null, "e": 962, "s": 954, "text": "Python3" }, { "code": null, "e": 965, "s": 962, "text": "C#" }, { "code": null, "e": 969, "s": 965, "text": "PHP" }, { "code": null, "e": 980, "s": 969, "text": "Javascript" }, { "code": "// C++ implementation to find// minimum number of deletions// to make a string palindromic#include <bits/stdc++.h>using namespace std; // Returns the length of// the longest palindromic// subsequence in 'str'int lps(string str){ int n = str.size(); // Create a table to store // results of subproblems int L[n][n]; // Strings of length 1 // are palindrome of length 1 for (int i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note that // the lower diagonal values // of table are useless and // not filled in the process. // c1 is length of substring for (int cl = 2; cl <= n; cl++) { for (int i = 0; i < n - cl + 1; i++) { int j = i + cl - 1; if (str[i] == str[j] && cl == 2) L[i][j] = 2; else if (str[i] == str[j]) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = max(L[i][j - 1], L[i + 1][j]); } } // length of longest // palindromic subseq return L[0][n - 1];} // function to calculate// minimum number of deletionsint minimumNumberOfDeletions(string str){ int n = str.size(); // Find longest palindromic // subsequence int len = lps(str); // After removing characters // other than the lps, we // get palindrome. return (n - len);} // Driver Codeint main(){ string str = \"geeksforgeeks\"; cout << \"Minimum number of deletions = \" << minimumNumberOfDeletions(str); return 0;}", "e": 2544, "s": 980, "text": null }, { "code": "// Java implementation to// find minimum number of// deletions to make a// string palindromicclass GFG{ // Returns the length of // the longest palindromic // subsequence in 'str' static int lps(String str) { int n = str.length(); // Create a table to store // results of subproblems int L[][] = new int[n][n]; // Strings of length 1 // are palindrome of length 1 for (int i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note // that the lower diagonal // values of table are useless // and not filled in the process. // c1 is length of substring for (int cl = 2; cl <= n; cl++) { for (int i = 0; i < n - cl + 1; i++) { int j = i + cl - 1; if (str.charAt(i) == str.charAt(j) && cl == 2) L[i][j] = 2; else if (str.charAt(i) == str.charAt(j)) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = Integer.max(L[i][j - 1], L[i + 1][j]); } } // length of longest // palindromic subsequence return L[0][n - 1]; } // function to calculate minimum // number of deletions static int minimumNumberOfDeletions(String str) { int n = str.length(); // Find longest palindromic // subsequence int len = lps(str); // After removing characters // other than the lps, we get // palindrome. return (n - len); } // Driver Code public static void main(String[] args) { String str = \"geeksforgeeks\"; System.out.println(\"Minimum number \" + \"of deletions = \"+ minimumNumberOfDeletions(str)); }} // This code is contributed by Sumit Ghosh", "e": 4498, "s": 2544, "text": null }, { "code": "# Python3 implementation to find# minimum number of deletions# to make a string palindromic # Returns the length of# the longest palindromic# subsequence in 'str'def lps(str): n = len(str) # Create a table to store # results of subproblems L = [[0 for x in range(n)]for y in range(n)] # Strings of length 1 # are palindrome of length 1 for i in range(n): L[i][i] = 1 # Build the table. Note that # the lower diagonal values # of table are useless and # not filled in the process. # c1 is length of substring for cl in range( 2, n+1): for i in range(n - cl + 1): j = i + cl - 1 if (str[i] == str[j] and cl == 2): L[i][j] = 2 elif (str[i] == str[j]): L[i][j] = L[i + 1][j - 1] + 2 else: L[i][j] = max(L[i][j - 1],L[i + 1][j]) # length of longest # palindromic subseq return L[0][n - 1] # function to calculate# minimum number of deletionsdef minimumNumberOfDeletions( str): n = len(str) # Find longest palindromic # subsequence l = lps(str) # After removing characters # other than the lps, we # get palindrome. return (n - l) # Driver Codeif __name__ == \"__main__\": str = \"geeksforgeeks\" print( \"Minimum number of deletions = \" , minimumNumberOfDeletions(str))", "e": 5868, "s": 4498, "text": null }, { "code": "// C# implementation to find// minimum number of deletions// to make a string palindromicusing System; class GFG{ // Returns the length of // the longest palindromic // subsequence in 'str' static int lps(String str) { int n = str.Length; // Create a table to store // results of subproblems int [,]L = new int[n, n]; // Strings of length 1 // are palindrome of length 1 for (int i = 0; i < n; i++) L[i, i] = 1; // Build the table. Note // that the lower diagonal // values of table are useless // and not filled in the process. // c1 is length of substring for (int cl = 2; cl <= n; cl++) { for (int i = 0; i < n - cl + 1; i++) { int j = i + cl - 1; if (str[i] == str[j] && cl == 2) L[i, j] = 2; else if (str[i] == str[j]) L[i, j] = L[i + 1, j - 1] + 2; else L[i, j] = Math.Max(L[i, j - 1], L[i + 1, j]); } } // length of longest // palindromic subsequence return L[0, n - 1]; } // function to calculate minimum // number of deletions static int minimumNumberOfDeletions(string str) { int n = str.Length; // Find longest palindromic // subsequence int len = lps(str); // After removing characters // other than the lps, we get // palindrome. return (n - len); } // Driver Code public static void Main() { string str = \"geeksforgeeks\"; Console.Write(\"Minimum number of\" + \" deletions = \" + minimumNumberOfDeletions(str)); }} // This code is contributed by nitin mittal.", "e": 7721, "s": 5868, "text": null }, { "code": "<?php// PHP implementation to find// minimum number of deletions// to make a string palindromic // Returns the length of// the longest palindromic// subsequence in 'str'function lps($str){ $n = strlen($str); // Create a table to store // results of subproblems $L; // Strings of length 1 // are palindrome of length 1 for ($i = 0; $i < $n; $i++) $L[$i][$i] = 1; // Build the table. Note that // the lower diagonal values // of table are useless and // not filled in the process. // c1 is length of substring for ($cl = 2; $cl <= $n; $cl++) { for ( $i = 0; $i < $n -$cl + 1; $i++) { $j = $i + $cl - 1; if ($str[$i] == $str[$j] && $cl == 2) $L[$i][$j] = 2; else if ($str[$i] == $str[$j]) $L[$i][$j] = $L[$i + 1][$j - 1] + 2; else $L[$i][$j] = max($L[$i][$j - 1], $L[$i + 1][$j]); } } // length of longest // palindromic subseq return $L[0][$n - 1];} // function to calculate minimum// number of deletionsfunction minimumNumberOfDeletions($str){ $n = strlen($str); // Find longest // palindromic subsequence $len = lps($str); // After removing characters // other than the lps, we get // palindrome. return ($n - $len);} // Driver Code{ $str = \"geeksforgeeks\"; echo \"Minimum number of deletions = \", minimumNumberOfDeletions($str); return 0;} // This code is contributed by nitin mittal.?>", "e": 9348, "s": 7721, "text": null }, { "code": "<script> // JavaScript implementation to // find minimum number of // deletions to make a // string palindromic // Returns the length of // the longest palindromic // subsequence in 'str' function lps(str) { let n = str.length; // Create a table to store // results of subproblems let L = new Array(n); for (let i = 0; i < n; i++) { L[i] = new Array(n); for (let j = 0; j < n; j++) { L[i][j] = 0; } } // Strings of length 1 // are palindrome of length 1 for (let i = 0; i < n; i++) L[i][i] = 1; // Build the table. Note // that the lower diagonal // values of table are useless // and not filled in the process. // c1 is length of substring for (let cl = 2; cl <= n; cl++) { for (let i = 0; i < n - cl + 1; i++) { let j = i + cl - 1; if (str[i] == str[j] && cl == 2) L[i][j] = 2; else if (str[i] == str[j]) L[i][j] = L[i + 1][j - 1] + 2; else L[i][j] = Math.max(L[i][j - 1], L[i + 1][j]); } } // length of longest // palindromic subsequence return L[0][n - 1]; } // function to calculate minimum // number of deletions function minimumNumberOfDeletions(str) { let n = str.length; // Find longest palindromic // subsequence let len = lps(str); // After removing characters // other than the lps, we get // palindrome. return (n - len); } let str = \"geeksforgeeks\"; document.write(\"Minimum number \" + \"of deletions = \"+ minimumNumberOfDeletions(str)); </script>", "e": 11065, "s": 9348, "text": null }, { "code": null, "e": 11097, "s": 11065, "text": "Minimum number of deletions = 8" }, { "code": null, "e": 11120, "s": 11097, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 11138, "s": 11120, "text": "Another Approach:" }, { "code": null, "e": 11186, "s": 11138, "text": "Take two indexes first as ‘i’ and last as a ‘j’" }, { "code": null, "e": 11237, "s": 11186, "text": "now compare the character at the index ‘i’ and ‘j’" }, { "code": null, "e": 11352, "s": 11237, "text": "if characters are equal, then recursively call the function by incrementing ‘i’ by ‘1’ and decrementing ‘j’ by ‘1’" }, { "code": null, "e": 11437, "s": 11352, "text": "recursively call the function by incrementing ‘i’ by ‘1’ and decrementing ‘j’ by ‘1’" }, { "code": null, "e": 11628, "s": 11437, "text": "else recursively call the two functions, the first increment ‘i’ by ‘1’ keeping ‘j’ constant, second decrement ‘j’ by ‘1’ keeping ‘i’ constant.take a minimum of both and return by adding ‘1’" }, { "code": null, "e": 11767, "s": 11628, "text": "recursively call the two functions, the first increment ‘i’ by ‘1’ keeping ‘j’ constant, second decrement ‘j’ by ‘1’ keeping ‘i’ constant." }, { "code": null, "e": 11815, "s": 11767, "text": "take a minimum of both and return by adding ‘1’" }, { "code": null, "e": 11866, "s": 11815, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 11870, "s": 11866, "text": "C++" }, { "code": null, "e": 11875, "s": 11870, "text": "Java" }, { "code": null, "e": 11883, "s": 11875, "text": "Python3" }, { "code": null, "e": 11886, "s": 11883, "text": "C#" }, { "code": null, "e": 11897, "s": 11886, "text": "Javascript" }, { "code": "// C++ program for above approach#include <iostream>using namespace std; // Function to return minimum// Element between two valuesint min(int x, int y){ return (x < y) ? x : y;} // Utility function for calculating// Minimum element to deleteint utility_fun_for_del(string str, int i, int j){ if (i >= j) return 0; // Condition to compare characters if (str[i] == str[j]) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + min(utility_fun_for_del(str, i + 1, j), utility_fun_for_del(str, i, j - 1));} // Function to calculate the minimum// Element required to delete for// Making string palindromeint min_ele_del(string str){ // Utility function call return utility_fun_for_del(str, 0, str.length() - 1);} // Driver codeint main(){ string str = \"abefbac\"; cout << \"Minimum element of deletions = \" << min_ele_del(str) << endl; return 0;} // This code is contributed by MOHAMMAD MUDASSIR", "e": 13031, "s": 11897, "text": null }, { "code": "// Java program for above approachimport java.io.*;import java.util.*; class GFG{ // Function to return minimum// Element between two valuespublic static int min(int x, int y){ return (x < y) ? x : y;} // Utility function for calculating// Minimum element to deletepublic static int utility_fun_for_del(String str, int i, int j){ if (i >= j) return 0; // Condition to compare characters if (str.charAt(i) == str.charAt(j)) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + Math.min(utility_fun_for_del(str, i + 1, j), utility_fun_for_del(str, i, j - 1));} // Function to calculate the minimum// Element required to delete for// Making string palindromepublic static int min_ele_del(String str){ // Utility function call return utility_fun_for_del(str, 0, str.length() - 1);} // Driver Codepublic static void main(String[] args){ String str = \"abefbac\"; System.out.println(\"Minimum element of deletions = \" + min_ele_del(str));}} // This code is contributed by divyeshrabadiya07", "e": 14311, "s": 13031, "text": null }, { "code": "# Python3 program for above approach # Utility function for calculating# Minimum element to deletedef utility_fun_for_del(Str, i, j): if (i >= j): return 0 # Condition to compare characters if (Str[i] == Str[j]): # Recursive function call return utility_fun_for_del(Str, i + 1, j - 1) # Return value, incrementing by 1 # return minimum Element between two values return (1 + min(utility_fun_for_del(Str, i + 1, j), utility_fun_for_del(Str, i, j - 1))) # Function to calculate the minimum# Element required to delete for# Making string palindromedef min_ele_del(Str): # Utility function call return utility_fun_for_del(Str, 0, len(Str) - 1) # Driver codeStr = \"abefbac\" print(\"Minimum element of deletions =\", min_ele_del(Str)) # This code is contributed by avanitrachhadiya2155", "e": 15244, "s": 14311, "text": null }, { "code": "// C# program for above approachusing System;using System.Collections.Generic; class GFG{ // Function to return minimum// Element between two valuesstatic int min(int x, int y){ return (x < y) ? x : y;} // Utility function for calculating// Minimum element to deletestatic int utility_fun_for_del(string str, int i, int j){ if (i >= j) return 0; // Condition to compare characters if (str[i] == str[j]) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + Math.Min(utility_fun_for_del( str, i + 1, j), utility_fun_for_del( str, i, j - 1));} // Function to calculate the minimum// Element required to delete for// Making string palindromestatic int min_ele_del(string str){ // Utility function call return utility_fun_for_del(str, 0, str.Length - 1);} // Driver code static void Main(){ string str = \"abefbac\"; Console.WriteLine(\"Minimum element of \" + \"deletions = \" + min_ele_del(str));}} // This code is contributed by divyesh072019", "e": 16559, "s": 15244, "text": null }, { "code": "<script> // Javascript program for above approach // Function to return minimum // Element between two values function min(x, y) { return (x < y) ? x : y; } // Utility function for calculating // Minimum element to delete function utility_fun_for_del(str, i, j) { if (i >= j) return 0; // Condition to compare characters if (str[i] == str[j]) { // Recursive function call return utility_fun_for_del(str, i + 1, j - 1); } // Return value, incrementing by 1 return 1 + Math.min(utility_fun_for_del( str, i + 1, j), utility_fun_for_del( str, i, j - 1)); } // Function to calculate the minimum // Element required to delete for // Making string palindrome function min_ele_del(str) { // Utility function call return utility_fun_for_del(str, 0, str.length - 1); } let str = \"abefbac\"; document.write(\"Minimum element of \" + \"deletions = \" + min_ele_del(str)); // This code is contributed by mukesh07.</script>", "e": 17813, "s": 16559, "text": null }, { "code": null, "e": 17846, "s": 17813, "text": "Minimum element of deletions = 2" }, { "code": null, "e": 17885, "s": 17846, "text": "Approach: Top-down dynamic programming" }, { "code": null, "e": 17998, "s": 17885, "text": "We will first define the DP table and initialize it with -1 throughout the table. Follow the below approach now," }, { "code": null, "e": 18514, "s": 17998, "text": "Define the function transformation to calculate the Minimum number of deletions and insertions to transform one string into anotherWe write the condition for base casesChecking the wanted conditionIf the condition is satisfied we increment the value and store the value in the tableIf the recursive call is being solved earlier than we directly utilize the value from the tableElse store the max transformation from the subsequenceWe will continue the process till we reach the base conditionReturn the DP [-1][-1]" }, { "code": null, "e": 18646, "s": 18514, "text": "Define the function transformation to calculate the Minimum number of deletions and insertions to transform one string into another" }, { "code": null, "e": 18685, "s": 18646, "text": "We write the condition for base cases" }, { "code": null, "e": 18715, "s": 18685, "text": "Checking the wanted condition" }, { "code": null, "e": 18801, "s": 18715, "text": "If the condition is satisfied we increment the value and store the value in the table" }, { "code": null, "e": 18897, "s": 18801, "text": "If the recursive call is being solved earlier than we directly utilize the value from the table" }, { "code": null, "e": 18952, "s": 18897, "text": "Else store the max transformation from the subsequence" }, { "code": null, "e": 19014, "s": 18952, "text": "We will continue the process till we reach the base condition" }, { "code": null, "e": 19037, "s": 19014, "text": "Return the DP [-1][-1]" }, { "code": null, "e": 19066, "s": 19037, "text": "Below is the implementation:" }, { "code": null, "e": 19070, "s": 19066, "text": "C++" }, { "code": null, "e": 19075, "s": 19070, "text": "Java" }, { "code": null, "e": 19083, "s": 19075, "text": "Python3" }, { "code": null, "e": 19086, "s": 19083, "text": "C#" }, { "code": null, "e": 19097, "s": 19086, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; int dp[2000][2000]; // Function definitionint transformation(string s1, string s2, int i, int j){ // Base cases if (i >= (s1.size()) || j >= (s2.size())) return 0; // Checking the ndesired condition if (s1[i] == s2[j]) { // If yes increment the count dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if (dp[i][j] != -1) { // Return the value form the table return dp[i][j]; } // Else store the max transformation // from the subsequence else dp[i][j] = max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); // Return the dp [-1][-1] return dp[s1.size() - 1][s2.size() - 1];} // Driver codeint main(){ string s1 = \"geeksforgeeks\"; string s2 = \"geeks\"; int i = 0; int j = 0; // Initialize the array with -1 memset(dp, -1, sizeof dp); cout << \"MINIMUM NUMBER OF DELETIONS: \" << (s1.size()) - transformation(s1, s2, 0, 0) << endl; cout << \"MINIMUM NUMBER OF INSERTIONS: \" << (s2.size()) - transformation(s1, s2, 0, 0) << endl; cout << (\"LCS LENGTH: \") << transformation(s1, s2, 0, 0);} // This code is contributed by Stream_Cipher", "e": 20500, "s": 19097, "text": null }, { "code": "import java.util.*;public class GFG{ static int dp[][] = new int[2000][2000]; // Function definition public static int transformation(String s1, String s2, int i, int j) { // Base cases if(i >= s1.length() || j >= s2.length()) { return 0; } // Checking the ndesired condition if(s1.charAt(i) == s2.charAt(j)) { // If yes increment the count dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if(dp[i][j] != -1) { // Return the value form the table return dp[i][j]; } // Else store the max transformation // from the subsequence else { dp[i][j] = Math.max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); } // Return the dp [-1][-1] return dp[s1.length() - 1][s2.length() - 1]; } // Driver code public static void main(String []args) { String s1 = \"geeksforgeeks\"; String s2 = \"geeks\"; int i = 0; int j = 0; // Initialize the array with -1 for (int[] row: dp) {Arrays.fill(row, -1);} System.out.println(\"MINIMUM NUMBER OF DELETIONS: \" + (s1.length() - transformation(s1, s2, 0, 0))); System.out.println(\"MINIMUM NUMBER OF INSERTIONS: \" + (s2.length() - transformation(s1, s2, 0, 0))); System.out.println(\"LCS LENGTH: \" + transformation(s1, s2, 0, 0)); }} // This code is contributed by avanitrachhadiya2155", "e": 22312, "s": 20500, "text": null }, { "code": "# function definitiondef transformation(s1,s2,i,j,dp): # base cases if i>=len(s1) or j>=len(s2): return 0 # checking the ndesired condition if s1[i]==s2[j]: # if yes increment the count dp[i][j]=1+transformation(s1,s2,i+1,j+1,dp) # if no if dp[i][j]!=-1: #return the value form the table return dp[i][j] # else store the max transformation # from the subsequence else: dp[i][j]=max(transformation(s1,s2,i,j+i,dp), transformation(s1,s2,i+1,j,dp)) # return the dp [-1][-1] return dp[-1][-1] s1 = \"geeksforgeeks\"s2 = \"geeks\"i=0j=0 #initialize the array with -1dp=[[-1 for _ in range(len(s1)+1)] for _ in range(len(s2)+1)]print(\"MINIMUM NUMBER OF DELETIONS: \", len(s1)-transformation(s1,s2,0,0,dp), end=\" \")print(\"MINIMUM NUMBER OF INSERTIONS: \", len(s2)-transformation(s1,s2,0,0,dp), end=\" \" )print(\"LCS LENGTH: \",transformation(s1,s2,0,0,dp)) #code contributed by saikumar kudikala", "e": 23388, "s": 22312, "text": null }, { "code": "using System; class GFG{ static int[,] dp = new int[2000, 2000]; // Function definitionstatic int transformation(string s1, string s2, int i, int j ){ // Base cases if (i >= (s1.Length) || j >= (s2.Length)) { return 0; } // Checking the ndesired condition if (s1[i] == s2[j]) { // If yes increment the count dp[i, j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if (dp[i, j] != -1) { // Return the value form the table return dp[i, j]; } // Else store the max transformation // from the subsequence else { dp[i, j] = Math.Max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); } // Return the dp [-1][-1] return dp[s1.Length - 1, s2.Length - 1];} // Driver codestatic public void Main(){ string s1 = \"geeksforgeeks\"; string s2 = \"geeks\"; // Initialize the array with -1 for(int m = 0; m < 2000; m++ ) { for(int n = 0; n < 2000; n++) { dp[m, n] = -1; } } Console.WriteLine(\"MINIMUM NUMBER OF DELETIONS: \" + (s1.Length-transformation(s1, s2, 0, 0))); Console.WriteLine(\"MINIMUM NUMBER OF INSERTIONS: \" + (s2.Length-transformation(s1, s2, 0, 0))); Console.WriteLine(\"LCS LENGTH: \" + transformation(s1, s2, 0, 0));}} // This code is contributed by rag2127", "e": 24982, "s": 23388, "text": null }, { "code": "<script> let dp = new Array(2000); // Function definitionfunction transformation(s1, s2, i, j){ // Base cases if(i >= s1.length || j >= s2.length) { return 0; } // Checking the ndesired condition if (s1[i] == s2[j]) { // If yes increment the count dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1); } // If no if (dp[i][j] != -1) { // Return the value form the table return dp[i][j]; } // Else store the max transformation // from the subsequence else { dp[i][j] = Math.max(transformation(s1, s2, i, j + i), transformation(s1, s2, i + 1, j)); } // Return the dp [-1][-1] return dp[s1.length - 1][s2.length - 1];} // Driver codelet s1 = \"geeksforgeeks\";let s2 = \"geeks\";let i = 0;let j = 0; // Initialize the array with -1for(let row = 0; row < dp.length; row++){ dp[row] = new Array(dp.length); for(let column = 0; column < dp.length; column++) { dp[row][column] = -1; }} document.write(\"MINIMUM NUMBER OF DELETIONS: \" + (s1.length - transformation(s1, s2, 0, 0)));document.write(\" MINIMUM NUMBER OF INSERTIONS: \" + (s2.length - transformation(s1, s2, 0, 0)));document.write(\" LCS LENGTH: \" + transformation(s1, s2, 0, 0)); // This code is contributed by rameshtravel07 </script>", "e": 26478, "s": 24982, "text": null }, { "code": null, "e": 26486, "s": 26478, "text": "Output:" }, { "code": null, "e": 26566, "s": 26486, "text": "MINIMUM NUMBER OF DELETIONS: 8 MINIMUM NUMBER OF INSERTIONS: 0 LCS LENGTH: 5" }, { "code": null, "e": 26590, "s": 26566, "text": "Time Complexity: O(N^K)" }, { "code": null, "e": 26613, "s": 26590, "text": "Space Complexity: O(N)" }, { "code": null, "e": 26660, "s": 26613, "text": "This article is contributed by Ayush Jauhari. " }, { "code": null, "e": 27035, "s": 26660, "text": "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": 27050, "s": 27037, "text": "nitin mittal" }, { "code": null, "e": 27056, "s": 27050, "text": "ukasp" }, { "code": null, "e": 27073, "s": 27056, "text": "MohammadMudassir" }, { "code": null, "e": 27094, "s": 27073, "text": "avanitrachhadiya2155" }, { "code": null, "e": 27111, "s": 27094, "text": "saikumarkudikala" }, { "code": null, "e": 27125, "s": 27111, "text": "Stream_Cipher" }, { "code": null, "e": 27143, "s": 27125, "text": "divyeshrabadiya07" }, { "code": null, "e": 27157, "s": 27143, "text": "divyesh072019" }, { "code": null, "e": 27165, "s": 27157, "text": "rag2127" }, { "code": null, "e": 27177, "s": 27165, "text": "anikaseth98" }, { "code": null, "e": 27186, "s": 27177, "text": "mukesh07" }, { "code": null, "e": 27201, "s": 27186, "text": "rameshtravel07" }, { "code": null, "e": 27212, "s": 27201, "text": "decode2207" }, { "code": null, "e": 27227, "s": 27212, "text": "adnanirshad158" }, { "code": null, "e": 27236, "s": 27227, "text": "gabaa406" }, { "code": null, "e": 27248, "s": 27236, "text": "kashishsoda" }, { "code": null, "e": 27262, "s": 27248, "text": "sumitgumber28" }, { "code": null, "e": 27275, "s": 27262, "text": "simmytarika5" }, { "code": null, "e": 27290, "s": 27275, "text": "kothavvsaakash" }, { "code": null, "e": 27297, "s": 27290, "text": "Amazon" }, { "code": null, "e": 27308, "s": 27297, "text": "palindrome" }, { "code": null, "e": 27328, "s": 27308, "text": "Dynamic Programming" }, { "code": null, "e": 27336, "s": 27328, "text": "Strings" }, { "code": null, "e": 27343, "s": 27336, "text": "Amazon" }, { "code": null, "e": 27351, "s": 27343, "text": "Strings" }, { "code": null, "e": 27371, "s": 27351, "text": "Dynamic Programming" }, { "code": null, "e": 27382, "s": 27371, "text": "palindrome" }, { "code": null, "e": 27480, "s": 27382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27512, "s": 27480, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 27542, "s": 27512, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 27580, "s": 27542, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 27618, "s": 27580, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 27686, "s": 27618, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 27732, "s": 27686, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 27757, "s": 27732, "text": "Reverse a string in Java" }, { "code": null, "e": 27817, "s": 27757, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27832, "s": 27817, "text": "C++ Data Types" } ]
Dart – Collections
22 Sep, 2021 Collections are groups of objects that represent a particular element. The dart::collection library is used to implement the collection in dart. There are a variety of collections available in dart. Some of the classes of Dart Collection are – List<E>: A List is an ordered group of objects. Set<E>: Collection of objects in which each of the objects occurs only once Map<K, V>: Collection of objects that has a simple key/value pair-based object. The key and value of a map can be of any type. Queue<E>: A Queue is a collection that can be manipulated at both ends. One can iterate over a queue with an Iterator or using forEach. DoubleLinkedQueue<E>: Doubly-linked list based on the queue data structure. HashMap<K, V>: Map based on hash table i.e unordered map. HashSet<E>: Set based on hash table i.e unordered set. LinkedHashMap<K, V>: Similar to HashMap but based on LinkedList. LinkedHashSet<E>: Similar to HashSet but based on LinkedList. LinkedList<E extends LinkedListEntry<E>>: It is a specialized double-linked list of elements. LinkedListEntry<E extends LinkedListEntry<E>>: An element of a LinkedList. MapBase<K, V>: This is the base class for Map. UnmodifiableListView<E>: An unmodifiable List view of another List. UnmodifiableMapBase<K, V>: Basic implementation of an unmodifiable Map. UnmodifiableMapView<K, V>: Unmodifiable view of the map. We will be discussing the 4 basic collections with examples here. The list is an ordered group of objects where each object is from one specific type. To define a list in dart, specify the object type inside the angled brackets (<>) as shown below: List<String> fruits = ["Mango", "Apple", "Banana"] Example: Here we have defined a list and performed some common operations along with some basic commonly used methods. Dart void main() { // creating a new empty List List geekList = new List(); // We can also create a list with a predefined type // as List<int> sampleList = new List() // and also define a list of fixed length as // List<int> sampleList = new List(5) // Adding an element to the geekList geekList.addAll([1,2,3,4,5,"Apple"]); print(geekList); // Looping over the list for(var i = 0; i<geekList.length;i++){ print("element $i is ${geekList[i]}"); } // Removing an element from geekList by index geekList.removeAt(2); // Removing an element from geekList by object geekList.remove("Apple"); print(geekList); // Return a reversed version of the list print(geekList.reversed); // Checks if the list is empty print(geekList.isEmpty); // Gives the first element of the list print(geekList.first); // Reassigning the geekList and creating the // elements using Iterable geekList = Iterable<int>.generate(10).toList(); print(geekList);} Output: [1, 2, 3, 4, 5, Apple] element 0 is 1 element 1 is 2 element 2 is 3 element 3 is 4 element 4 is 5 element 5 is Apple [1, 2, 4, 5] (5, 4, 2, 1) false 1 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Sets are one of the essential part of Dart Collections. A set is defined as an unordered collection of unique objects. To define a set follow the below: Set fruits = Set.from("Mango", "Apple", "Banana") Example: As discussed earlier a set stores a group of objects that are not repeating. A sample program is shown below. Dart void main() { // Initializing the Set and Adding the values Set geekSet = new Set(); geekSet.addAll([9,1,2,3,4,5,6,1,1,9]); // Looping over the set for(var el in geekSet){ print(el); } // length of the set. print('Length: ${geekSet.length}'); // printing the first element in the set print('First Element: ${geekSet.first}'); // Deleting an element not present. No Change geekSet.remove(10); // Deleting an element 9 geekSet.remove(9); print(geekSet);} Output: 9 1 2 3 4 5 6 Length: 7 First Element: 9 {1, 2, 3, 4, 5, 6} In Dart, Maps are unordered key-value pair collection that sets an associate key to the values within. To define a Map, specify the key type and the value type inside the angle brackets(<>) as shown below: Map<int, string> fruits = {1: "Mango", 2:"Apple", 3:"Banana"} Example: The map collection stores the objects as a key-value pair. An example is shown below. Dart void main() { // Initializing the map with sample values. var geekMap = {1:"Apple",2:"Mango",3:"Banana"}; print(geekMap); // Adding elements by different methods. geekMap.addAll({4:'Pineapple',2:'Grapes'}); geekMap[9]="Kiwi"; print(geekMap); // printing key and values print('Keys: ${geekMap.keys} \nValues: ${geekMap.values}'); // removing an element from the map by its key geekMap.remove(2); // printing the map and its length print('{$geekMap} length is ${geekMap.length}');} Output: {1: Apple, 2: Mango, 3: Banana} {1: Apple, 2: Grapes, 3: Banana, 4: Pineapple, 9: Kiwi} Keys: (1, 2, 3, 4, 9) Values: (Apple, Grapes, Banana, Pineapple, Kiwi) {{1: Apple, 3: Banana, 4: Pineapple, 9: Kiwi}} length is 4 Queues are used to implement FIFO(First in First Out) collection. This collection can be manipulated from both ends. A queue in dart is defined as follows: Queue<String> queue = new Queue("Mango", "Apple","Banana") Example: Dart import 'dart:collection';void main() { // Initializing the Set and Adding the values // We can also initialize a queue of a specific type // as Queue<int> q = new Queue(); var geekQueue = new Queue(); geekQueue.addAll([9,1,2,3,4,5,6,1,1,9]); // Adds Element to the Start of the Queue geekQueue.addFirst("GFG"); // Adds Element to the End of the Queue geekQueue.addLast("GFG2"); print(geekQueue); // Removes the first Element geekQueue.removeFirst(); print(geekQueue); // Removes the Last Element geekQueue.removeLast(); print(geekQueue); // printing the first element in the set print('First Element: ${geekQueue.first}'); // Looping over the set for(var el in geekQueue){ print(el); } // Other Operations // length of the set. print('Length: ${geekQueue.length}'); // Deleting an element not present. No Change geekQueue.remove(10); // Deleting an element 9 geekQueue.remove(2); print(geekQueue); } Output: {GFG, 9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2} {9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2} {9, 1, 2, 3, 4, 5, 6, 1, 1, 9} First Element: 9 9 1 2 3 4 5 6 1 1 9 Length: 10 {9, 1, 3, 4, 5, 6, 1, 1, 9} Documentation anikaseth98 akshaysingh98088 Dart-Collection Picked Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ListView Class in Flutter Flutter - Search Bar Flutter - Dialogs Flutter - FutureBuilder Widget Flutter - Flexible Widget Flutter - Pop Up Menu Android Studio Setup for Flutter Development What is widgets in Flutter? Flutter - CircleAvatar Widget Flutter - RichText Widget
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Sep, 2021" }, { "code": null, "e": 252, "s": 53, "text": "Collections are groups of objects that represent a particular element. The dart::collection library is used to implement the collection in dart. There are a variety of collections available in dart." }, { "code": null, "e": 297, "s": 252, "text": "Some of the classes of Dart Collection are –" }, { "code": null, "e": 345, "s": 297, "text": "List<E>: A List is an ordered group of objects." }, { "code": null, "e": 421, "s": 345, "text": "Set<E>: Collection of objects in which each of the objects occurs only once" }, { "code": null, "e": 548, "s": 421, "text": "Map<K, V>: Collection of objects that has a simple key/value pair-based object. The key and value of a map can be of any type." }, { "code": null, "e": 684, "s": 548, "text": "Queue<E>: A Queue is a collection that can be manipulated at both ends. One can iterate over a queue with an Iterator or using forEach." }, { "code": null, "e": 760, "s": 684, "text": "DoubleLinkedQueue<E>: Doubly-linked list based on the queue data structure." }, { "code": null, "e": 818, "s": 760, "text": "HashMap<K, V>: Map based on hash table i.e unordered map." }, { "code": null, "e": 873, "s": 818, "text": "HashSet<E>: Set based on hash table i.e unordered set." }, { "code": null, "e": 938, "s": 873, "text": "LinkedHashMap<K, V>: Similar to HashMap but based on LinkedList." }, { "code": null, "e": 1000, "s": 938, "text": "LinkedHashSet<E>: Similar to HashSet but based on LinkedList." }, { "code": null, "e": 1094, "s": 1000, "text": "LinkedList<E extends LinkedListEntry<E>>: It is a specialized double-linked list of elements." }, { "code": null, "e": 1169, "s": 1094, "text": "LinkedListEntry<E extends LinkedListEntry<E>>: An element of a LinkedList." }, { "code": null, "e": 1216, "s": 1169, "text": "MapBase<K, V>: This is the base class for Map." }, { "code": null, "e": 1284, "s": 1216, "text": "UnmodifiableListView<E>: An unmodifiable List view of another List." }, { "code": null, "e": 1356, "s": 1284, "text": "UnmodifiableMapBase<K, V>: Basic implementation of an unmodifiable Map." }, { "code": null, "e": 1413, "s": 1356, "text": "UnmodifiableMapView<K, V>: Unmodifiable view of the map." }, { "code": null, "e": 1479, "s": 1413, "text": "We will be discussing the 4 basic collections with examples here." }, { "code": null, "e": 1662, "s": 1479, "text": "The list is an ordered group of objects where each object is from one specific type. To define a list in dart, specify the object type inside the angled brackets (<>) as shown below:" }, { "code": null, "e": 1713, "s": 1662, "text": "List<String> fruits = [\"Mango\", \"Apple\", \"Banana\"]" }, { "code": null, "e": 1723, "s": 1713, "text": "Example: " }, { "code": null, "e": 1833, "s": 1723, "text": "Here we have defined a list and performed some common operations along with some basic commonly used methods." }, { "code": null, "e": 1838, "s": 1833, "text": "Dart" }, { "code": "void main() { // creating a new empty List List geekList = new List(); // We can also create a list with a predefined type // as List<int> sampleList = new List() // and also define a list of fixed length as // List<int> sampleList = new List(5) // Adding an element to the geekList geekList.addAll([1,2,3,4,5,\"Apple\"]); print(geekList); // Looping over the list for(var i = 0; i<geekList.length;i++){ print(\"element $i is ${geekList[i]}\"); } // Removing an element from geekList by index geekList.removeAt(2); // Removing an element from geekList by object geekList.remove(\"Apple\"); print(geekList); // Return a reversed version of the list print(geekList.reversed); // Checks if the list is empty print(geekList.isEmpty); // Gives the first element of the list print(geekList.first); // Reassigning the geekList and creating the // elements using Iterable geekList = Iterable<int>.generate(10).toList(); print(geekList);}", "e": 2819, "s": 1838, "text": null }, { "code": null, "e": 2827, "s": 2819, "text": "Output:" }, { "code": null, "e": 3009, "s": 2827, "text": "[1, 2, 3, 4, 5, Apple]\nelement 0 is 1\nelement 1 is 2\nelement 2 is 3\nelement 3 is 4\nelement 4 is 5\nelement 5 is Apple\n[1, 2, 4, 5]\n(5, 4, 2, 1)\nfalse\n1\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 3162, "s": 3009, "text": "Sets are one of the essential part of Dart Collections. A set is defined as an unordered collection of unique objects. To define a set follow the below:" }, { "code": null, "e": 3212, "s": 3162, "text": "Set fruits = Set.from(\"Mango\", \"Apple\", \"Banana\")" }, { "code": null, "e": 3221, "s": 3212, "text": "Example:" }, { "code": null, "e": 3331, "s": 3221, "text": "As discussed earlier a set stores a group of objects that are not repeating. A sample program is shown below." }, { "code": null, "e": 3336, "s": 3331, "text": "Dart" }, { "code": "void main() { // Initializing the Set and Adding the values Set geekSet = new Set(); geekSet.addAll([9,1,2,3,4,5,6,1,1,9]); // Looping over the set for(var el in geekSet){ print(el); } // length of the set. print('Length: ${geekSet.length}'); // printing the first element in the set print('First Element: ${geekSet.first}'); // Deleting an element not present. No Change geekSet.remove(10); // Deleting an element 9 geekSet.remove(9); print(geekSet);}", "e": 3829, "s": 3336, "text": null }, { "code": null, "e": 3837, "s": 3829, "text": "Output:" }, { "code": null, "e": 3897, "s": 3837, "text": "9\n1\n2\n3\n4\n5\n6\nLength: 7\nFirst Element: 9\n{1, 2, 3, 4, 5, 6}" }, { "code": null, "e": 4103, "s": 3897, "text": "In Dart, Maps are unordered key-value pair collection that sets an associate key to the values within. To define a Map, specify the key type and the value type inside the angle brackets(<>) as shown below:" }, { "code": null, "e": 4165, "s": 4103, "text": "Map<int, string> fruits = {1: \"Mango\", 2:\"Apple\", 3:\"Banana\"}" }, { "code": null, "e": 4174, "s": 4165, "text": "Example:" }, { "code": null, "e": 4260, "s": 4174, "text": "The map collection stores the objects as a key-value pair. An example is shown below." }, { "code": null, "e": 4265, "s": 4260, "text": "Dart" }, { "code": "void main() { // Initializing the map with sample values. var geekMap = {1:\"Apple\",2:\"Mango\",3:\"Banana\"}; print(geekMap); // Adding elements by different methods. geekMap.addAll({4:'Pineapple',2:'Grapes'}); geekMap[9]=\"Kiwi\"; print(geekMap); // printing key and values print('Keys: ${geekMap.keys} \\nValues: ${geekMap.values}'); // removing an element from the map by its key geekMap.remove(2); // printing the map and its length print('{$geekMap} length is ${geekMap.length}');}", "e": 4773, "s": 4265, "text": null }, { "code": null, "e": 4781, "s": 4773, "text": "Output:" }, { "code": null, "e": 5000, "s": 4781, "text": "{1: Apple, 2: Mango, 3: Banana}\n{1: Apple, 2: Grapes, 3: Banana, 4: Pineapple, 9: Kiwi}\nKeys: (1, 2, 3, 4, 9) \nValues: (Apple, Grapes, Banana, Pineapple, Kiwi)\n{{1: Apple, 3: Banana, 4: Pineapple, 9: Kiwi}} length is 4" }, { "code": null, "e": 5156, "s": 5000, "text": "Queues are used to implement FIFO(First in First Out) collection. This collection can be manipulated from both ends. A queue in dart is defined as follows:" }, { "code": null, "e": 5215, "s": 5156, "text": "Queue<String> queue = new Queue(\"Mango\", \"Apple\",\"Banana\")" }, { "code": null, "e": 5224, "s": 5215, "text": "Example:" }, { "code": null, "e": 5229, "s": 5224, "text": "Dart" }, { "code": "import 'dart:collection';void main() { // Initializing the Set and Adding the values // We can also initialize a queue of a specific type // as Queue<int> q = new Queue(); var geekQueue = new Queue(); geekQueue.addAll([9,1,2,3,4,5,6,1,1,9]); // Adds Element to the Start of the Queue geekQueue.addFirst(\"GFG\"); // Adds Element to the End of the Queue geekQueue.addLast(\"GFG2\"); print(geekQueue); // Removes the first Element geekQueue.removeFirst(); print(geekQueue); // Removes the Last Element geekQueue.removeLast(); print(geekQueue); // printing the first element in the set print('First Element: ${geekQueue.first}'); // Looping over the set for(var el in geekQueue){ print(el); } // Other Operations // length of the set. print('Length: ${geekQueue.length}'); // Deleting an element not present. No Change geekQueue.remove(10); // Deleting an element 9 geekQueue.remove(2); print(geekQueue); }", "e": 6197, "s": 5229, "text": null }, { "code": null, "e": 6205, "s": 6197, "text": "Output:" }, { "code": null, "e": 6406, "s": 6205, "text": "{GFG, 9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2}\n{9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2}\n{9, 1, 2, 3, 4, 5, 6, 1, 1, 9}\nFirst Element: 9\n9\n1\n2\n3\n4\n5\n6\n1\n1\n9\nLength: 10\n{9, 1, 3, 4, 5, 6, 1, 1, 9}\nDocumentation " }, { "code": null, "e": 6418, "s": 6406, "text": "anikaseth98" }, { "code": null, "e": 6435, "s": 6418, "text": "akshaysingh98088" }, { "code": null, "e": 6451, "s": 6435, "text": "Dart-Collection" }, { "code": null, "e": 6458, "s": 6451, "text": "Picked" }, { "code": null, "e": 6463, "s": 6458, "text": "Dart" }, { "code": null, "e": 6561, "s": 6463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6587, "s": 6561, "text": "ListView Class in Flutter" }, { "code": null, "e": 6608, "s": 6587, "text": "Flutter - Search Bar" }, { "code": null, "e": 6626, "s": 6608, "text": "Flutter - Dialogs" }, { "code": null, "e": 6657, "s": 6626, "text": "Flutter - FutureBuilder Widget" }, { "code": null, "e": 6683, "s": 6657, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 6705, "s": 6683, "text": "Flutter - Pop Up Menu" }, { "code": null, "e": 6750, "s": 6705, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 6778, "s": 6750, "text": "What is widgets in Flutter?" }, { "code": null, "e": 6808, "s": 6778, "text": "Flutter - CircleAvatar Widget" } ]
Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
10 Jun, 2022 Given a string str of lowercase English alphabets and an integer m. The task is to count how many positions are there in the string such that if you partition the string into two non-empty sub-strings, there are at least m characters with the same frequency in both the sub-strings. The characters need to be present in the string str.Examples: Input: str = “aabbccaa”, m = 2 Output: 2 The string has length 8, so there are 7 positions available to perform the partition. i.e. a|a|b|b|c|c|a|a Only two partitions are possible which satisfy the given constraints. aab|bccaa – On the left half of the separator, ‘a’ has frequency 2 and ‘b’ has frequency 1 which is same as that of the right half. aabbc|caa – On the left half of the separator, ‘a’ has frequency 2 and ‘c’ has frequency 1 which is same as that of the right half.Input: str = “aabbaa”, m = 2 Output: 1 Approach: For each partition position, calculate the frequencies of each of the characters of the string in both the partitions. Then calculate the number of characters having same frequency in both partitions. If the count of such characters is at least m then add 1 to the required count of partitions.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of ways// to partition the given so that the// given condition is satisfiedint countWays(string str, int m){ // Hashset to store unique characters // in the given string set<char> s; for (int i = 0; i < str.length(); i++) s.insert(str[i]); // To store the number of ways // to partition the string int result = 0; for (int i = 1; i < str.length(); i++) { // Hashmaps to store frequency of characters // of both the partitions map<char, int> first_map, second_map; // Iterate in the first partition for (int j = 0; j < i; j++) // If character already exists in the hashmap // then increase it's frequency first_map[str[j]]++; // Iterate in the second partition for (int k = 0; k < str.length(); k++) // If character already exists in the hashmap // then increase it's frequency second_map[str[k]]++; // Iterator for HashSet set<char>::iterator itr = s.begin(); // To store the count of characters that have // equal frequencies in both the partitions int total_count = 0; while (++itr != s.end()) { // first_count and second_count keeps track // of the frequencies of each character int first_count = 0, second_count = 0; char ch = *(itr); // Frequency of the character // in the first partition if (first_map.find(ch) != first_map.end()) first_count = first_map[ch]; // Frequency of the character // in the second partition if (second_map.find(ch) != second_map.end()) second_count = second_map[ch]; // Check if frequency is same // in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; } // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result;} // Driver codeint main(int argc, char const *argv[]){ string str = "aabbccaa"; int m = 2; cout << countWays(str, m) << endl; return 0;} // This code is contributed by// sanjeev2552 // Java implementation of the approachimport java.util.*; class GFG { // Function to return the number of ways // to partition the given so that the // given condition is satisfied static int countWays(String str, int m) { // Hashset to store unique characters // in the given string HashSet<Character> set = new HashSet<Character>(); for (int i = 0; i < str.length(); i++) set.add(str.charAt(i)); // To store the number of ways // to partition the string int result = 0; for (int i = 1; i < str.length(); i++) { // Hashmaps to store frequency of characters // of both the partitions HashMap<Character, Integer> first_map = new HashMap<Character, Integer>(); HashMap<Character, Integer> second_map = new HashMap<Character, Integer>(); // Iterate in the first partition for (int j = 0; j < i; j++) { // If character already exists in the hashmap // then increase it's frequency if (first_map.containsKey(str.charAt(j))) first_map.put(str.charAt(j), (first_map.get(str.charAt(j)) + 1)); // Else create an entry for it in the Hashmap else first_map.put(str.charAt(j), 1); } // Iterate in the second partition for (int k = i; k < str.length(); k++) { // If character already exists in the hashmap // then increase it's frequency if (second_map.containsKey(str.charAt(k))) second_map.put(str.charAt(k), (second_map.get(str.charAt(k)) + 1)); // Else create an entry for it in the Hashmap else second_map.put(str.charAt(k), 1); } // Iterator for HashSet Iterator itr = set.iterator(); // To store the count of characters that have // equal frequencies in both the partitions int total_count = 0; while (itr.hasNext()) { // first_count and second_count keeps track // of the frequencies of each character int first_count = 0, second_count = 0; char ch = (char)itr.next(); // Frequency of the character // in the first partition if (first_map.containsKey(ch)) first_count = first_map.get(ch); // Frequency of the character // in the second partition if (second_map.containsKey(ch)) second_count = second_map.get(ch); // Check if frequency is same in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; } // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result; } // Driver code public static void main(String[] args) { String str = "aabbccaa"; int m = 2; System.out.println(countWays(str, m)); }} # Python3 implementation of the approachfrom collections import defaultdict # Function to return the number of ways# to partition the given so that the# given condition is satisfieddef countWays(string, m): # Hashset to store unique # characters in the given string Set = set() for i in range(0, len(string)): Set.add(string[i]) # To store the number of ways # to partition the string result = 0 for i in range(1, len(string)): # Hashmaps to store frequency of # characters of both the partitions first_map = defaultdict(lambda:0) second_map = defaultdict(lambda:0) # Iterate in the first partition for j in range(0, i): first_map[string[j]] += 1 # Iterate in the second partition for k in range(i, len(string)): second_map[string[k]] += 1 # To store the count of characters that have # equal frequencies in both the partitions total_count = 0 for ch in Set: # first_count and second_count keeps track # of the frequencies of each character first_count, second_count = 0, 0 # Frequency of the character # in the first partition if ch in first_map: first_count = first_map[ch] # Frequency of the character # in the second partition if ch in second_map: second_count = second_map[ch] # Check if frequency is same in both the partitions if first_count == second_count and first_count != 0: total_count += 1 # Check if the condition is satisfied # for the current partition if total_count >= m: result += 1 return result # Driver codeif __name__ == "__main__": string = "aabbccaa" m = 2 print(countWays(string, m)) # This code is contributed by Rituraj Jain // C# implementation of the approachusing System;using System.Collections.Generic; public class GFG { // Function to return the number of ways // to partition the given so that the // given condition is satisfied static int countWays(String str, int m) { // Hashset to store unique characters // in the given string HashSet<char> set = new HashSet<char>(); for (int i = 0; i < str.Length; i++) set.Add(str[i]); // To store the number of ways // to partition the string int result = 0; for (int i = 1; i < str.Length; i++) { // Hashmaps to store frequency of characters // of both the partitions Dictionary<char, int> first_map = new Dictionary<char, int>(); Dictionary<char, int> second_map = new Dictionary<char, int>(); // Iterate in the first partition for (int j = 0; j < i; j++) { // If character already exists in the hashmap // then increase it's frequency if (first_map.ContainsKey(str[j])) first_map[str[j]] = (first_map[str[j]] + 1); // Else create an entry for it in the Hashmap else first_map.Add(str[j], 1); } // Iterate in the second partition for (int k = i; k < str.Length; k++) { // If character already exists in the hashmap // then increase it's frequency if (second_map.ContainsKey(str[k])) second_map[str[k]] = (second_map[str[k]] + 1); // Else create an entry for it in the Hashmap else second_map.Add(str[k], 1); } // To store the count of characters that have // equal frequencies in both the partitions int total_count = 0; // Iterator for HashSet foreach (int itr in set) { // first_count and second_count keeps track // of the frequencies of each character int first_count = 0, second_count = 0; char ch = (char)itr; // Frequency of the character // in the first partition if (first_map.ContainsKey(ch)) first_count = first_map[ch]; // Frequency of the character // in the second partition if (second_map.ContainsKey(ch)) second_count = second_map[ch]; // Check if frequency is same in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; } // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result; } // Driver code public static void Main(String[] args) { String str = "aabbccaa"; int m = 2; Console.WriteLine(countWays(str, m)); }} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to return the number of ways// to partition the given so that the// given condition is satisfiedfunction countWays(str, m){ // Hashset to store unique characters // in the given string var s = new Set(); for (var i = 0; i < str.length; i++) s.add(str[i]); // To store the number of ways // to partition the string var result = 0; for (var i = 1; i < str.length; i++) { // Hashmaps to store frequency of characters // of both the partitions var first_map = new Map(), second_map = new Map(); // Iterate in the first partition for (var j = 0; j < i; j++) // If character already exists in the hashmap // then increase it's frequency if(first_map.has(str[j])) first_map.set(str[j], first_map.get(str[j])+1) else first_map.set(str[j], 1) // Iterate in the second partition for (var k = 0; k < str.length; k++) // If character already exists in the hashmap // then increase it's frequency if(second_map.has(str[k])) second_map.set(str[k], second_map.get(str[k])+1) else second_map.set(str[k], 1) // To store the count of characters that have // equal frequencies in both the partitions var total_count = 0; s.forEach(itr => { // first_count and second_count keeps track // of the frequencies of each character var first_count = 0, second_count = 0; var ch = itr; // Frequency of the character // in the first partition if (first_map.has(ch)) first_count = first_map.get(ch); // Frequency of the character // in the second partition if (second_map.has(ch)) second_count = second_map.get(ch); // Check if frequency is same // in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; }); // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result;} // Driver codevar str = "aabbccaa";var m = 2;document.write( countWays(str, m)); // This code is contributed by itsok.</script> 2 Time Complexity: O(n*n*log(n)), as nested loops are used for iterationAuxiliary Space: O(n), as extra space of size n is used to make a set and map rituraj_jain Divyank_Sheth sanjeev2552 Rajput-Ji itsok singhh3010 frequency-counting HashSet Java 8 Thoughtworks Hash Strings Thoughtworks Hash Strings 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": 54, "s": 26, "text": "\n10 Jun, 2022" }, { "code": null, "e": 401, "s": 54, "text": "Given a string str of lowercase English alphabets and an integer m. The task is to count how many positions are there in the string such that if you partition the string into two non-empty sub-strings, there are at least m characters with the same frequency in both the sub-strings. The characters need to be present in the string str.Examples: " }, { "code": null, "e": 923, "s": 401, "text": "Input: str = “aabbccaa”, m = 2 Output: 2 The string has length 8, so there are 7 positions available to perform the partition. i.e. a|a|b|b|c|c|a|a Only two partitions are possible which satisfy the given constraints. aab|bccaa – On the left half of the separator, ‘a’ has frequency 2 and ‘b’ has frequency 1 which is same as that of the right half. aabbc|caa – On the left half of the separator, ‘a’ has frequency 2 and ‘c’ has frequency 1 which is same as that of the right half.Input: str = “aabbaa”, m = 2 Output: 1 " }, { "code": null, "e": 1282, "s": 925, "text": "Approach: For each partition position, calculate the frequencies of each of the characters of the string in both the partitions. Then calculate the number of characters having same frequency in both partitions. If the count of such characters is at least m then add 1 to the required count of partitions.Below is the implementation of the above approach: " }, { "code": null, "e": 1286, "s": 1282, "text": "C++" }, { "code": null, "e": 1291, "s": 1286, "text": "Java" }, { "code": null, "e": 1299, "s": 1291, "text": "Python3" }, { "code": null, "e": 1302, "s": 1299, "text": "C#" }, { "code": null, "e": 1313, "s": 1302, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of ways// to partition the given so that the// given condition is satisfiedint countWays(string str, int m){ // Hashset to store unique characters // in the given string set<char> s; for (int i = 0; i < str.length(); i++) s.insert(str[i]); // To store the number of ways // to partition the string int result = 0; for (int i = 1; i < str.length(); i++) { // Hashmaps to store frequency of characters // of both the partitions map<char, int> first_map, second_map; // Iterate in the first partition for (int j = 0; j < i; j++) // If character already exists in the hashmap // then increase it's frequency first_map[str[j]]++; // Iterate in the second partition for (int k = 0; k < str.length(); k++) // If character already exists in the hashmap // then increase it's frequency second_map[str[k]]++; // Iterator for HashSet set<char>::iterator itr = s.begin(); // To store the count of characters that have // equal frequencies in both the partitions int total_count = 0; while (++itr != s.end()) { // first_count and second_count keeps track // of the frequencies of each character int first_count = 0, second_count = 0; char ch = *(itr); // Frequency of the character // in the first partition if (first_map.find(ch) != first_map.end()) first_count = first_map[ch]; // Frequency of the character // in the second partition if (second_map.find(ch) != second_map.end()) second_count = second_map[ch]; // Check if frequency is same // in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; } // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result;} // Driver codeint main(int argc, char const *argv[]){ string str = \"aabbccaa\"; int m = 2; cout << countWays(str, m) << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 3729, "s": 1313, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to return the number of ways // to partition the given so that the // given condition is satisfied static int countWays(String str, int m) { // Hashset to store unique characters // in the given string HashSet<Character> set = new HashSet<Character>(); for (int i = 0; i < str.length(); i++) set.add(str.charAt(i)); // To store the number of ways // to partition the string int result = 0; for (int i = 1; i < str.length(); i++) { // Hashmaps to store frequency of characters // of both the partitions HashMap<Character, Integer> first_map = new HashMap<Character, Integer>(); HashMap<Character, Integer> second_map = new HashMap<Character, Integer>(); // Iterate in the first partition for (int j = 0; j < i; j++) { // If character already exists in the hashmap // then increase it's frequency if (first_map.containsKey(str.charAt(j))) first_map.put(str.charAt(j), (first_map.get(str.charAt(j)) + 1)); // Else create an entry for it in the Hashmap else first_map.put(str.charAt(j), 1); } // Iterate in the second partition for (int k = i; k < str.length(); k++) { // If character already exists in the hashmap // then increase it's frequency if (second_map.containsKey(str.charAt(k))) second_map.put(str.charAt(k), (second_map.get(str.charAt(k)) + 1)); // Else create an entry for it in the Hashmap else second_map.put(str.charAt(k), 1); } // Iterator for HashSet Iterator itr = set.iterator(); // To store the count of characters that have // equal frequencies in both the partitions int total_count = 0; while (itr.hasNext()) { // first_count and second_count keeps track // of the frequencies of each character int first_count = 0, second_count = 0; char ch = (char)itr.next(); // Frequency of the character // in the first partition if (first_map.containsKey(ch)) first_count = first_map.get(ch); // Frequency of the character // in the second partition if (second_map.containsKey(ch)) second_count = second_map.get(ch); // Check if frequency is same in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; } // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result; } // Driver code public static void main(String[] args) { String str = \"aabbccaa\"; int m = 2; System.out.println(countWays(str, m)); }}", "e": 7067, "s": 3729, "text": null }, { "code": "# Python3 implementation of the approachfrom collections import defaultdict # Function to return the number of ways# to partition the given so that the# given condition is satisfieddef countWays(string, m): # Hashset to store unique # characters in the given string Set = set() for i in range(0, len(string)): Set.add(string[i]) # To store the number of ways # to partition the string result = 0 for i in range(1, len(string)): # Hashmaps to store frequency of # characters of both the partitions first_map = defaultdict(lambda:0) second_map = defaultdict(lambda:0) # Iterate in the first partition for j in range(0, i): first_map[string[j]] += 1 # Iterate in the second partition for k in range(i, len(string)): second_map[string[k]] += 1 # To store the count of characters that have # equal frequencies in both the partitions total_count = 0 for ch in Set: # first_count and second_count keeps track # of the frequencies of each character first_count, second_count = 0, 0 # Frequency of the character # in the first partition if ch in first_map: first_count = first_map[ch] # Frequency of the character # in the second partition if ch in second_map: second_count = second_map[ch] # Check if frequency is same in both the partitions if first_count == second_count and first_count != 0: total_count += 1 # Check if the condition is satisfied # for the current partition if total_count >= m: result += 1 return result # Driver codeif __name__ == \"__main__\": string = \"aabbccaa\" m = 2 print(countWays(string, m)) # This code is contributed by Rituraj Jain", "e": 9017, "s": 7067, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; public class GFG { // Function to return the number of ways // to partition the given so that the // given condition is satisfied static int countWays(String str, int m) { // Hashset to store unique characters // in the given string HashSet<char> set = new HashSet<char>(); for (int i = 0; i < str.Length; i++) set.Add(str[i]); // To store the number of ways // to partition the string int result = 0; for (int i = 1; i < str.Length; i++) { // Hashmaps to store frequency of characters // of both the partitions Dictionary<char, int> first_map = new Dictionary<char, int>(); Dictionary<char, int> second_map = new Dictionary<char, int>(); // Iterate in the first partition for (int j = 0; j < i; j++) { // If character already exists in the hashmap // then increase it's frequency if (first_map.ContainsKey(str[j])) first_map[str[j]] = (first_map[str[j]] + 1); // Else create an entry for it in the Hashmap else first_map.Add(str[j], 1); } // Iterate in the second partition for (int k = i; k < str.Length; k++) { // If character already exists in the hashmap // then increase it's frequency if (second_map.ContainsKey(str[k])) second_map[str[k]] = (second_map[str[k]] + 1); // Else create an entry for it in the Hashmap else second_map.Add(str[k], 1); } // To store the count of characters that have // equal frequencies in both the partitions int total_count = 0; // Iterator for HashSet foreach (int itr in set) { // first_count and second_count keeps track // of the frequencies of each character int first_count = 0, second_count = 0; char ch = (char)itr; // Frequency of the character // in the first partition if (first_map.ContainsKey(ch)) first_count = first_map[ch]; // Frequency of the character // in the second partition if (second_map.ContainsKey(ch)) second_count = second_map[ch]; // Check if frequency is same in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; } // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result; } // Driver code public static void Main(String[] args) { String str = \"aabbccaa\"; int m = 2; Console.WriteLine(countWays(str, m)); }} // This code is contributed by Rajput-Ji", "e": 12276, "s": 9017, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the number of ways// to partition the given so that the// given condition is satisfiedfunction countWays(str, m){ // Hashset to store unique characters // in the given string var s = new Set(); for (var i = 0; i < str.length; i++) s.add(str[i]); // To store the number of ways // to partition the string var result = 0; for (var i = 1; i < str.length; i++) { // Hashmaps to store frequency of characters // of both the partitions var first_map = new Map(), second_map = new Map(); // Iterate in the first partition for (var j = 0; j < i; j++) // If character already exists in the hashmap // then increase it's frequency if(first_map.has(str[j])) first_map.set(str[j], first_map.get(str[j])+1) else first_map.set(str[j], 1) // Iterate in the second partition for (var k = 0; k < str.length; k++) // If character already exists in the hashmap // then increase it's frequency if(second_map.has(str[k])) second_map.set(str[k], second_map.get(str[k])+1) else second_map.set(str[k], 1) // To store the count of characters that have // equal frequencies in both the partitions var total_count = 0; s.forEach(itr => { // first_count and second_count keeps track // of the frequencies of each character var first_count = 0, second_count = 0; var ch = itr; // Frequency of the character // in the first partition if (first_map.has(ch)) first_count = first_map.get(ch); // Frequency of the character // in the second partition if (second_map.has(ch)) second_count = second_map.get(ch); // Check if frequency is same // in both the partitions if (first_count == second_count && first_count != 0) total_count += 1; }); // Check if the condition is satisfied // for the current partition if (total_count >= m) result += 1; } return result;} // Driver codevar str = \"aabbccaa\";var m = 2;document.write( countWays(str, m)); // This code is contributed by itsok.</script>", "e": 14740, "s": 12276, "text": null }, { "code": null, "e": 14742, "s": 14740, "text": "2" }, { "code": null, "e": 14892, "s": 14744, "text": "Time Complexity: O(n*n*log(n)), as nested loops are used for iterationAuxiliary Space: O(n), as extra space of size n is used to make a set and map" }, { "code": null, "e": 14905, "s": 14892, "text": "rituraj_jain" }, { "code": null, "e": 14919, "s": 14905, "text": "Divyank_Sheth" }, { "code": null, "e": 14931, "s": 14919, "text": "sanjeev2552" }, { "code": null, "e": 14941, "s": 14931, "text": "Rajput-Ji" }, { "code": null, "e": 14947, "s": 14941, "text": "itsok" }, { "code": null, "e": 14958, "s": 14947, "text": "singhh3010" }, { "code": null, "e": 14977, "s": 14958, "text": "frequency-counting" }, { "code": null, "e": 14985, "s": 14977, "text": "HashSet" }, { "code": null, "e": 14992, "s": 14985, "text": "Java 8" }, { "code": null, "e": 15005, "s": 14992, "text": "Thoughtworks" }, { "code": null, "e": 15010, "s": 15005, "text": "Hash" }, { "code": null, "e": 15018, "s": 15010, "text": "Strings" }, { "code": null, "e": 15031, "s": 15018, "text": "Thoughtworks" }, { "code": null, "e": 15036, "s": 15031, "text": "Hash" }, { "code": null, "e": 15044, "s": 15036, "text": "Strings" }, { "code": null, "e": 15142, "s": 15044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15180, "s": 15142, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 15221, "s": 15180, "text": "Real-time application of Data Structures" }, { "code": null, "e": 15277, "s": 15221, "text": "Find k numbers with most occurrences in the given array" }, { "code": null, "e": 15324, "s": 15277, "text": "Find the length of largest subarray with 0 sum" }, { "code": null, "e": 15346, "s": 15324, "text": "Non-Repeating Element" }, { "code": null, "e": 15392, "s": 15346, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 15417, "s": 15392, "text": "Reverse a string in Java" }, { "code": null, "e": 15477, "s": 15417, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 15492, "s": 15477, "text": "C++ Data Types" } ]
Set Aspect Ratio of Scatter Plot and Bar Plot in R Programming - Using asp in plot() Function - GeeksforGeeks
30 Jun, 2020 asp is a parameter of the plot() function in R Language is used to set aspect ratio of plots (Scatterplot and Barplot). Aspect ratio is defined as proportional relationship between width and height of the plot axes. Syntax: plot(x, y, asp ) Parameters:x, y: Coordinates of x and y axisasp: Aspect ratio Example 1: # Set seed for reproducibilityset.seed(86000) # Create random x variablex <- runif(120) # Create y variable correlated with xy <- x + runif(120) # Plot without setting aspect ratioplot(x, y) # Plot with asp = 5plot(x, y, asp = 5) Output: Plot Without Aspect Ratio: Plot with Aspect Ratio: Example 2: # Set seed for reproducibilityset.seed(86000) # Create random x variablex <- runif(120) # Create y variable correlated with xy <- x + runif(120) # Regular barplotbarplot(x) # Barplot with aspect ratio of 5barplot(x, asp = 5) Output: Bar Plot Without Aspect Ratio: Bar Plot with Aspect Ratio: Here, the asp option increases the width of the y-axis. R Plot-Function R Statistics-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n30 Jun, 2020" }, { "code": null, "e": 26703, "s": 26487, "text": "asp is a parameter of the plot() function in R Language is used to set aspect ratio of plots (Scatterplot and Barplot). Aspect ratio is defined as proportional relationship between width and height of the plot axes." }, { "code": null, "e": 26728, "s": 26703, "text": "Syntax: plot(x, y, asp )" }, { "code": null, "e": 26790, "s": 26728, "text": "Parameters:x, y: Coordinates of x and y axisasp: Aspect ratio" }, { "code": null, "e": 26801, "s": 26790, "text": "Example 1:" }, { "code": "# Set seed for reproducibilityset.seed(86000) # Create random x variablex <- runif(120) # Create y variable correlated with xy <- x + runif(120) # Plot without setting aspect ratioplot(x, y) # Plot with asp = 5plot(x, y, asp = 5) ", "e": 27067, "s": 26801, "text": null }, { "code": null, "e": 27075, "s": 27067, "text": "Output:" }, { "code": null, "e": 27102, "s": 27075, "text": "Plot Without Aspect Ratio:" }, { "code": null, "e": 27126, "s": 27102, "text": "Plot with Aspect Ratio:" }, { "code": null, "e": 27137, "s": 27126, "text": "Example 2:" }, { "code": "# Set seed for reproducibilityset.seed(86000) # Create random x variablex <- runif(120) # Create y variable correlated with xy <- x + runif(120) # Regular barplotbarplot(x) # Barplot with aspect ratio of 5barplot(x, asp = 5) ", "e": 27423, "s": 27137, "text": null }, { "code": null, "e": 27431, "s": 27423, "text": "Output:" }, { "code": null, "e": 27462, "s": 27431, "text": "Bar Plot Without Aspect Ratio:" }, { "code": null, "e": 27490, "s": 27462, "text": "Bar Plot with Aspect Ratio:" }, { "code": null, "e": 27546, "s": 27490, "text": "Here, the asp option increases the width of the y-axis." }, { "code": null, "e": 27562, "s": 27546, "text": "R Plot-Function" }, { "code": null, "e": 27584, "s": 27562, "text": "R Statistics-Function" }, { "code": null, "e": 27595, "s": 27584, "text": "R Language" }, { "code": null, "e": 27693, "s": 27595, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27745, "s": 27693, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27780, "s": 27745, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27818, "s": 27780, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27876, "s": 27818, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27919, "s": 27876, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27968, "s": 27919, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28005, "s": 27968, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28031, "s": 28005, "text": "Time Series Analysis in R" }, { "code": null, "e": 28048, "s": 28031, "text": "R - if statement" } ]
exp() function C++ - GeeksforGeeks
12 May, 2022 The exp() function in C++ returns the exponential (Euler’s number) e (or 2.71828) raised to the given argument. Syntax for returning exponential e: result=exp() Parameter: The function can take any value i.e, positive, negative or zero in its parameter and returns result in int, double or float or long double. Return Value: The exp() function returns the value in the range of [0, inf]. Error: It shows error when we pass more than one argument in exp function Application: Given below is an example of application of exp() function CPP #include <bits/stdc++.h>using namespace std; // function to explain use of exp() functiondouble application(double x){ double result = exp(x); cout << "exp(x) = " << result << endl; return result;} // driver programint main(){ double x = 10; cout << application(x); return 0;} Output: exp(x) = 22026.5 Applications of e (mathematical constant): Compound Interest : An account that starts at $1 and offers an annual interest rate of R will, after t years, yield eRt dollars with continuous compounding (Here R is the decimal equivalent of the rate of interest expressed as a percentage, so for 5% interest, R = 5/100 = 0.05) Value of below expression is e. The probability that a gambler never wins if he/she tries million times in a game where chances of winning in every trial is one by million is close to 1/e. The number e is the sum of the infinite series Source : Wiki solankinilesh61 surinderdawra388 CPP-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Constructors in C++ Templates in C++ with Examples Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++
[ { "code": null, "e": 25826, "s": 25798, "text": "\n12 May, 2022" }, { "code": null, "e": 25938, "s": 25826, "text": "The exp() function in C++ returns the exponential (Euler’s number) e (or 2.71828) raised to the given argument." }, { "code": null, "e": 25987, "s": 25938, "text": "Syntax for returning exponential e: result=exp()" }, { "code": null, "e": 26362, "s": 25987, "text": "Parameter: The function can take any value i.e, positive, negative or zero in its parameter and returns result in int, double or float or long double. Return Value: The exp() function returns the value in the range of [0, inf]. Error: It shows error when we pass more than one argument in exp function Application: Given below is an example of application of exp() function " }, { "code": null, "e": 26366, "s": 26362, "text": "CPP" }, { "code": "#include <bits/stdc++.h>using namespace std; // function to explain use of exp() functiondouble application(double x){ double result = exp(x); cout << \"exp(x) = \" << result << endl; return result;} // driver programint main(){ double x = 10; cout << application(x); return 0;}", "e": 26661, "s": 26366, "text": null }, { "code": null, "e": 26669, "s": 26661, "text": "Output:" }, { "code": null, "e": 26686, "s": 26669, "text": "exp(x) = 22026.5" }, { "code": null, "e": 26729, "s": 26686, "text": "Applications of e (mathematical constant):" }, { "code": null, "e": 27008, "s": 26729, "text": "Compound Interest : An account that starts at $1 and offers an annual interest rate of R will, after t years, yield eRt dollars with continuous compounding (Here R is the decimal equivalent of the rate of interest expressed as a percentage, so for 5% interest, R = 5/100 = 0.05)" }, { "code": null, "e": 27041, "s": 27008, "text": "Value of below expression is e. " }, { "code": null, "e": 27198, "s": 27041, "text": "The probability that a gambler never wins if he/she tries million times in a game where chances of winning in every trial is one by million is close to 1/e." }, { "code": null, "e": 27246, "s": 27198, "text": "The number e is the sum of the infinite series " }, { "code": null, "e": 27260, "s": 27246, "text": "Source : Wiki" }, { "code": null, "e": 27276, "s": 27260, "text": "solankinilesh61" }, { "code": null, "e": 27293, "s": 27276, "text": "surinderdawra388" }, { "code": null, "e": 27305, "s": 27293, "text": "CPP-Library" }, { "code": null, "e": 27309, "s": 27305, "text": "C++" }, { "code": null, "e": 27313, "s": 27309, "text": "CPP" }, { "code": null, "e": 27411, "s": 27313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27430, "s": 27411, "text": "Inheritance in C++" }, { "code": null, "e": 27473, "s": 27430, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27497, "s": 27473, "text": "C++ Classes and Objects" }, { "code": null, "e": 27524, "s": 27497, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27548, "s": 27524, "text": "Virtual Function in C++" }, { "code": null, "e": 27568, "s": 27548, "text": "Constructors in C++" }, { "code": null, "e": 27599, "s": 27568, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27627, "s": 27599, "text": "Operator Overloading in C++" }, { "code": null, "e": 27655, "s": 27627, "text": "Socket Programming in C/C++" } ]
Sink Odd nodes in Binary Tree - GeeksforGeeks
02 Mar, 2022 Given a Binary Tree having odd and even elements, sink all its odd valued nodes such that no node with odd value could be parent of node with even value. There can be multiple outputs for a given tree, we need to print one of them. It is always possible to convert a tree (Note that a node with even nodes and all odd nodes follows the rule) Input : 1 / \ 2 3 Output 2 2 / \ OR / \ 1 3 3 1 Input : 1 / \ 5 8 / \ / \ 2 4 9 10 Output : 2 4 / \ / \ 4 8 OR 2 8 OR .. (any tree with / \ / \ / \ / \ same keys and 5 1 9 10 5 1 9 10 no odd is parent of even) We strongly recommend you to minimize your browser and try this yourself first.Basically, we need to swap odd value of a node with even value of one of its descendants. The idea is to traverse the tree in postorder fashion. Since we process in postorder, for each odd node encountered, its left and right subtrees are already balanced (sinked), we check if it’s an odd node and its left or right child has an even value. If even value is found, we swap the node’s data with that of even child node and call the procedure on the even child to balance the subtree. If both children have odd values, that means that all its descendants are odd.Below is the implementation of the idea. C++ Python3 // Program to sink odd nodes to the bottom of// binary tree#include<bits/stdc++.h>using namespace std; // A binary tree nodestruct Node{ int data; Node* left, *right;}; // Helper function to allocates a new nodeNode* newnode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return node;} // Helper function to check if node is leaf nodebool isLeaf(Node *root){ return (root->left == NULL && root->right == NULL);} // A recursive method to sink a tree with odd root// This method assumes that the subtrees are already// sinked. This method is similar to Heapify of// Heap-Sortvoid sink(Node *&root){ // If NULL or is a leaf, do nothing if (root == NULL || isLeaf(root)) return; // if left subtree exists and left child is even if (root->left && !(root->left->data & 1)) { // swap root's data with left child and // fix left subtree swap(root->data, root->left->data); sink(root->left); } // if right subtree exists and right child is even else if(root->right && !(root->right->data & 1)) { // swap root's data with right child and // fix right subtree swap(root->data, root->right->data); sink(root->right); }} // Function to sink all odd nodes to the bottom of binary// tree. It does a postorder traversal and calls sink()// if any odd node is foundvoid sinkOddNodes(Node* &root){ // If NULL or is a leaf, do nothing if (root == NULL || isLeaf(root)) return; // Process left and right subtrees before this node sinkOddNodes(root->left); sinkOddNodes(root->right); // If root is odd, sink it if (root->data & 1) sink(root);} // Helper function to do Level Order Traversal of// Binary Tree level by level. This function is used// here only for showing modified tree.void printLevelOrder(Node* root){ queue<Node*> q; q.push(root); // Do Level order traversal while (!q.empty()) { int nodeCount = q.size(); // Print one level at a time while (nodeCount) { Node *node = q.front(); printf("%d ", node->data); q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } // Line separator for levels printf("\n"); }} // Driver program to test above functionsint main(){ /* Constructed binary tree is 1 / \ 5 8 / \ / \ 2 4 9 10 */ Node *root = newnode(1); root->left = newnode(5); root->right = newnode(8); root->left->left = newnode(2); root->left->right = newnode(4); root->right->left = newnode(9); root->right->right = newnode(10); sinkOddNodes(root); printf("Level order traversal of modified tree\n"); printLevelOrder(root); return 0;} # Python3 program to sink odd nodes# to the bottom of binary tree # A binary tree node# Helper function to allocates a new nodeclass newnode: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Helper function to check# if node is leaf nodedef isLeaf(root): return (root.left == None and root.right == None) # A recursive method to sink a tree with odd root# This method assumes that the subtrees are# already sinked. This method is similar to# Heapify of Heap-Sortdef sink(root): # If None or is a leaf, do nothing if (root == None or isLeaf(root)): return # if left subtree exists and # left child is even if (root.left and not(root.left.data & 1)): # swap root's data with left child # and fix left subtree root.data, \ root.left.data = root.left.data, \ root.data sink(root.left) # if right subtree exists and # right child is even else if(root.right and not(root.right.data & 1)): # swap root's data with right child # and fix right subtree root.data, \ root.right.data = root.right.data, \ root.data sink(root.right) # Function to sink all odd nodes to# the bottom of binary tree. It does# a postorder traversal and calls sink()# if any odd node is founddef sinkOddNodes(root): # If None or is a leaf, do nothing if (root == None or isLeaf(root)): return # Process left and right subtrees # before this node sinkOddNodes(root.left) sinkOddNodes(root.right) # If root is odd, sink it if (root.data & 1): sink(root) # Helper function to do Level Order Traversal# of Binary Tree level by level. This function# is used here only for showing modified tree.def printLevelOrder(root): q = [] q.append(root) # Do Level order traversal while (len(q)): nodeCount = len(q) # Print one level at a time while (nodeCount): node = q[0] print(node.data, end = " ") q.pop(0) if (node.left != None): q.append(node.left) if (node.right != None): q.append(node.right) nodeCount -= 1 # Line separator for levels print() # Driver Code""" Constructed binary tree is 1 / \ 5 8 / \ / \ 2 4 9 10 """root = newnode(1)root.left = newnode(5)root.right = newnode(8)root.left.left = newnode(2)root.left.right = newnode(4)root.right.left = newnode(9)root.right.right = newnode(10) sinkOddNodes(root) print("Level order traversal of modified tree")printLevelOrder(root) # This code is contributed by SHUBHAMSINGH10 Output : Level order traversal of modified tree 2 4 8 5 1 9 10 YouTubeGeeksforGeeks507K subscribersSink Odd nodes in Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=w87SVBrXA9U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above SHUBHAMSINGH10 surinderdawra388 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
[ { "code": null, "e": 26613, "s": 26585, "text": "\n02 Mar, 2022" }, { "code": null, "e": 26956, "s": 26613, "text": "Given a Binary Tree having odd and even elements, sink all its odd valued nodes such that no node with odd value could be parent of node with even value. There can be multiple outputs for a given tree, we need to print one of them. It is always possible to convert a tree (Note that a node with even nodes and all odd nodes follows the rule) " }, { "code": null, "e": 27431, "s": 26956, "text": "Input : \n 1\n / \\\n 2 3\nOutput\n 2 2\n / \\ OR / \\\n 1 3 3 1 \n \n\nInput : \n 1\n / \\\n 5 8\n / \\ / \\\n 2 4 9 10\nOutput :\n 2 4\n / \\ / \\ \n 4 8 OR 2 8 OR .. (any tree with \n/ \\ / \\ / \\ / \\ same keys and \n5 1 9 10 5 1 9 10 no odd is parent\n of even)" }, { "code": null, "e": 28115, "s": 27431, "text": "We strongly recommend you to minimize your browser and try this yourself first.Basically, we need to swap odd value of a node with even value of one of its descendants. The idea is to traverse the tree in postorder fashion. Since we process in postorder, for each odd node encountered, its left and right subtrees are already balanced (sinked), we check if it’s an odd node and its left or right child has an even value. If even value is found, we swap the node’s data with that of even child node and call the procedure on the even child to balance the subtree. If both children have odd values, that means that all its descendants are odd.Below is the implementation of the idea. " }, { "code": null, "e": 28119, "s": 28115, "text": "C++" }, { "code": null, "e": 28127, "s": 28119, "text": "Python3" }, { "code": "// Program to sink odd nodes to the bottom of// binary tree#include<bits/stdc++.h>using namespace std; // A binary tree nodestruct Node{ int data; Node* left, *right;}; // Helper function to allocates a new nodeNode* newnode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return node;} // Helper function to check if node is leaf nodebool isLeaf(Node *root){ return (root->left == NULL && root->right == NULL);} // A recursive method to sink a tree with odd root// This method assumes that the subtrees are already// sinked. This method is similar to Heapify of// Heap-Sortvoid sink(Node *&root){ // If NULL or is a leaf, do nothing if (root == NULL || isLeaf(root)) return; // if left subtree exists and left child is even if (root->left && !(root->left->data & 1)) { // swap root's data with left child and // fix left subtree swap(root->data, root->left->data); sink(root->left); } // if right subtree exists and right child is even else if(root->right && !(root->right->data & 1)) { // swap root's data with right child and // fix right subtree swap(root->data, root->right->data); sink(root->right); }} // Function to sink all odd nodes to the bottom of binary// tree. It does a postorder traversal and calls sink()// if any odd node is foundvoid sinkOddNodes(Node* &root){ // If NULL or is a leaf, do nothing if (root == NULL || isLeaf(root)) return; // Process left and right subtrees before this node sinkOddNodes(root->left); sinkOddNodes(root->right); // If root is odd, sink it if (root->data & 1) sink(root);} // Helper function to do Level Order Traversal of// Binary Tree level by level. This function is used// here only for showing modified tree.void printLevelOrder(Node* root){ queue<Node*> q; q.push(root); // Do Level order traversal while (!q.empty()) { int nodeCount = q.size(); // Print one level at a time while (nodeCount) { Node *node = q.front(); printf(\"%d \", node->data); q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } // Line separator for levels printf(\"\\n\"); }} // Driver program to test above functionsint main(){ /* Constructed binary tree is 1 / \\ 5 8 / \\ / \\ 2 4 9 10 */ Node *root = newnode(1); root->left = newnode(5); root->right = newnode(8); root->left->left = newnode(2); root->left->right = newnode(4); root->right->left = newnode(9); root->right->right = newnode(10); sinkOddNodes(root); printf(\"Level order traversal of modified tree\\n\"); printLevelOrder(root); return 0;}", "e": 31072, "s": 28127, "text": null }, { "code": "# Python3 program to sink odd nodes# to the bottom of binary tree # A binary tree node# Helper function to allocates a new nodeclass newnode: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Helper function to check# if node is leaf nodedef isLeaf(root): return (root.left == None and root.right == None) # A recursive method to sink a tree with odd root# This method assumes that the subtrees are# already sinked. This method is similar to# Heapify of Heap-Sortdef sink(root): # If None or is a leaf, do nothing if (root == None or isLeaf(root)): return # if left subtree exists and # left child is even if (root.left and not(root.left.data & 1)): # swap root's data with left child # and fix left subtree root.data, \\ root.left.data = root.left.data, \\ root.data sink(root.left) # if right subtree exists and # right child is even else if(root.right and not(root.right.data & 1)): # swap root's data with right child # and fix right subtree root.data, \\ root.right.data = root.right.data, \\ root.data sink(root.right) # Function to sink all odd nodes to# the bottom of binary tree. It does# a postorder traversal and calls sink()# if any odd node is founddef sinkOddNodes(root): # If None or is a leaf, do nothing if (root == None or isLeaf(root)): return # Process left and right subtrees # before this node sinkOddNodes(root.left) sinkOddNodes(root.right) # If root is odd, sink it if (root.data & 1): sink(root) # Helper function to do Level Order Traversal# of Binary Tree level by level. This function# is used here only for showing modified tree.def printLevelOrder(root): q = [] q.append(root) # Do Level order traversal while (len(q)): nodeCount = len(q) # Print one level at a time while (nodeCount): node = q[0] print(node.data, end = \" \") q.pop(0) if (node.left != None): q.append(node.left) if (node.right != None): q.append(node.right) nodeCount -= 1 # Line separator for levels print() # Driver Code\"\"\" Constructed binary tree is 1 / \\ 5 8 / \\ / \\ 2 4 9 10 \"\"\"root = newnode(1)root.left = newnode(5)root.right = newnode(8)root.left.left = newnode(2)root.left.right = newnode(4)root.right.left = newnode(9)root.right.right = newnode(10) sinkOddNodes(root) print(\"Level order traversal of modified tree\")printLevelOrder(root) # This code is contributed by SHUBHAMSINGH10", "e": 33922, "s": 31072, "text": null }, { "code": null, "e": 33932, "s": 33922, "text": "Output : " }, { "code": null, "e": 33989, "s": 33932, "text": "Level order traversal of modified tree\n2 \n4 8 \n5 1 9 10 " }, { "code": null, "e": 34819, "s": 33991, "text": "YouTubeGeeksforGeeks507K subscribersSink Odd nodes in Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=w87SVBrXA9U\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 34988, "s": 34819, "text": "This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 35003, "s": 34988, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 35020, "s": 35003, "text": "surinderdawra388" }, { "code": null, "e": 35025, "s": 35020, "text": "Tree" }, { "code": null, "e": 35030, "s": 35025, "text": "Tree" }, { "code": null, "e": 35128, "s": 35030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35171, "s": 35128, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 35212, "s": 35171, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 35245, "s": 35212, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 35259, "s": 35245, "text": "Decision Tree" }, { "code": null, "e": 35309, "s": 35259, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 35367, "s": 35309, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 35403, "s": 35367, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 35451, "s": 35403, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
Area of Reuleaux Triangle - GeeksforGeeks
17 Mar, 2021 Given an integer h which is the side of an equilateral triangle formed by the same vertices as the Reuleaux triangle, the task is to find and print the area of the Reuleaux triangle. Examples: Input: h = 6 Output: 25.3717Input: h = 9 Output: 57.0864 Approach: The shape made by the intersection of the three circles ABC is the Reuleaux Triangle and the triangle formed by the same vertices i.e. ABC is an equilateral triangle with side h. Now, Area of sector ACB, A1 = (π * h2) / 6 Similarly, Area of sector CBA, A2 = (π * h2) / 6 And, Area of sector BAC, A3 = (π * h2) / 6 So, A1 + A2 + A3 = (π * h2) / 2 Since, the area of the triangle is added thrice in the sum. So, Area of the Reuleaux Triangle, A = (π * h2) / 2 – 2 * (Area of equilateral triangle) = (π – √3) * h2 / 2 = 0.70477 * h2 Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ Program to find the area// of Reuleaux triangle#include <bits/stdc++.h>using namespace std; // Function to find the Area// of the Reuleaux trianglefloat ReuleauxArea(float a){ // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle float A = 0.70477 * pow(a, 2); return A;} // Driver codeint main(){ float a = 6; cout << ReuleauxArea(a) << endl; return 0;} // Java Program to find the area// of Reuleaux triangle public class GFG{ // Function to find the Area // of the Reuleaux triangle static double ReuleauxArea(float a) { // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle double A = (double)0.70477 * Math.pow(a, 2); return A; } // Driver code public static void main(String args[]) { float a = 6; System.out.println(ReuleauxArea(a)) ; } // This code is contributed by Ryuga} # Python3 program to find the area# of Reuleaux triangleimport math as mt # function to the area of the# Reuleaux triangledef ReuleauxArea(a): # Side cannot be negative if a < 0: return -1 # Area of the Reauleax triangle return 0.70477 * pow(a, 2) # Driver codea = 6print(ReuleauxArea(a)) # This code is contributed# by Mohit Kumar // C# Program to find the area // of Reuleaux triangle using System; public class GFG{ // Function to find the Area // of the Reuleaux triangle static double ReuleauxArea(float a) { // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle double A = (double)0.70477 * Math.Pow(a, 2); return A; } // Driver code public static void Main() { float a = 6; Console.WriteLine(ReuleauxArea(a)) ; }} // This code is contributed by Subhadeep <?php// PHP Program to find the area// of Reuleaux triangle // Function to find the Area// of the Reuleaux trianglefunction ReuleauxArea($a){ // Side cannot be negative if ($a < 0) return -1; // Area of the Reuleaux triangle $A = 0.70477 * pow($a, 2); return $A;} // Driver code$a = 6;echo ReuleauxArea($a); // This code is contributed// by Akanksha Rai <script>// javascript Program to find the area// of Reuleaux triangle // Function to find the Area// of the Reuleaux trianglefunction ReuleauxArea(a){ // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle var A = 0.70477 * Math.pow(a, 2); return A;} // Driver code var a = 6;document.write(ReuleauxArea(a)) ; // This code is contributed by Princi Singh</script> 25.3717 ankthon tufan_gupta2000 mohit kumar 29 Akanksha_Rai princi singh area-volume-programs C++ Programs Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Closest Pair of Points using Divide and Conquer algorithm How to check if a given point lies inside or outside a polygon? Program for distance between two points on earth How to check if two given line segments intersect? Find if two rectangles overlap
[ { "code": null, "e": 25851, "s": 25823, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26036, "s": 25851, "text": "Given an integer h which is the side of an equilateral triangle formed by the same vertices as the Reuleaux triangle, the task is to find and print the area of the Reuleaux triangle. " }, { "code": null, "e": 26048, "s": 26036, "text": "Examples: " }, { "code": null, "e": 26107, "s": 26048, "text": "Input: h = 6 Output: 25.3717Input: h = 9 Output: 57.0864 " }, { "code": null, "e": 26300, "s": 26109, "text": "Approach: The shape made by the intersection of the three circles ABC is the Reuleaux Triangle and the triangle formed by the same vertices i.e. ABC is an equilateral triangle with side h. " }, { "code": null, "e": 26653, "s": 26300, "text": "Now, Area of sector ACB, A1 = (π * h2) / 6 Similarly, Area of sector CBA, A2 = (π * h2) / 6 And, Area of sector BAC, A3 = (π * h2) / 6 So, A1 + A2 + A3 = (π * h2) / 2 Since, the area of the triangle is added thrice in the sum. So, Area of the Reuleaux Triangle, A = (π * h2) / 2 – 2 * (Area of equilateral triangle) = (π – √3) * h2 / 2 = 0.70477 * h2 " }, { "code": null, "e": 26706, "s": 26653, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26710, "s": 26706, "text": "C++" }, { "code": null, "e": 26715, "s": 26710, "text": "Java" }, { "code": null, "e": 26723, "s": 26715, "text": "Python3" }, { "code": null, "e": 26726, "s": 26723, "text": "C#" }, { "code": null, "e": 26730, "s": 26726, "text": "PHP" }, { "code": null, "e": 26741, "s": 26730, "text": "Javascript" }, { "code": "// C++ Program to find the area// of Reuleaux triangle#include <bits/stdc++.h>using namespace std; // Function to find the Area// of the Reuleaux trianglefloat ReuleauxArea(float a){ // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle float A = 0.70477 * pow(a, 2); return A;} // Driver codeint main(){ float a = 6; cout << ReuleauxArea(a) << endl; return 0;}", "e": 27164, "s": 26741, "text": null }, { "code": "// Java Program to find the area// of Reuleaux triangle public class GFG{ // Function to find the Area // of the Reuleaux triangle static double ReuleauxArea(float a) { // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle double A = (double)0.70477 * Math.pow(a, 2); return A; } // Driver code public static void main(String args[]) { float a = 6; System.out.println(ReuleauxArea(a)) ; } // This code is contributed by Ryuga}", "e": 27724, "s": 27164, "text": null }, { "code": "# Python3 program to find the area# of Reuleaux triangleimport math as mt # function to the area of the# Reuleaux triangledef ReuleauxArea(a): # Side cannot be negative if a < 0: return -1 # Area of the Reauleax triangle return 0.70477 * pow(a, 2) # Driver codea = 6print(ReuleauxArea(a)) # This code is contributed# by Mohit Kumar ", "e": 28087, "s": 27724, "text": null }, { "code": "// C# Program to find the area // of Reuleaux triangle using System; public class GFG{ // Function to find the Area // of the Reuleaux triangle static double ReuleauxArea(float a) { // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle double A = (double)0.70477 * Math.Pow(a, 2); return A; } // Driver code public static void Main() { float a = 6; Console.WriteLine(ReuleauxArea(a)) ; }} // This code is contributed by Subhadeep", "e": 28675, "s": 28087, "text": null }, { "code": "<?php// PHP Program to find the area// of Reuleaux triangle // Function to find the Area// of the Reuleaux trianglefunction ReuleauxArea($a){ // Side cannot be negative if ($a < 0) return -1; // Area of the Reuleaux triangle $A = 0.70477 * pow($a, 2); return $A;} // Driver code$a = 6;echo ReuleauxArea($a); // This code is contributed// by Akanksha Rai", "e": 29053, "s": 28675, "text": null }, { "code": "<script>// javascript Program to find the area// of Reuleaux triangle // Function to find the Area// of the Reuleaux trianglefunction ReuleauxArea(a){ // Side cannot be negative if (a < 0) return -1; // Area of the Reuleaux triangle var A = 0.70477 * Math.pow(a, 2); return A;} // Driver code var a = 6;document.write(ReuleauxArea(a)) ; // This code is contributed by Princi Singh</script>", "e": 29469, "s": 29053, "text": null }, { "code": null, "e": 29477, "s": 29469, "text": "25.3717" }, { "code": null, "e": 29487, "s": 29479, "text": "ankthon" }, { "code": null, "e": 29503, "s": 29487, "text": "tufan_gupta2000" }, { "code": null, "e": 29518, "s": 29503, "text": "mohit kumar 29" }, { "code": null, "e": 29531, "s": 29518, "text": "Akanksha_Rai" }, { "code": null, "e": 29544, "s": 29531, "text": "princi singh" }, { "code": null, "e": 29565, "s": 29544, "text": "area-volume-programs" }, { "code": null, "e": 29578, "s": 29565, "text": "C++ Programs" }, { "code": null, "e": 29588, "s": 29578, "text": "Geometric" }, { "code": null, "e": 29601, "s": 29588, "text": "Mathematical" }, { "code": null, "e": 29614, "s": 29601, "text": "Mathematical" }, { "code": null, "e": 29624, "s": 29614, "text": "Geometric" }, { "code": null, "e": 29722, "s": 29624, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29763, "s": 29722, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 29822, "s": 29763, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 29843, "s": 29822, "text": "Const keyword in C++" }, { "code": null, "e": 29855, "s": 29843, "text": "cout in C++" }, { "code": null, "e": 29876, "s": 29855, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 29934, "s": 29876, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 29998, "s": 29934, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 30047, "s": 29998, "text": "Program for distance between two points on earth" }, { "code": null, "e": 30098, "s": 30047, "text": "How to check if two given line segments intersect?" } ]
CSS | ::first-line Selector - GeeksforGeeks
04 Jan, 2019 The ::first-line selector in CSS is used to apply style to the first line of a block-level element. The length of the first line depends on many factors, including the width of the element, the width of the document, font-size of the text, etc. Syntax: ::first-line { //CSS Property } Example: <!DOCTYPE html><html> <head> <title> CSS ::first-line selector </title> <style> p { width: 25%; } p::first-line { color: white; background: green; } </style></head> <body style="text-align: center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> CSS ::first-line selector </h2> <p> A computer science portal for geeks. </p> </body> </html> Output:Supported Browsers: The browser supported by ::first-line selector are listed below: Apple Safari 1.0 Google Chrome 1.0 Firefox 1.0 Opera 7.0 Partial from 3.5 Internet Explorer 9.0 Partial from 5.5 CSS-Selectors CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24885, "s": 24857, "text": "\n04 Jan, 2019" }, { "code": null, "e": 25130, "s": 24885, "text": "The ::first-line selector in CSS is used to apply style to the first line of a block-level element. The length of the first line depends on many factors, including the width of the element, the width of the document, font-size of the text, etc." }, { "code": null, "e": 25138, "s": 25130, "text": "Syntax:" }, { "code": null, "e": 25175, "s": 25138, "text": "::first-line {\n //CSS Property\n}\n" }, { "code": null, "e": 25184, "s": 25175, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS ::first-line selector </title> <style> p { width: 25%; } p::first-line { color: white; background: green; } </style></head> <body style=\"text-align: center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> CSS ::first-line selector </h2> <p> A computer science portal for geeks. </p> </body> </html>", "e": 25680, "s": 25184, "text": null }, { "code": null, "e": 25772, "s": 25680, "text": "Output:Supported Browsers: The browser supported by ::first-line selector are listed below:" }, { "code": null, "e": 25789, "s": 25772, "text": "Apple Safari 1.0" }, { "code": null, "e": 25807, "s": 25789, "text": "Google Chrome 1.0" }, { "code": null, "e": 25819, "s": 25807, "text": "Firefox 1.0" }, { "code": null, "e": 25846, "s": 25819, "text": "Opera 7.0 Partial from 3.5" }, { "code": null, "e": 25885, "s": 25846, "text": "Internet Explorer 9.0 Partial from 5.5" }, { "code": null, "e": 25899, "s": 25885, "text": "CSS-Selectors" }, { "code": null, "e": 25903, "s": 25899, "text": "CSS" }, { "code": null, "e": 25920, "s": 25903, "text": "Web Technologies" }, { "code": null, "e": 26018, "s": 25920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26068, "s": 26018, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26130, "s": 26068, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26178, "s": 26130, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26236, "s": 26178, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26291, "s": 26236, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 26331, "s": 26291, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26364, "s": 26331, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26409, "s": 26364, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26452, "s": 26409, "text": "How to fetch data from an API in ReactJS ?" } ]
Program to accept a Strings which contains all the Vowels - GeeksforGeeks
21 May, 2021 Given a string S, the task is to check and accept the given string if it contains all vowels i.e. ‘a’, ‘e’, ‘i’.’o’, ‘u’ or ‘A’, ‘E’, ‘I’, ‘O’, ‘U’.Examples: Input: S = “GeeksforGeeks” Output: Not Accepted Since S does not contain vowels a, i and uInput: S = “ABeeIghiObhkUul” Output: Accepted Since S contains all vowels a, e, i, o and u Approach: Hashing can be used to solve this problem easily. For this, a hash data structure needs to be created of size 5 such that the index 0, 1, 2, 3, and 4 represent the vowels a, e, i, o, and u. Create a Boolean Array, as the hash data structure, to check that all vowels are present or not in the string. Iterate over the string character by character and if the character is vowel then mark that vowel present in the Boolean Array After the Iteration of the string, check that is there any vowel which is not present in the boolean array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to check that// a string contains all vowels #include <iostream>using namespace std; // Function to to check that// a string contains all vowelsint checkIfAllVowels(string str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u int hash[5] = { 0 }; // Loop the string to mark the vowels // which are present for (int i = 0; i < str.length(); i++) { if (str[i] == 'A' || str[i] == 'a') hash[0] = 1; else if (str[i] == 'E' || str[i] == 'e') hash[1] = 1; else if (str[i] == 'I' || str[i] == 'i') hash[2] = 1; else if (str[i] == 'O' || str[i] == 'o') hash[3] = 1; else if (str[i] == 'U' || str[i] == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the string for (int i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } } return 0;} // Function to to check that// a string contains all vowelsint checkIfAllVowelsArePresent(string str){ if (checkIfAllVowels(str)) cout << "Not Accepted\n"; else cout << "Accepted\n";} // Driver Codeint main(){ string str = "aeioubc"; checkIfAllVowelsArePresent(str); return 0;} // Java implementation to check that// a String contains all vowels class GFG{ // Function to to check that// a String contains all vowelsstatic int checkIfAllVowels(String str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u int []hash = new int[5]; // Loop the String to mark the vowels // which are present for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == 'A' || str.charAt(i) == 'a') hash[0] = 1; else if (str.charAt(i) == 'E' || str.charAt(i) == 'e') hash[1] = 1; else if (str.charAt(i) == 'I' || str.charAt(i) == 'i') hash[2] = 1; else if (str.charAt(i) == 'O' || str.charAt(i) == 'o') hash[3] = 1; else if (str.charAt(i) == 'U' || str.charAt(i) == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the String for (int i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } }return 0;} // Function to to check that// a String contains all vowelsstatic void checkIfAllVowelsArePresent(String str){ if (checkIfAllVowels(str) == 1) System.out.print("Not Accepted\n"); else System.out.print("Accepted\n");} // Driver Codepublic static void main(String[] args){ String str = "aeioubc"; checkIfAllVowelsArePresent(str);}} // This code is contributed by 29AjayKumar # Python3 implementation to check that# a string contains all vowels # Function to to check that# a string contains all vowelsdef checkIfAllVowels(string) : # Hash Array of size 5 # such that the index 0, 1, 2, 3 and 4 # represent the vowels a, e, i, o and u hash = [0]*5 ; # Loop the string to mark the vowels # which are present for i in range(len(string)) : if (string[i] == 'A' or string[i] == 'a') : hash[0] = 1; elif (string[i] == 'E' or string[i] == 'e') : hash[1] = 1; elif (string[i] == 'I' or string[i] == 'i') : hash[2] = 1; elif (string[i] == 'O' or string[i] == 'o') : hash[3] = 1; elif (string[i] == 'U' or string[i] == 'u') : hash[4] = 1; # Loop to check if there is any vowel # which is not present in the string for i in range(5) : if (hash[i] == 0) : return 1; return 0; # Function to to check that# a string contains all vowelsdef checkIfAllVowelsArePresent(string) : if (checkIfAllVowels(string)) : print("Not Accepted"); else : print("Accepted"); # Driver Codeif __name__ == "__main__" : string = "aeioubc"; checkIfAllVowelsArePresent(string); # This code is contributed by AnkitRai01 // C# implementation to check that// a String contains all vowelsusing System; class GFG{ // Function to to check that// a String contains all vowelsstatic int checkIfAllVowels(String str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u int []hash = new int[5]; // Loop the String to mark the vowels // which are present for (int i = 0; i < str.Length; i++) { if (str[i] == 'A' || str[i] == 'a') hash[0] = 1; else if (str[i] == 'E' || str[i] == 'e') hash[1] = 1; else if (str[i] == 'I' || str[i] == 'i') hash[2] = 1; else if (str[i] == 'O' || str[i] == 'o') hash[3] = 1; else if (str[i] == 'U' || str[i] == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the String for (int i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } }return 0;} // Function to to check that// a String contains all vowelsstatic void checkIfAllVowelsArePresent(String str){ if (checkIfAllVowels(str) == 1) Console.Write("Not Accepted\n"); else Console.Write("Accepted\n");} // Driver Codepublic static void Main(String[] args){ String str = "aeioubc"; checkIfAllVowelsArePresent(str);}} // This code is contributed by 29AjayKumar <script> // JavaScript implementation to check that// a string contains all vowels // Function to to check that// a string contains all vowelsfunction checkIfAllVowels(str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u var hash = Array(5).fill(0); // Loop the string to mark the vowels // which are present for (var i = 0; i < str.length; i++) { if (str[i] == 'A' || str[i] == 'a') hash[0] = 1; else if (str[i] == 'E' || str[i] == 'e') hash[1] = 1; else if (str[i] == 'I' || str[i] == 'i') hash[2] = 1; else if (str[i] == 'O' || str[i] == 'o') hash[3] = 1; else if (str[i] == 'U' || str[i] == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the string for (var i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } } return 0;} // Function to to check that// a string contains all vowelsfunction checkIfAllVowelsArePresent(str){ if (checkIfAllVowels(str)) document.write( "Not Accepted<br>"); else document.write( "Accepted<br>");} // Driver Codevar str = "aeioubc";checkIfAllVowelsArePresent(str); </script> Accepted 29AjayKumar ankthon importantly Arrays Hash Strings Arrays Hash Strings 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 Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum
[ { "code": null, "e": 26323, "s": 26295, "text": "\n21 May, 2021" }, { "code": null, "e": 26483, "s": 26323, "text": "Given a string S, the task is to check and accept the given string if it contains all vowels i.e. ‘a’, ‘e’, ‘i’.’o’, ‘u’ or ‘A’, ‘E’, ‘I’, ‘O’, ‘U’.Examples: " }, { "code": null, "e": 26666, "s": 26483, "text": "Input: S = “GeeksforGeeks” Output: Not Accepted Since S does not contain vowels a, i and uInput: S = “ABeeIghiObhkUul” Output: Accepted Since S contains all vowels a, e, i, o and u " }, { "code": null, "e": 26680, "s": 26668, "text": "Approach: " }, { "code": null, "e": 26870, "s": 26680, "text": "Hashing can be used to solve this problem easily. For this, a hash data structure needs to be created of size 5 such that the index 0, 1, 2, 3, and 4 represent the vowels a, e, i, o, and u." }, { "code": null, "e": 26981, "s": 26870, "text": "Create a Boolean Array, as the hash data structure, to check that all vowels are present or not in the string." }, { "code": null, "e": 27108, "s": 26981, "text": "Iterate over the string character by character and if the character is vowel then mark that vowel present in the Boolean Array" }, { "code": null, "e": 27216, "s": 27108, "text": "After the Iteration of the string, check that is there any vowel which is not present in the boolean array." }, { "code": null, "e": 27268, "s": 27216, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27272, "s": 27268, "text": "C++" }, { "code": null, "e": 27277, "s": 27272, "text": "Java" }, { "code": null, "e": 27285, "s": 27277, "text": "Python3" }, { "code": null, "e": 27288, "s": 27285, "text": "C#" }, { "code": null, "e": 27299, "s": 27288, "text": "Javascript" }, { "code": "// C++ implementation to check that// a string contains all vowels #include <iostream>using namespace std; // Function to to check that// a string contains all vowelsint checkIfAllVowels(string str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u int hash[5] = { 0 }; // Loop the string to mark the vowels // which are present for (int i = 0; i < str.length(); i++) { if (str[i] == 'A' || str[i] == 'a') hash[0] = 1; else if (str[i] == 'E' || str[i] == 'e') hash[1] = 1; else if (str[i] == 'I' || str[i] == 'i') hash[2] = 1; else if (str[i] == 'O' || str[i] == 'o') hash[3] = 1; else if (str[i] == 'U' || str[i] == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the string for (int i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } } return 0;} // Function to to check that// a string contains all vowelsint checkIfAllVowelsArePresent(string str){ if (checkIfAllVowels(str)) cout << \"Not Accepted\\n\"; else cout << \"Accepted\\n\";} // Driver Codeint main(){ string str = \"aeioubc\"; checkIfAllVowelsArePresent(str); return 0;}", "e": 28615, "s": 27299, "text": null }, { "code": "// Java implementation to check that// a String contains all vowels class GFG{ // Function to to check that// a String contains all vowelsstatic int checkIfAllVowels(String str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u int []hash = new int[5]; // Loop the String to mark the vowels // which are present for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == 'A' || str.charAt(i) == 'a') hash[0] = 1; else if (str.charAt(i) == 'E' || str.charAt(i) == 'e') hash[1] = 1; else if (str.charAt(i) == 'I' || str.charAt(i) == 'i') hash[2] = 1; else if (str.charAt(i) == 'O' || str.charAt(i) == 'o') hash[3] = 1; else if (str.charAt(i) == 'U' || str.charAt(i) == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the String for (int i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } }return 0;} // Function to to check that// a String contains all vowelsstatic void checkIfAllVowelsArePresent(String str){ if (checkIfAllVowels(str) == 1) System.out.print(\"Not Accepted\\n\"); else System.out.print(\"Accepted\\n\");} // Driver Codepublic static void main(String[] args){ String str = \"aeioubc\"; checkIfAllVowelsArePresent(str);}} // This code is contributed by 29AjayKumar", "e": 30084, "s": 28615, "text": null }, { "code": "# Python3 implementation to check that# a string contains all vowels # Function to to check that# a string contains all vowelsdef checkIfAllVowels(string) : # Hash Array of size 5 # such that the index 0, 1, 2, 3 and 4 # represent the vowels a, e, i, o and u hash = [0]*5 ; # Loop the string to mark the vowels # which are present for i in range(len(string)) : if (string[i] == 'A' or string[i] == 'a') : hash[0] = 1; elif (string[i] == 'E' or string[i] == 'e') : hash[1] = 1; elif (string[i] == 'I' or string[i] == 'i') : hash[2] = 1; elif (string[i] == 'O' or string[i] == 'o') : hash[3] = 1; elif (string[i] == 'U' or string[i] == 'u') : hash[4] = 1; # Loop to check if there is any vowel # which is not present in the string for i in range(5) : if (hash[i] == 0) : return 1; return 0; # Function to to check that# a string contains all vowelsdef checkIfAllVowelsArePresent(string) : if (checkIfAllVowels(string)) : print(\"Not Accepted\"); else : print(\"Accepted\"); # Driver Codeif __name__ == \"__main__\" : string = \"aeioubc\"; checkIfAllVowelsArePresent(string); # This code is contributed by AnkitRai01", "e": 31443, "s": 30084, "text": null }, { "code": "// C# implementation to check that// a String contains all vowelsusing System; class GFG{ // Function to to check that// a String contains all vowelsstatic int checkIfAllVowels(String str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u int []hash = new int[5]; // Loop the String to mark the vowels // which are present for (int i = 0; i < str.Length; i++) { if (str[i] == 'A' || str[i] == 'a') hash[0] = 1; else if (str[i] == 'E' || str[i] == 'e') hash[1] = 1; else if (str[i] == 'I' || str[i] == 'i') hash[2] = 1; else if (str[i] == 'O' || str[i] == 'o') hash[3] = 1; else if (str[i] == 'U' || str[i] == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the String for (int i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } }return 0;} // Function to to check that// a String contains all vowelsstatic void checkIfAllVowelsArePresent(String str){ if (checkIfAllVowels(str) == 1) Console.Write(\"Not Accepted\\n\"); else Console.Write(\"Accepted\\n\");} // Driver Codepublic static void Main(String[] args){ String str = \"aeioubc\"; checkIfAllVowelsArePresent(str);}} // This code is contributed by 29AjayKumar", "e": 32845, "s": 31443, "text": null }, { "code": "<script> // JavaScript implementation to check that// a string contains all vowels // Function to to check that// a string contains all vowelsfunction checkIfAllVowels(str){ // Hash Array of size 5 // such that the index 0, 1, 2, 3 and 4 // represent the vowels a, e, i, o and u var hash = Array(5).fill(0); // Loop the string to mark the vowels // which are present for (var i = 0; i < str.length; i++) { if (str[i] == 'A' || str[i] == 'a') hash[0] = 1; else if (str[i] == 'E' || str[i] == 'e') hash[1] = 1; else if (str[i] == 'I' || str[i] == 'i') hash[2] = 1; else if (str[i] == 'O' || str[i] == 'o') hash[3] = 1; else if (str[i] == 'U' || str[i] == 'u') hash[4] = 1; } // Loop to check if there is any vowel // which is not present in the string for (var i = 0; i < 5; i++) { if (hash[i] == 0) { return 1; } } return 0;} // Function to to check that// a string contains all vowelsfunction checkIfAllVowelsArePresent(str){ if (checkIfAllVowels(str)) document.write( \"Not Accepted<br>\"); else document.write( \"Accepted<br>\");} // Driver Codevar str = \"aeioubc\";checkIfAllVowelsArePresent(str); </script>", "e": 34137, "s": 32845, "text": null }, { "code": null, "e": 34146, "s": 34137, "text": "Accepted" }, { "code": null, "e": 34160, "s": 34148, "text": "29AjayKumar" }, { "code": null, "e": 34168, "s": 34160, "text": "ankthon" }, { "code": null, "e": 34180, "s": 34168, "text": "importantly" }, { "code": null, "e": 34187, "s": 34180, "text": "Arrays" }, { "code": null, "e": 34192, "s": 34187, "text": "Hash" }, { "code": null, "e": 34200, "s": 34192, "text": "Strings" }, { "code": null, "e": 34207, "s": 34200, "text": "Arrays" }, { "code": null, "e": 34212, "s": 34207, "text": "Hash" }, { "code": null, "e": 34220, "s": 34212, "text": "Strings" }, { "code": null, "e": 34318, "s": 34220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34386, "s": 34318, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34430, "s": 34386, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34478, "s": 34430, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34501, "s": 34478, "text": "Introduction to Arrays" }, { "code": null, "e": 34533, "s": 34501, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34618, "s": 34533, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34654, "s": 34618, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 34685, "s": 34654, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 34719, "s": 34685, "text": "Hashing | Set 3 (Open Addressing)" } ]
MySQL | DATABASE() and CURRENT_USER() Functions - GeeksforGeeks
21 Jun, 2021 DATABASE() Function The DATABASE() Function in MySQL returns the name of the default or current database. The string or name returned by DATABASE() function uses the utf8 character set. If there is no default database,the Database function returns NULL. In the older versions than MySQL 4.1.1,The Database function used to return an empty string, if there is no default database. Syntax : SELECT DATABASE(); The DATABASE() function is easy to use and does not accept any parameters. We can easily get the name of default database using the above syntax on MySQL console. Example : Let us consider the name of the default database is “Employees”. Therefore to know the name of the default database, the database function can be executed in the following way: Output: 'Employees' CURRENT_USER() Function The CURRENT_USER() Function in MySQL is used to return the user name and host name for the MySQL account which is used by the server to authenticate the current client. As of MySQL 4.1.,the CURRENT_USER() function uses the utf8 character set. Syntax: SELECT CURRENT_USER(); CURRENT_USER() function also does not accepts any parameters. Example : Let us consider the username of MySQL account used by the server to authenticate the current client is ‘root’ and the hostname is ‘localhost’. Therefore to know the username and hostname for the MySQL account used by the server to authenticate the current client, the CURRENT_USER() function can be executed in the following way: Output: 'root@localhost' rajeev0719singh Functions mysql SQL Functions 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 | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n21 Jun, 2021" }, { "code": null, "e": 25533, "s": 25513, "text": "DATABASE() Function" }, { "code": null, "e": 25894, "s": 25533, "text": "The DATABASE() Function in MySQL returns the name of the default or current database. The string or name returned by DATABASE() function uses the utf8 character set. If there is no default database,the Database function returns NULL. In the older versions than MySQL 4.1.1,The Database function used to return an empty string, if there is no default database. " }, { "code": null, "e": 25905, "s": 25894, "text": "Syntax : " }, { "code": null, "e": 25924, "s": 25905, "text": "SELECT DATABASE();" }, { "code": null, "e": 26088, "s": 25924, "text": "The DATABASE() function is easy to use and does not accept any parameters. We can easily get the name of default database using the above syntax on MySQL console. " }, { "code": null, "e": 26277, "s": 26088, "text": "Example : Let us consider the name of the default database is “Employees”. Therefore to know the name of the default database, the database function can be executed in the following way: " }, { "code": null, "e": 26287, "s": 26277, "text": "Output: " }, { "code": null, "e": 26299, "s": 26287, "text": "'Employees'" }, { "code": null, "e": 26325, "s": 26301, "text": "CURRENT_USER() Function" }, { "code": null, "e": 26495, "s": 26325, "text": "The CURRENT_USER() Function in MySQL is used to return the user name and host name for the MySQL account which is used by the server to authenticate the current client. " }, { "code": null, "e": 26570, "s": 26495, "text": "As of MySQL 4.1.,the CURRENT_USER() function uses the utf8 character set. " }, { "code": null, "e": 26580, "s": 26570, "text": "Syntax: " }, { "code": null, "e": 26603, "s": 26580, "text": "SELECT CURRENT_USER();" }, { "code": null, "e": 26666, "s": 26603, "text": "CURRENT_USER() function also does not accepts any parameters. " }, { "code": null, "e": 27008, "s": 26666, "text": "Example : Let us consider the username of MySQL account used by the server to authenticate the current client is ‘root’ and the hostname is ‘localhost’. Therefore to know the username and hostname for the MySQL account used by the server to authenticate the current client, the CURRENT_USER() function can be executed in the following way: " }, { "code": null, "e": 27018, "s": 27008, "text": "Output: " }, { "code": null, "e": 27035, "s": 27018, "text": "'root@localhost'" }, { "code": null, "e": 27053, "s": 27037, "text": "rajeev0719singh" }, { "code": null, "e": 27063, "s": 27053, "text": "Functions" }, { "code": null, "e": 27069, "s": 27063, "text": "mysql" }, { "code": null, "e": 27073, "s": 27069, "text": "SQL" }, { "code": null, "e": 27083, "s": 27073, "text": "Functions" }, { "code": null, "e": 27087, "s": 27083, "text": "SQL" }, { "code": null, "e": 27185, "s": 27087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27251, "s": 27185, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27266, "s": 27251, "text": "SQL | Subquery" }, { "code": null, "e": 27323, "s": 27266, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27355, "s": 27323, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27433, "s": 27355, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27450, "s": 27433, "text": "SQL using Python" }, { "code": null, "e": 27486, "s": 27450, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27552, "s": 27486, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27614, "s": 27552, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Non-generic Vs Generic Collection in Java
Errors appear at compile time than at run time. Code reusability: Generics help in reusing the code already written, thereby making it usable for other types (for a method, or class, or an interface). If a data structure is generic, say a list, it would only take specific type of objects and return the same specific type of object as output. This eliminates the need to typecast individually. Algorithms can be implemented with ease, since they can be used to work with different types of objects, and maintaining type safety as well as code reusability. Following is an example − Live Demo import java.util.*; public class Demo { public static void main(String[] args) { ArrayList<String> my_list = new ArrayList<String>(); my_list.add("Joe"); my_list.add("Rob"); my_list.add("John"); my_list.add("Billy"); String s1 = my_list.get(0); String s2 = my_list.get(1); String s3 = my_list.get(3); System.out.println(s1); System.out.println(s2); System.out.println(s3); } } Joe Rob Billy A class named Demo contains the main function. Here, an arraylist of strings is defined. Elements are added to this list with the help of the ‘add’ function. The ‘get’ function is used to store the element at a specific index. The println function is used to print the specific element on the console. When the data structure is non-generic, it causes issues when the data is tried to be retrieved from the collection/data structure. Every time an element from the collection is retrieved, it needs to be explicitly type-casted to its required type, which is a problem when there are too many elements. The above code, when implemented using non-generic collection yields the following output. Live Demo import java.util.*; public class Demo { public static void main(String[] args) { ArrayList my_list = new ArrayList(); my_list.add("Joe"); my_list.add("Rob"); my_list.add("Nate"); my_list.add("Bill"); String s1 = (String)my_list.get(0); String s2 = (String)my_list.get(1); String s3 = (String)my_list.get(3); System.out.println(s1); System.out.println(s2); System.out.println(s3); } } : Joe Rob Bill A class named Demo contains the main function. Here, an arraylist of strings is defined. Elements are added to this list with the help of the ‘add’ function. The ‘get’ function is used to store the element at a specific index. Here, every element of the list is explicitly typecasted to String type before being stored in another string variable. The println function is used to print the specific element on the console.
[ { "code": null, "e": 1110, "s": 1062, "text": "Errors appear at compile time than at run time." }, { "code": null, "e": 1263, "s": 1110, "text": "Code reusability: Generics help in reusing the code already written, thereby making it usable for other types (for a method, or class, or an interface)." }, { "code": null, "e": 1457, "s": 1263, "text": "If a data structure is generic, say a list, it would only take specific type of objects and return the same specific type of object as output. This eliminates the need to typecast individually." }, { "code": null, "e": 1619, "s": 1457, "text": "Algorithms can be implemented with ease, since they can be used to work with different types of objects, and maintaining type safety as well as code reusability." }, { "code": null, "e": 1645, "s": 1619, "text": "Following is an example −" }, { "code": null, "e": 1656, "s": 1645, "text": " Live Demo" }, { "code": null, "e": 2105, "s": 1656, "text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<String> my_list = new ArrayList<String>();\n my_list.add(\"Joe\");\n my_list.add(\"Rob\");\n my_list.add(\"John\");\n my_list.add(\"Billy\");\n String s1 = my_list.get(0);\n String s2 = my_list.get(1);\n String s3 = my_list.get(3);\n System.out.println(s1);\n System.out.println(s2);\n System.out.println(s3);\n }\n}" }, { "code": null, "e": 2119, "s": 2105, "text": "Joe\nRob\nBilly" }, { "code": null, "e": 2421, "s": 2119, "text": "A class named Demo contains the main function. Here, an arraylist of strings is defined. Elements are added to this list with the help of the ‘add’ function. The ‘get’ function is used to store the element at a specific index. The println function is used to print the specific element on the console." }, { "code": null, "e": 2553, "s": 2421, "text": "When the data structure is non-generic, it causes issues when the data is tried to be retrieved from the collection/data structure." }, { "code": null, "e": 2722, "s": 2553, "text": "Every time an element from the collection is retrieved, it needs to be explicitly type-casted to its required type, which is a problem when there are too many elements." }, { "code": null, "e": 2813, "s": 2722, "text": "The above code, when implemented using non-generic collection yields the following output." }, { "code": null, "e": 2824, "s": 2813, "text": " Live Demo" }, { "code": null, "e": 3280, "s": 2824, "text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList my_list = new ArrayList();\n my_list.add(\"Joe\");\n my_list.add(\"Rob\");\n my_list.add(\"Nate\");\n my_list.add(\"Bill\");\n String s1 = (String)my_list.get(0);\n String s2 = (String)my_list.get(1);\n String s3 = (String)my_list.get(3);\n System.out.println(s1);\n System.out.println(s2);\n System.out.println(s3);\n }\n}" }, { "code": null, "e": 3295, "s": 3280, "text": ":\nJoe\nRob\nBill" }, { "code": null, "e": 3717, "s": 3295, "text": "A class named Demo contains the main function. Here, an arraylist of strings is defined. Elements are added to this list with the help of the ‘add’ function. The ‘get’ function is used to store the element at a specific index. Here, every element of the list is explicitly typecasted to String type before being stored in another string variable. The println function is used to print the specific element on the console." } ]