title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to limit the number of characters entered in a textarea in an HTML form?
To add a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. To limit the number of characters entered in a textarea, use the maxlength attribute. The value if the attribute is in number. Here are the other attributes of <textarea> tag − You can try to run the following code to limit the number of characters entered in textarea in an HTML form − <!DOCTYPE html> <html> <head> <title>HTML textarea Tag</title> </head> <body> <form action = "" method = "get"> What improvements you want in College? <br> <textarea rows = "5" cols = "40" maxlength = "100" name = "description"> Enter answer here... </textarea> <br> <input type = "submit" value = "submit" /> </form> </body> </html>
[ { "code": null, "e": 1447, "s": 1187, "text": "To add a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. To limit the number of characters entered in a textarea, use the maxlength attribute. The value if the attribute is in number." }, { "code": null, "e": 1497, "s": 1447, "text": "Here are the other attributes of <textarea> tag −" }, { "code": null, "e": 1609, "s": 1499, "text": "You can try to run the following code to limit the number of characters entered in textarea in an HTML form −" }, { "code": null, "e": 2064, "s": 1609, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML textarea Tag</title>\n </head>\n\n <body>\n <form action = \"\" method = \"get\">\n What improvements you want in College?\n <br>\n \n <textarea rows = \"5\" cols = \"40\" maxlength = \"100\" name = \"description\">\n Enter answer here...\n </textarea>\n <br>\n \n <input type = \"submit\" value = \"submit\" />\n </form>\n \n </body>\n</html>" } ]
Convert character array to string in C++
28 Dec, 2021 This article shows how to convert a character array to a string in C++. The std::string in c++ has a lot of inbuilt functions which makes implementation much easier than handling a character array. Hence, it would often be easier to work if we convert a character array to string.Examples: Input: char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' } ; Output: string s = "geeksforgeeks" ; Input: char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ; Output: string s = "coding" ; Method 1: Approach: Get the character array and its size.Create an empty string.Iterate through the character array.As you iterate keep on concatenating the characters we encounter in the character array to the string.Return the string. Get the character array and its size.Create an empty string.Iterate through the character array.As you iterate keep on concatenating the characters we encounter in the character array to the string.Return the string. Get the character array and its size. Create an empty string. Iterate through the character array. As you iterate keep on concatenating the characters we encounter in the character array to the string. Return the string. Below is the implementation of the above approach. C++ // Demonstrates conversion// from character array to string #include <bits/stdc++.h>using namespace std; // converts character array// to string and returns itstring convertToString(char* a, int size){ int i; string s = ""; for (i = 0; i < size; i++) { s = s + a[i]; } return s;} // Driver codeint main(){ char a[] = { 'C', 'O', 'D', 'E' }; char b[] = "geeksforgeeks"; int a_size = sizeof(a) / sizeof(char); int b_size = sizeof(b) / sizeof(char); string s_a = convertToString(a, a_size); string s_b = convertToString(b, b_size); cout << s_a << endl; cout << s_b << endl; return 0;} Method 2: The std::string has an inbuilt constructor which does the work for us. This constructor takes in a null-terminated character sequence as it’s input. However, we can use this method only at the time of string declaration and it cannot be used again for the same string because it uses a constructor which is only called when we declare a string.Approach: Get the character array and its size.Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor.Use the syntax: string string_name(character_array_name);Return the string. Get the character array and its size.Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor.Use the syntax: string string_name(character_array_name);Return the string. Get the character array and its size. Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor. Use the syntax: string string_name(character_array_name); Return the string. Below is the implementation of the above approach. C++ // Demonstrates conversion// from character array to string #include <bits/stdc++.h>using namespace std; // uses the constructor in string class// to convert character array to stringstring convertToString(char* a){ string s(a); // we cannot use this technique again // to store something in s // because we use constructors // which are only called // when the string is declared. // Remove commented portion // to see for yourself /* char demo[] = "gfg"; s(demo); // compilation error */ return s;} // Driver codeint main(){ char a[] = { 'C', 'O', 'D', 'E' }; char b[] = "geeksforgeeks"; string s_a = convertToString(a); string s_b = convertToString(b); cout << s_a << endl; cout << s_b << endl; return 0;} Method 3: Another way to do so would be to use an overloaded ‘=’ operator which is also available in the C++ std::string. Approach: Get the character array and its size.Declare a string.Use the overloaded ‘=’ operator to assign the characters in the character array to the string.Return the string. Get the character array and its size.Declare a string.Use the overloaded ‘=’ operator to assign the characters in the character array to the string.Return the string. Get the character array and its size. Declare a string. Use the overloaded ‘=’ operator to assign the characters in the character array to the string. Return the string. Below is the implementation of the above approach. C++ // Demonstrates conversion// from character array to string #include <bits/stdc++.h>using namespace std; // uses overloaded '=' operator from string class// to convert character array to stringstring convertToString(char* a){ string s = a; return s;} // Driver codeint main(){ char a[] = { 'C', 'O', 'D', 'E' }; char b[] = "geeksforgeeks"; string s_a = convertToString(a); string s_b = convertToString(b); cout << s_a << endl; cout << s_b << endl; return 0;} yogesh1331 cpp-strings C++ Strings cpp-strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Dec, 2021" }, { "code": null, "e": 345, "s": 53, "text": "This article shows how to convert a character array to a string in C++. The std::string in c++ has a lot of inbuilt functions which makes implementation much easier than handling a character array. Hence, it would often be easier to work if we convert a character array to string.Examples: " }, { "code": null, "e": 575, "s": 345, "text": "Input: char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',\n 'r', 'g', 'e', 'e', 'k', 's' } ;\nOutput: string s = \"geeksforgeeks\" ;\n\nInput: char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ;\nOutput: string s = \"coding\" ;" }, { "code": null, "e": 814, "s": 577, "text": "Method 1: Approach: Get the character array and its size.Create an empty string.Iterate through the character array.As you iterate keep on concatenating the characters we encounter in the character array to the string.Return the string." }, { "code": null, "e": 1031, "s": 814, "text": "Get the character array and its size.Create an empty string.Iterate through the character array.As you iterate keep on concatenating the characters we encounter in the character array to the string.Return the string." }, { "code": null, "e": 1069, "s": 1031, "text": "Get the character array and its size." }, { "code": null, "e": 1093, "s": 1069, "text": "Create an empty string." }, { "code": null, "e": 1130, "s": 1093, "text": "Iterate through the character array." }, { "code": null, "e": 1233, "s": 1130, "text": "As you iterate keep on concatenating the characters we encounter in the character array to the string." }, { "code": null, "e": 1252, "s": 1233, "text": "Return the string." }, { "code": null, "e": 1303, "s": 1252, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1307, "s": 1303, "text": "C++" }, { "code": "// Demonstrates conversion// from character array to string #include <bits/stdc++.h>using namespace std; // converts character array// to string and returns itstring convertToString(char* a, int size){ int i; string s = \"\"; for (i = 0; i < size; i++) { s = s + a[i]; } return s;} // Driver codeint main(){ char a[] = { 'C', 'O', 'D', 'E' }; char b[] = \"geeksforgeeks\"; int a_size = sizeof(a) / sizeof(char); int b_size = sizeof(b) / sizeof(char); string s_a = convertToString(a, a_size); string s_b = convertToString(b, b_size); cout << s_a << endl; cout << s_b << endl; return 0;}", "e": 1942, "s": 1307, "text": null }, { "code": null, "e": 2554, "s": 1942, "text": "Method 2: The std::string has an inbuilt constructor which does the work for us. This constructor takes in a null-terminated character sequence as it’s input. However, we can use this method only at the time of string declaration and it cannot be used again for the same string because it uses a constructor which is only called when we declare a string.Approach: Get the character array and its size.Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor.Use the syntax: string string_name(character_array_name);Return the string." }, { "code": null, "e": 2802, "s": 2554, "text": "Get the character array and its size.Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor.Use the syntax: string string_name(character_array_name);Return the string." }, { "code": null, "e": 2840, "s": 2802, "text": "Get the character array and its size." }, { "code": null, "e": 2976, "s": 2840, "text": "Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor." }, { "code": null, "e": 3034, "s": 2976, "text": "Use the syntax: string string_name(character_array_name);" }, { "code": null, "e": 3053, "s": 3034, "text": "Return the string." }, { "code": null, "e": 3104, "s": 3053, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 3108, "s": 3104, "text": "C++" }, { "code": "// Demonstrates conversion// from character array to string #include <bits/stdc++.h>using namespace std; // uses the constructor in string class// to convert character array to stringstring convertToString(char* a){ string s(a); // we cannot use this technique again // to store something in s // because we use constructors // which are only called // when the string is declared. // Remove commented portion // to see for yourself /* char demo[] = \"gfg\"; s(demo); // compilation error */ return s;} // Driver codeint main(){ char a[] = { 'C', 'O', 'D', 'E' }; char b[] = \"geeksforgeeks\"; string s_a = convertToString(a); string s_b = convertToString(b); cout << s_a << endl; cout << s_b << endl; return 0;}", "e": 3884, "s": 3108, "text": null }, { "code": null, "e": 4183, "s": 3884, "text": "Method 3: Another way to do so would be to use an overloaded ‘=’ operator which is also available in the C++ std::string. Approach: Get the character array and its size.Declare a string.Use the overloaded ‘=’ operator to assign the characters in the character array to the string.Return the string." }, { "code": null, "e": 4350, "s": 4183, "text": "Get the character array and its size.Declare a string.Use the overloaded ‘=’ operator to assign the characters in the character array to the string.Return the string." }, { "code": null, "e": 4388, "s": 4350, "text": "Get the character array and its size." }, { "code": null, "e": 4406, "s": 4388, "text": "Declare a string." }, { "code": null, "e": 4501, "s": 4406, "text": "Use the overloaded ‘=’ operator to assign the characters in the character array to the string." }, { "code": null, "e": 4520, "s": 4501, "text": "Return the string." }, { "code": null, "e": 4571, "s": 4520, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 4575, "s": 4571, "text": "C++" }, { "code": "// Demonstrates conversion// from character array to string #include <bits/stdc++.h>using namespace std; // uses overloaded '=' operator from string class// to convert character array to stringstring convertToString(char* a){ string s = a; return s;} // Driver codeint main(){ char a[] = { 'C', 'O', 'D', 'E' }; char b[] = \"geeksforgeeks\"; string s_a = convertToString(a); string s_b = convertToString(b); cout << s_a << endl; cout << s_b << endl; return 0;}", "e": 5064, "s": 4575, "text": null }, { "code": null, "e": 5075, "s": 5064, "text": "yogesh1331" }, { "code": null, "e": 5087, "s": 5075, "text": "cpp-strings" }, { "code": null, "e": 5091, "s": 5087, "text": "C++" }, { "code": null, "e": 5099, "s": 5091, "text": "Strings" }, { "code": null, "e": 5111, "s": 5099, "text": "cpp-strings" }, { "code": null, "e": 5119, "s": 5111, "text": "Strings" }, { "code": null, "e": 5123, "s": 5119, "text": "CPP" }, { "code": null, "e": 5221, "s": 5123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5248, "s": 5221, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 5291, "s": 5248, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5325, "s": 5291, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 5350, "s": 5325, "text": "unordered_map in C++ STL" }, { "code": null, "e": 5369, "s": 5350, "text": "Inheritance in C++" }, { "code": null, "e": 5415, "s": 5369, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 5440, "s": 5415, "text": "Reverse a string in Java" }, { "code": null, "e": 5500, "s": 5440, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5515, "s": 5500, "text": "C++ Data Types" } ]
TypeScript - Array reduce()
reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. array.reduce(callback[, initialValue]); callback − Function to execute on each value in the array. callback − Function to execute on each value in the array. initialValue − Object to use as the first argument to the first call of the callback. initialValue − Object to use as the first argument to the first call of the callback. Returns the reduced single value of the array. var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; }); console.log("total is : " + total ); On compiling, it will generate the same code in JavaScript. Its output is as follows − total is : 6
[ { "code": null, "e": 2320, "s": 2182, "text": "reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value." }, { "code": null, "e": 2361, "s": 2320, "text": "array.reduce(callback[, initialValue]);\n" }, { "code": null, "e": 2420, "s": 2361, "text": "callback − Function to execute on each value in the array." }, { "code": null, "e": 2479, "s": 2420, "text": "callback − Function to execute on each value in the array." }, { "code": null, "e": 2565, "s": 2479, "text": "initialValue − Object to use as the first argument to the first call of the callback." }, { "code": null, "e": 2651, "s": 2565, "text": "initialValue − Object to use as the first argument to the first call of the callback." }, { "code": null, "e": 2698, "s": 2651, "text": "Returns the reduced single value of the array." }, { "code": null, "e": 2803, "s": 2698, "text": "var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; }); \nconsole.log(\"total is : \" + total );\n" }, { "code": null, "e": 2863, "s": 2803, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2890, "s": 2863, "text": "Its output is as follows −" } ]
Print Binary Search Tree in Min Max Fashion
25 Oct, 2021 Given a Binary Search Tree (BST), the task is to print the BST in min-max fashion. What is min-max fashion? A min-max fashion means you have to print the maximum node first then the minimum then the second maximum then the second minimum and so on. Examples: Input: 100 / \ 20 500 / \ 10 30 \ 40 Output: 10 500 20 100 30 40 Input: 40 / \ 20 50 / \ \ 10 35 60 / / 25 55 Output: 10 60 20 55 25 50 35 40 Approach: Create an array inorder[] and store the inorder traversal of the given binary search tree.Since the inorder traversal of the binary search tree is sorted in ascending, initialise i = 0 and j = n – 1.Print inorder[i] and update i = i + 1.Print inorder[j] and update j = j – 1.Repeat steps 3 and 4 until all the elements have been printed. Create an array inorder[] and store the inorder traversal of the given binary search tree. Since the inorder traversal of the binary search tree is sorted in ascending, initialise i = 0 and j = n – 1. Print inorder[i] and update i = i + 1. Print inorder[j] and update j = j – 1. Repeat steps 3 and 4 until all the elements have been printed. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Structure of each node of BSTstruct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodenode* newNode(int item){ node* temp = new node(); temp->key = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a newnode with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treeint sizeOfTree(node* root){ if (root == NULL) { return 0; } // Calculate left size recursively int left = sizeOfTree(root->left); // Calculate right size recursively int right = sizeOfTree(root->right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTvoid printMinMaxOrderUtil(node* root, int inOrder[], int& index){ // Base condition if (root == NULL) { return; } // Left recursive call printMinMaxOrderUtil(root->left, inOrder, index); // Store elements in inorder array inOrder[index++] = root->key; // Right recursive call printMinMaxOrderUtil(root->right, inOrder, index);} // Function to print the// Min max order of BSTvoid printMinMaxOrder(node* root){ // Store the size of BST int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST int inOrder[numNode + 1]; int index = 0; // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder, index); int i = 0; index--; // While loop for printing elements // In front last order while (i < index) { cout << inOrder[i++] << " " << inOrder[index--] << " "; } if (i == index) { cout << inOrder[i] << endl; }} // Driver codeint main(){ struct node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); printMinMaxOrder(root); return 0;} // Java implementation of the approachclass GFG{ // Structure of each node of BSTstatic class node{ int key; node left, right;};static int index; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to insert a newnode with given key in BST */static node insert(node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treestatic int sizeOfTree(node root){ if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTstatic void printMinMaxOrderUtil(node root, int inOrder[]){ // Base condition if (root == null) { return; } // Left recursive call printMinMaxOrderUtil(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call printMinMaxOrderUtil(root.right, inOrder);} // Function to print the// Min max order of BSTstatic void printMinMaxOrder(node root){ // Store the size of BST int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST int []inOrder = new int[numNode + 1]; // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder); int i = 0; index--; // While loop for printing elements // In front last order while (i < index) { System.out.print(inOrder[i++] + " " + inOrder[index--] + " "); } if (i == index) { System.out.println(inOrder[i]); }} // Driver codepublic static void main(String[] args){ node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); printMinMaxOrder(root);}} // This code is contributed by 29AjayKumar # Python3 implementation of the approach # Structure of each node of BSTclass Node: def __init__(self,key): self.left = None self.right = None self.val = key def insert(root,node): if root is None: root = Node(node) else: if root.val < node: if root.right is None: root.right = Node(node) else: insert(root.right, node) else: if root.left is None: root.left = Node(node) else: insert(root.left, node) # Function to return the size of the treedef sizeOfTree(root): if root == None: return 0 # Calculate left size recursively left = sizeOfTree(root.left) # Calculate right size recursively right = sizeOfTree(root.right); # Return total size recursively return (left + right + 1) # Utility function to print the# Min max order of BSTdef printMinMaxOrderUtil(root, inOrder, index): # Base condition if root == None: return # Left recursive call printMinMaxOrderUtil(root.left, inOrder, index) # Store elements in inorder array inOrder[index[0]] = root.val index[0] += 1 # Right recursive call printMinMaxOrderUtil(root.right, inOrder, index) # Function to print the# Min max order of BSTdef printMinMaxOrder(root): # Store the size of BST numNode = sizeOfTree(root); # Take auxiliary array for storing # The inorder traversal of BST inOrder = [0] * (numNode + 1) index = 0 # Function call for printing # element in min max order ref = [index] printMinMaxOrderUtil(root, inOrder, ref) index = ref[0] i = 0; index -= 1 # While loop for printing elements # In front last order while (i < index): print (inOrder[i], inOrder[index], end = ' ') i += 1 index -= 1 if i == index: print(inOrder[i]) # Driver Coderoot = Node(50)insert(root, 30)insert(root, 20)insert(root, 40)insert(root, 70)insert(root, 60)insert(root, 80) printMinMaxOrder(root) # This code is contributed by Sadik Ali // C# implementation of the approachusing System; class GFG{ // Structure of each node of BSTclass node{ public int key; public node left, right;};static int index; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to insert a newnode with given key in BST */static node insert(node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treestatic int sizeOfTree(node root){ if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTstatic void printMinMaxOrderUtil(node root, int []inOrder){ // Base condition if (root == null) { return; } // Left recursive call printMinMaxOrderUtil(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call printMinMaxOrderUtil(root.right, inOrder);} // Function to print the// Min max order of BSTstatic void printMinMaxOrder(node root){ // Store the size of BST int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST int []inOrder = new int[numNode + 1]; // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder); int i = 0; index--; // While loop for printing elements // In front last order while (i < index) { Console.Write(inOrder[i++] + " " + inOrder[index--] + " "); } if (i == index) { Console.WriteLine(inOrder[i]); }} // Driver codepublic static void Main(String[] args){ node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); printMinMaxOrder(root);}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach // Structure of each node of BSTclass node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; var index = 0; // A utility function to create a new BST nodefunction newNode(item){ var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to insert a new// node with given key in BSTfunction insert(node, key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treefunction sizeOfTree(root){ if (root == null) { return 0; } // Calculate left size recursively var left = sizeOfTree(root.left); // Calculate right size recursively var right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTfunction printMinMaxOrderUtil(root, inOrder){ // Base condition if (root == null) { return; } // Left recursive call printMinMaxOrderUtil(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call printMinMaxOrderUtil(root.right, inOrder);} // Function to print the// Min max order of BSTfunction printMinMaxOrder(root){ // Store the size of BST var numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST var inOrder = Array(numNode+1); // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder); var i = 0; index--; // While loop for printing elements // In front last order while (i < index) { document.write(inOrder[i++] + " " + inOrder[index--] + " "); } if (i == index) { document.write(inOrder[i]); }} // Driver codevar root = null;root = insert(root, 50);insert(root, 30);insert(root, 20);insert(root, 40);insert(root, 70);insert(root, 60);insert(root, 80); printMinMaxOrder(root); // This code is contributed by noob2000 </script> 20 80 30 70 40 60 50 chsadik99 29AjayKumar princiraj1992 noob2000 prachisoda1234 Inorder Traversal Binary Search Tree Recursion Tree Recursion Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. set vs unordered_set in C++ STL Flatten BST to sorted list | Increasing order Largest BST in a Binary Tree | Set 2 Find median of BST in O(n) time and O(1) space Floor and Ceil from a BST Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Oct, 2021" }, { "code": null, "e": 301, "s": 52, "text": "Given a Binary Search Tree (BST), the task is to print the BST in min-max fashion. What is min-max fashion? A min-max fashion means you have to print the maximum node first then the minimum then the second maximum then the second minimum and so on." }, { "code": null, "e": 312, "s": 301, "text": "Examples: " }, { "code": null, "e": 726, "s": 312, "text": "Input: \n 100 \n / \\ \n 20 500 \n / \\ \n 10 30 \n \\ \n 40\nOutput: 10 500 20 100 30 40\n\nInput:\n 40 \n / \\ \n 20 50 \n / \\ \\ \n 10 35 60\n / / \n 25 55\nOutput: 10 60 20 55 25 50 35 40 " }, { "code": null, "e": 738, "s": 726, "text": "Approach: " }, { "code": null, "e": 1076, "s": 738, "text": "Create an array inorder[] and store the inorder traversal of the given binary search tree.Since the inorder traversal of the binary search tree is sorted in ascending, initialise i = 0 and j = n – 1.Print inorder[i] and update i = i + 1.Print inorder[j] and update j = j – 1.Repeat steps 3 and 4 until all the elements have been printed." }, { "code": null, "e": 1167, "s": 1076, "text": "Create an array inorder[] and store the inorder traversal of the given binary search tree." }, { "code": null, "e": 1277, "s": 1167, "text": "Since the inorder traversal of the binary search tree is sorted in ascending, initialise i = 0 and j = n – 1." }, { "code": null, "e": 1316, "s": 1277, "text": "Print inorder[i] and update i = i + 1." }, { "code": null, "e": 1355, "s": 1316, "text": "Print inorder[j] and update j = j – 1." }, { "code": null, "e": 1418, "s": 1355, "text": "Repeat steps 3 and 4 until all the elements have been printed." }, { "code": null, "e": 1471, "s": 1418, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1475, "s": 1471, "text": "C++" }, { "code": null, "e": 1480, "s": 1475, "text": "Java" }, { "code": null, "e": 1488, "s": 1480, "text": "Python3" }, { "code": null, "e": 1491, "s": 1488, "text": "C#" }, { "code": null, "e": 1502, "s": 1491, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Structure of each node of BSTstruct node { int key; struct node *left, *right;}; // A utility function to create a new BST nodenode* newNode(int item){ node* temp = new node(); temp->key = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a newnode with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treeint sizeOfTree(node* root){ if (root == NULL) { return 0; } // Calculate left size recursively int left = sizeOfTree(root->left); // Calculate right size recursively int right = sizeOfTree(root->right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTvoid printMinMaxOrderUtil(node* root, int inOrder[], int& index){ // Base condition if (root == NULL) { return; } // Left recursive call printMinMaxOrderUtil(root->left, inOrder, index); // Store elements in inorder array inOrder[index++] = root->key; // Right recursive call printMinMaxOrderUtil(root->right, inOrder, index);} // Function to print the// Min max order of BSTvoid printMinMaxOrder(node* root){ // Store the size of BST int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST int inOrder[numNode + 1]; int index = 0; // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder, index); int i = 0; index--; // While loop for printing elements // In front last order while (i < index) { cout << inOrder[i++] << \" \" << inOrder[index--] << \" \"; } if (i == index) { cout << inOrder[i] << endl; }} // Driver codeint main(){ struct node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); printMinMaxOrder(root); return 0;}", "e": 3978, "s": 1502, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Structure of each node of BSTstatic class node{ int key; node left, right;};static int index; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to insert a newnode with given key in BST */static node insert(node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treestatic int sizeOfTree(node root){ if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTstatic void printMinMaxOrderUtil(node root, int inOrder[]){ // Base condition if (root == null) { return; } // Left recursive call printMinMaxOrderUtil(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call printMinMaxOrderUtil(root.right, inOrder);} // Function to print the// Min max order of BSTstatic void printMinMaxOrder(node root){ // Store the size of BST int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST int []inOrder = new int[numNode + 1]; // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder); int i = 0; index--; // While loop for printing elements // In front last order while (i < index) { System.out.print(inOrder[i++] + \" \" + inOrder[index--] + \" \"); } if (i == index) { System.out.println(inOrder[i]); }} // Driver codepublic static void main(String[] args){ node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); printMinMaxOrder(root);}} // This code is contributed by 29AjayKumar", "e": 6495, "s": 3978, "text": null }, { "code": "# Python3 implementation of the approach # Structure of each node of BSTclass Node: def __init__(self,key): self.left = None self.right = None self.val = key def insert(root,node): if root is None: root = Node(node) else: if root.val < node: if root.right is None: root.right = Node(node) else: insert(root.right, node) else: if root.left is None: root.left = Node(node) else: insert(root.left, node) # Function to return the size of the treedef sizeOfTree(root): if root == None: return 0 # Calculate left size recursively left = sizeOfTree(root.left) # Calculate right size recursively right = sizeOfTree(root.right); # Return total size recursively return (left + right + 1) # Utility function to print the# Min max order of BSTdef printMinMaxOrderUtil(root, inOrder, index): # Base condition if root == None: return # Left recursive call printMinMaxOrderUtil(root.left, inOrder, index) # Store elements in inorder array inOrder[index[0]] = root.val index[0] += 1 # Right recursive call printMinMaxOrderUtil(root.right, inOrder, index) # Function to print the# Min max order of BSTdef printMinMaxOrder(root): # Store the size of BST numNode = sizeOfTree(root); # Take auxiliary array for storing # The inorder traversal of BST inOrder = [0] * (numNode + 1) index = 0 # Function call for printing # element in min max order ref = [index] printMinMaxOrderUtil(root, inOrder, ref) index = ref[0] i = 0; index -= 1 # While loop for printing elements # In front last order while (i < index): print (inOrder[i], inOrder[index], end = ' ') i += 1 index -= 1 if i == index: print(inOrder[i]) # Driver Coderoot = Node(50)insert(root, 30)insert(root, 20)insert(root, 40)insert(root, 70)insert(root, 60)insert(root, 80) printMinMaxOrder(root) # This code is contributed by Sadik Ali", "e": 8632, "s": 6495, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Structure of each node of BSTclass node{ public int key; public node left, right;};static int index; // A utility function to create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} /* A utility function to insert a newnode with given key in BST */static node insert(node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treestatic int sizeOfTree(node root){ if (root == null) { return 0; } // Calculate left size recursively int left = sizeOfTree(root.left); // Calculate right size recursively int right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTstatic void printMinMaxOrderUtil(node root, int []inOrder){ // Base condition if (root == null) { return; } // Left recursive call printMinMaxOrderUtil(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call printMinMaxOrderUtil(root.right, inOrder);} // Function to print the// Min max order of BSTstatic void printMinMaxOrder(node root){ // Store the size of BST int numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST int []inOrder = new int[numNode + 1]; // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder); int i = 0; index--; // While loop for printing elements // In front last order while (i < index) { Console.Write(inOrder[i++] + \" \" + inOrder[index--] + \" \"); } if (i == index) { Console.WriteLine(inOrder[i]); }} // Driver codepublic static void Main(String[] args){ node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); printMinMaxOrder(root);}} // This code is contributed by PrinciRaj1992", "e": 11164, "s": 8632, "text": null }, { "code": "<script> // Javascript implementation of the approach // Structure of each node of BSTclass node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; var index = 0; // A utility function to create a new BST nodefunction newNode(item){ var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to insert a new// node with given key in BSTfunction insert(node, key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to return the size of the treefunction sizeOfTree(root){ if (root == null) { return 0; } // Calculate left size recursively var left = sizeOfTree(root.left); // Calculate right size recursively var right = sizeOfTree(root.right); // Return total size recursively return (left + right + 1);} // Utility function to print the// Min max order of BSTfunction printMinMaxOrderUtil(root, inOrder){ // Base condition if (root == null) { return; } // Left recursive call printMinMaxOrderUtil(root.left, inOrder); // Store elements in inorder array inOrder[index++] = root.key; // Right recursive call printMinMaxOrderUtil(root.right, inOrder);} // Function to print the// Min max order of BSTfunction printMinMaxOrder(root){ // Store the size of BST var numNode = sizeOfTree(root); // Take auxiliary array for storing // The inorder traversal of BST var inOrder = Array(numNode+1); // Function call for printing // element in min max order printMinMaxOrderUtil(root, inOrder); var i = 0; index--; // While loop for printing elements // In front last order while (i < index) { document.write(inOrder[i++] + \" \" + inOrder[index--] + \" \"); } if (i == index) { document.write(inOrder[i]); }} // Driver codevar root = null;root = insert(root, 50);insert(root, 30);insert(root, 20);insert(root, 40);insert(root, 70);insert(root, 60);insert(root, 80); printMinMaxOrder(root); // This code is contributed by noob2000 </script>", "e": 13591, "s": 11164, "text": null }, { "code": null, "e": 13612, "s": 13591, "text": "20 80 30 70 40 60 50" }, { "code": null, "e": 13624, "s": 13614, "text": "chsadik99" }, { "code": null, "e": 13636, "s": 13624, "text": "29AjayKumar" }, { "code": null, "e": 13650, "s": 13636, "text": "princiraj1992" }, { "code": null, "e": 13659, "s": 13650, "text": "noob2000" }, { "code": null, "e": 13674, "s": 13659, "text": "prachisoda1234" }, { "code": null, "e": 13692, "s": 13674, "text": "Inorder Traversal" }, { "code": null, "e": 13711, "s": 13692, "text": "Binary Search Tree" }, { "code": null, "e": 13721, "s": 13711, "text": "Recursion" }, { "code": null, "e": 13726, "s": 13721, "text": "Tree" }, { "code": null, "e": 13736, "s": 13726, "text": "Recursion" }, { "code": null, "e": 13755, "s": 13736, "text": "Binary Search Tree" }, { "code": null, "e": 13760, "s": 13755, "text": "Tree" }, { "code": null, "e": 13858, "s": 13760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13890, "s": 13858, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 13936, "s": 13890, "text": "Flatten BST to sorted list | Increasing order" }, { "code": null, "e": 13973, "s": 13936, "text": "Largest BST in a Binary Tree | Set 2" }, { "code": null, "e": 14020, "s": 13973, "text": "Find median of BST in O(n) time and O(1) space" }, { "code": null, "e": 14046, "s": 14020, "text": "Floor and Ceil from a BST" }, { "code": null, "e": 14106, "s": 14046, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 14191, "s": 14106, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 14201, "s": 14191, "text": "Recursion" }, { "code": null, "e": 14228, "s": 14201, "text": "Program for Tower of Hanoi" } ]
GATE | GATE CS 2012 | Question 4
28 Jun, 2021 Assuming P != NP, which of the following is true ? (A) NP-complete = NP (B) NP-complete P = (C) NP-hard = NP (D) P = NP-complete (A) A(B) B(C) C(D) DAnswer: (B)Explanation: The answer is B (no NP-Complete problem can be solved in polynomial time). Because, if one NP-Complete problem can be solved in polynomial time, then all NP problems can solved in polynomial time. If that is the case, then NP and P set become same which contradicts the given condition. Related Article:NP-Completeness | Set 1 (Introduction)P versus NP problem (Wikipedia)Quiz of this Question GATE-CS-2012 GATE-GATE CS 2012 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 2008 | Question 40 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31 GATE | GATE IT 2006 | Question 20
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 160, "s": 28, "text": "Assuming P != NP, which of the following is true ?\n(A) NP-complete = NP\n(B) NP-complete P = \n(C) NP-hard = NP\n(D) P = NP-complete\n" }, { "code": null, "e": 204, "s": 160, "text": "(A) A(B) B(C) C(D) DAnswer: (B)Explanation:" }, { "code": null, "e": 491, "s": 204, "text": "The answer is B (no NP-Complete problem can be solved in polynomial time). Because, if one NP-Complete problem can be solved in polynomial time, then all NP problems can solved in polynomial time. If that is the case, then NP and P set become same which contradicts the given condition." }, { "code": null, "e": 598, "s": 491, "text": "Related Article:NP-Completeness | Set 1 (Introduction)P versus NP problem (Wikipedia)Quiz of this Question" }, { "code": null, "e": 611, "s": 598, "text": "GATE-CS-2012" }, { "code": null, "e": 629, "s": 611, "text": "GATE-GATE CS 2012" }, { "code": null, "e": 634, "s": 629, "text": "GATE" }, { "code": null, "e": 732, "s": 634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 774, "s": 732, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 836, "s": 774, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 870, "s": 836, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 912, "s": 870, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 946, "s": 912, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 988, "s": 946, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1022, "s": 988, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 1056, "s": 1022, "text": "GATE | GATE CS 1996 | Question 38" }, { "code": null, "e": 1090, "s": 1056, "text": "GATE | GATE-CS-2004 | Question 31" } ]
Is it possible to assign a reference to "this" in java?
The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using it, you can refer the members of a class such as constructors, variables, and methods. According to the definition "this" is a keyword which acts as a reference to the current object (the object from whose constructor/method you are using it), its value id is fixed. Therefore, you cannot assign a new reference value to it. Moreover, it is just a keyword, not a variable. Still, if you try to it assign a reference value to "this" it leads to a compilation error. In the following Java program, the class (ExampleClass) has two private variables name, age and, a parameterized constructor which instantiates these variables. From a method named display, we are trying to assign a new value to "this". Live Demo public class ExampleClass { private String name; private int age; public ExampleClass(String name, int age){ this.name = name; this.age = age; } public void display(){ this = new ExampleClass("krishna", 23); } } On compiling, this program gives you an error as shown below − ExampleClass.java:14: error: cannot assign a value to final variable this this = new ExampleClass("krishna", 23); ^ 1 error
[ { "code": null, "e": 1397, "s": 1187, "text": "The \"this\" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using it, you can refer the members of a class such as constructors, variables, and methods." }, { "code": null, "e": 1683, "s": 1397, "text": "According to the definition \"this\" is a keyword which acts as a reference to the current object (the object from whose constructor/method you are using it), its value id is fixed. Therefore, you cannot assign a new reference value to it. Moreover, it is just a keyword, not a variable." }, { "code": null, "e": 1775, "s": 1683, "text": "Still, if you try to it assign a reference value to \"this\" it leads to a compilation error." }, { "code": null, "e": 2012, "s": 1775, "text": "In the following Java program, the class (ExampleClass) has two private variables name, age and, a parameterized constructor which instantiates these variables. From a method named display, we are trying to assign a new value to \"this\"." }, { "code": null, "e": 2023, "s": 2012, "text": " Live Demo" }, { "code": null, "e": 2271, "s": 2023, "text": "public class ExampleClass {\n private String name;\n private int age;\n public ExampleClass(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void display(){\n this = new ExampleClass(\"krishna\", 23);\n }\n}" }, { "code": null, "e": 2334, "s": 2271, "text": "On compiling, this program gives you an error as shown below −" }, { "code": null, "e": 2470, "s": 2334, "text": "ExampleClass.java:14: error: cannot assign a value to final variable this\n this = new ExampleClass(\"krishna\", 23);\n ^\n1 error" } ]
How to Install Python Pandas on Windows and Linux?
27 Feb, 2020 Pandas in Python is a package that is written for data analysis and manipulation. Pandas offer various operations and data structures to perform numerical data manipulations and time series. Pandas is an open-source library that is built over Numpy libraries. Pandas library is known for its high productivity and high performance. Pandas is popular because it makes importing and analyzing data much easier. Pandas programs can be written on any plain text editor like notepad, notepad++, or anything of that sort and saved with a .py extension. To begin with, writing Pandas Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below: To check if your device is pre-installed with Python or not, just go to the Command line(search for cmd in the Run dialog( + R).Now run the following command: python --version If Python is already installed, it will generate a message with the Python version available. To install Python, please visit: How to Install Python on Windows or Linux? Pandas can be installed in multiple ways on Windows and on Linux. Various different ways are listed below: Python Pandas can be installed on Windows in two ways: Using pip Using Anaconda PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI).Pandas can be installed using PIP by the use of the following command: pip install pandas Anaconda is open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. If your system is not pre-equipped with Anaconda Navigator, you can learn how to install Anaconda Navigator on Windows or Linux? Steps to Install Pandas using Anaconda Navigator: Step 1: Search for Anaconda Navigator in Start Menu and open it. Step 2: Click on the Environment tab and then click on the create button to create a new Pandas Environment. Step 3: Give a name to your Environment, e.g. Pandas and then choose a python version to run in the environment. Now click on the Create button to create Pandas Environment. Step 4: Now click on the Pandas Environment created to activate it. Step 5: In the list above package names, select All to filter all the packages. Step 6: Now in the Search Bar, look for ‘Pandas‘. Select the Pandas package for Installation. Step 7: Now Right Click on the checkbox given before the name of the package and then go to ‘Mark for specific version installation‘. Now select the version that you want to install. Step 8: Click on the Apply button to install the Pandas Package. Step 9: Finish the Installation process by clicking on the Apply button. Step 10: Now to open the Pandas Environment, click on the Green Arrow on the right of package name and select the Console with which you want to begin your Pandas programming. Pandas Terminal Window: To install Pandas on Linux, just type the following command in the Terminal Window and press Enter. Linux will automatically download and install the packages and files required to run Pandas Environment in Python: pip3 install pandas Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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 ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Feb, 2020" }, { "code": null, "e": 461, "s": 52, "text": "Pandas in Python is a package that is written for data analysis and manipulation. Pandas offer various operations and data structures to perform numerical data manipulations and time series. Pandas is an open-source library that is built over Numpy libraries. Pandas library is known for its high productivity and high performance. Pandas is popular because it makes importing and analyzing data much easier." }, { "code": null, "e": 816, "s": 461, "text": "Pandas programs can be written on any plain text editor like notepad, notepad++, or anything of that sort and saved with a .py extension. To begin with, writing Pandas Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:" }, { "code": null, "e": 975, "s": 816, "text": "To check if your device is pre-installed with Python or not, just go to the Command line(search for cmd in the Run dialog( + R).Now run the following command:" }, { "code": null, "e": 993, "s": 975, "text": "python --version\n" }, { "code": null, "e": 1087, "s": 993, "text": "If Python is already installed, it will generate a message with the Python version available." }, { "code": null, "e": 1163, "s": 1087, "text": "To install Python, please visit: How to Install Python on Windows or Linux?" }, { "code": null, "e": 1270, "s": 1163, "text": "Pandas can be installed in multiple ways on Windows and on Linux. Various different ways are listed below:" }, { "code": null, "e": 1325, "s": 1270, "text": "Python Pandas can be installed on Windows in two ways:" }, { "code": null, "e": 1335, "s": 1325, "text": "Using pip" }, { "code": null, "e": 1350, "s": 1335, "text": "Using Anaconda" }, { "code": null, "e": 1623, "s": 1350, "text": "PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI).Pandas can be installed using PIP by the use of the following command:" }, { "code": null, "e": 1642, "s": 1623, "text": "pip install pandas" }, { "code": null, "e": 3085, "s": 1642, "text": "Anaconda is open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. If your system is not pre-equipped with Anaconda Navigator, you can learn how to install Anaconda Navigator on Windows or Linux? Steps to Install Pandas using Anaconda Navigator: Step 1: Search for Anaconda Navigator in Start Menu and open it. Step 2: Click on the Environment tab and then click on the create button to create a new Pandas Environment. Step 3: Give a name to your Environment, e.g. Pandas and then choose a python version to run in the environment. Now click on the Create button to create Pandas Environment. Step 4: Now click on the Pandas Environment created to activate it. Step 5: In the list above package names, select All to filter all the packages. Step 6: Now in the Search Bar, look for ‘Pandas‘. Select the Pandas package for Installation. Step 7: Now Right Click on the checkbox given before the name of the package and then go to ‘Mark for specific version installation‘. Now select the version that you want to install. Step 8: Click on the Apply button to install the Pandas Package. Step 9: Finish the Installation process by clicking on the Apply button. Step 10: Now to open the Pandas Environment, click on the Green Arrow on the right of package name and select the Console with which you want to begin your Pandas programming. Pandas Terminal Window:" }, { "code": null, "e": 3300, "s": 3085, "text": "To install Pandas on Linux, just type the following command in the Terminal Window and press Enter. Linux will automatically download and install the packages and files required to run Pandas Environment in Python:" }, { "code": null, "e": 3321, "s": 3300, "text": "pip3 install pandas " }, { "code": null, "e": 3335, "s": 3321, "text": "Python-pandas" }, { "code": null, "e": 3342, "s": 3335, "text": "Python" }, { "code": null, "e": 3440, "s": 3342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3468, "s": 3440, "text": "Read JSON file using Python" }, { "code": null, "e": 3518, "s": 3468, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3540, "s": 3518, "text": "Python map() function" }, { "code": null, "e": 3584, "s": 3540, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3626, "s": 3584, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3648, "s": 3626, "text": "Enumerate() in Python" }, { "code": null, "e": 3683, "s": 3648, "text": "Read a file line by line in Python" }, { "code": null, "e": 3709, "s": 3683, "text": "Python String | replace()" }, { "code": null, "e": 3741, "s": 3709, "text": "How to Install PIP on Windows ?" } ]
{{ form.as_p }} – Render Django Forms as paragraph
13 Feb, 2020 Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as paragraphs in the template. Illustration of {{ form.as_p }} 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 ? Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number" ) password = forms.CharField(widget = forms.PasswordInput()) Now we need a View to render this form into a template. Let’s create a view, from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context) Finally, we will create the template where we need the form to be placed. In templates > home.html, <form action = "" method = "post"> {% csrf_token %} {{form.as_p }} <input type="submit" value=Submit"></form> Here {{ form.as_p }} will render them wrapped in <p> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/ Let’s check the source code whether the form is rendered as a paragraph or not. By rendering as a paragraph it is meant that all input fields will be enclosed in <p> tags.Here is the demonstration, {{ form.as_table }} will render them as table cells wrapped in <tr> tags {{ form.as_ul }} will render them wrapped in <li> tags NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Feb, 2020" }, { "code": null, "e": 452, "s": 53, "text": "Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. Rendering Django Forms in the template may seem messy at times but with proper knowledge of Django Forms and attributes of fields, one can easily create excellent Form with all powerful features. In this article, Form is rendered as paragraphs in the template." }, { "code": null, "e": 568, "s": 452, "text": "Illustration of {{ form.as_p }} using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 655, "s": 568, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 706, "s": 655, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 739, "s": 706, "text": "How to Create an App in Django ?" }, { "code": null, "e": 852, "s": 739, "text": "Let’s create a sample Django Form to render it and show as an example. In geeks > forms.py, enter following code" }, { "code": "from django import forms # creating a form class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = \"Enter 6 digit roll number\" ) password = forms.CharField(widget = forms.PasswordInput())", "e": 1209, "s": 852, "text": null }, { "code": null, "e": 1286, "s": 1209, "text": "Now we need a View to render this form into a template. Let’s create a view," }, { "code": "from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, \"home.html\", context)", "e": 1496, "s": 1286, "text": null }, { "code": null, "e": 1596, "s": 1496, "text": "Finally, we will create the template where we need the form to be placed. In templates > home.html," }, { "code": "<form action = \"\" method = \"post\"> {% csrf_token %} {{form.as_p }} <input type=\"submit\" value=Submit\"></form>", "e": 1715, "s": 1596, "text": null }, { "code": null, "e": 1857, "s": 1715, "text": "Here {{ form.as_p }} will render them wrapped in <p> tags. Let’s check whether this is working acordingly or not. Open http://localhost:8000/" }, { "code": null, "e": 2055, "s": 1857, "text": "Let’s check the source code whether the form is rendered as a paragraph or not. By rendering as a paragraph it is meant that all input fields will be enclosed in <p> tags.Here is the demonstration," }, { "code": null, "e": 2128, "s": 2055, "text": "{{ form.as_table }} will render them as table cells wrapped in <tr> tags" }, { "code": null, "e": 2183, "s": 2128, "text": "{{ form.as_ul }} will render them wrapped in <li> tags" }, { "code": null, "e": 2195, "s": 2183, "text": "NaveenArora" }, { "code": null, "e": 2208, "s": 2195, "text": "Django-forms" }, { "code": null, "e": 2222, "s": 2208, "text": "Python Django" }, { "code": null, "e": 2229, "s": 2222, "text": "Python" } ]
Java Program to Reverse a Number
08 Jul, 2022 Reversing a number means that the digit at the first position should be swapped with the last digit, the second digit will be swapped with the second last digit, and so on till the middle element, To reverse a number following steps should be performed: Take the number’s modulo by 10 Multiply the reverse number by 10 and add modulo value into the reverse number. Divide the number by 10. Repeat above steps until number becomes zero. We can reverse a number in java using two methods. 1. Using While Loop: Simply apply the steps/algorithm discussed and terminate the loop when the number becomes zero. Take the number’s modulo by 10 Multiply the reverse number by 10 and add modulo value into the reverse number. Divide the number by 10. Repeat the above steps until the number becomes zero. Below is the implementation of the above approach: Java // Java program to reverse a number import java.io.*; class GFG { // Function to reverse the number static int reverse(int n){ int rev = 0; // reversed number int rem; // remainder while(n>0){ rem = n%10; rev = (rev*10) + rem; n = n/10; } return rev; } // Driver Function public static void main (String[] args) { int n = 4526; System.out.print("Reversed Number is "+ reverse(n)); }} Reversed Number is 6254 2. Using Recursion: In recursion, the final reverse value will be stored in the global ‘rev’ variable. Follow the below instructions. If the number becomes zero then terminate the recursion, this will be the base condition. Take the modulo and add it with the ‘rev*10’ multiplying. Divide the number by 10 and call the reverse function on this number after updating it to number/10. Below is the Java implementation of the recursion method. Java // Java program to reverse a number recursively import java.io.*; class GFG { // stores reversed number static int rev = 0; // Function to reverse the number static void reverse(int n){ if(n<=0) return ; int rem = n%10; // remainder rev = (rev*10) + rem; reverse(n/10); } // Driver Function public static void main (String[] args) { int n = 4526; reverse(n); System.out.print("Reversed Number is "+ rev); }} Reversed Number is 6254 Time Complexity : O(logn) ,where n is number Auxiliary Space: O(logn) aditya942003patil Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jul, 2022" }, { "code": null, "e": 250, "s": 53, "text": "Reversing a number means that the digit at the first position should be swapped with the last digit, the second digit will be swapped with the second last digit, and so on till the middle element," }, { "code": null, "e": 307, "s": 250, "text": "To reverse a number following steps should be performed:" }, { "code": null, "e": 338, "s": 307, "text": "Take the number’s modulo by 10" }, { "code": null, "e": 418, "s": 338, "text": "Multiply the reverse number by 10 and add modulo value into the reverse number." }, { "code": null, "e": 443, "s": 418, "text": "Divide the number by 10." }, { "code": null, "e": 489, "s": 443, "text": "Repeat above steps until number becomes zero." }, { "code": null, "e": 541, "s": 489, "text": "We can reverse a number in java using two methods. " }, { "code": null, "e": 564, "s": 541, "text": "1. Using While Loop: " }, { "code": null, "e": 662, "s": 564, "text": " Simply apply the steps/algorithm discussed and terminate the loop when the number becomes zero. " }, { "code": null, "e": 693, "s": 662, "text": "Take the number’s modulo by 10" }, { "code": null, "e": 773, "s": 693, "text": "Multiply the reverse number by 10 and add modulo value into the reverse number." }, { "code": null, "e": 798, "s": 773, "text": "Divide the number by 10." }, { "code": null, "e": 852, "s": 798, "text": "Repeat the above steps until the number becomes zero." }, { "code": null, "e": 903, "s": 852, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 908, "s": 903, "text": "Java" }, { "code": "// Java program to reverse a number import java.io.*; class GFG { // Function to reverse the number static int reverse(int n){ int rev = 0; // reversed number int rem; // remainder while(n>0){ rem = n%10; rev = (rev*10) + rem; n = n/10; } return rev; } // Driver Function public static void main (String[] args) { int n = 4526; System.out.print(\"Reversed Number is \"+ reverse(n)); }}", "e": 1421, "s": 908, "text": null }, { "code": null, "e": 1445, "s": 1421, "text": "Reversed Number is 6254" }, { "code": null, "e": 1466, "s": 1445, "text": "2. Using Recursion: " }, { "code": null, "e": 1580, "s": 1466, "text": "In recursion, the final reverse value will be stored in the global ‘rev’ variable. Follow the below instructions." }, { "code": null, "e": 1670, "s": 1580, "text": "If the number becomes zero then terminate the recursion, this will be the base condition." }, { "code": null, "e": 1728, "s": 1670, "text": "Take the modulo and add it with the ‘rev*10’ multiplying." }, { "code": null, "e": 1829, "s": 1728, "text": "Divide the number by 10 and call the reverse function on this number after updating it to number/10." }, { "code": null, "e": 1887, "s": 1829, "text": "Below is the Java implementation of the recursion method." }, { "code": null, "e": 1892, "s": 1887, "text": "Java" }, { "code": "// Java program to reverse a number recursively import java.io.*; class GFG { // stores reversed number static int rev = 0; // Function to reverse the number static void reverse(int n){ if(n<=0) return ; int rem = n%10; // remainder rev = (rev*10) + rem; reverse(n/10); } // Driver Function public static void main (String[] args) { int n = 4526; reverse(n); System.out.print(\"Reversed Number is \"+ rev); }}", "e": 2434, "s": 1892, "text": null }, { "code": null, "e": 2458, "s": 2434, "text": "Reversed Number is 6254" }, { "code": null, "e": 2503, "s": 2458, "text": "Time Complexity : O(logn) ,where n is number" }, { "code": null, "e": 2528, "s": 2503, "text": "Auxiliary Space: O(logn)" }, { "code": null, "e": 2546, "s": 2528, "text": "aditya942003patil" }, { "code": null, "e": 2553, "s": 2546, "text": "Picked" }, { "code": null, "e": 2558, "s": 2553, "text": "Java" }, { "code": null, "e": 2572, "s": 2558, "text": "Java Programs" }, { "code": null, "e": 2577, "s": 2572, "text": "Java" }, { "code": null, "e": 2675, "s": 2577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2690, "s": 2675, "text": "Stream In Java" }, { "code": null, "e": 2711, "s": 2690, "text": "Introduction to Java" }, { "code": null, "e": 2732, "s": 2711, "text": "Constructors in Java" }, { "code": null, "e": 2751, "s": 2732, "text": "Exceptions in Java" }, { "code": null, "e": 2768, "s": 2751, "text": "Generics in Java" }, { "code": null, "e": 2794, "s": 2768, "text": "Java Programming Examples" }, { "code": null, "e": 2828, "s": 2794, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2875, "s": 2828, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2913, "s": 2875, "text": "Factory method design pattern in Java" } ]
TypeScript - String toUpperCase()
This method returns the calling string value converted to uppercase. string.toUpperCase( ) Returns a string representing the specified object. var str = "Apples are round, and Apples are Juicy."; console.log(str.toUpperCase( )); On compiling, it will generate the same code in JavaScript. Its output is as follows − APPLES ARE ROUND, AND APPLES ARE JUICY.
[ { "code": null, "e": 2251, "s": 2182, "text": "This method returns the calling string value converted to uppercase." }, { "code": null, "e": 2274, "s": 2251, "text": "string.toUpperCase( )\n" }, { "code": null, "e": 2326, "s": 2274, "text": "Returns a string representing the specified object." }, { "code": null, "e": 2414, "s": 2326, "text": "var str = \"Apples are round, and Apples are Juicy.\"; \nconsole.log(str.toUpperCase( ));\n" }, { "code": null, "e": 2474, "s": 2414, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2501, "s": 2474, "text": "Its output is as follows −" } ]
Python | Swap commas and dots in a String
17 Feb, 2021 The problem is quite simple. Given a string, we need to replace all commas with dots and all dots with the commas. This can be achieved in two popular ways. Examples: Input : 14, 625, 498.002 Output : 14.625.498, 002 Using maketrans and translate() maketrans: This static method returns a translation table usable for str.translate(). This builds a translation table, which is a mapping of integers or characters to integers, strings, or None.translate: This returns a copy of the string where all characters occurring in the optional argument are removed, and the remaining characters have been mapped through the translation table, given by the maketrans table. For more reference visit Python String Methods. Python3 # Python code to replace, with . and vice-versadef Replace(str1): maketrans = str1.maketrans final = str1.translate(maketrans(',.', '.,', ' ')) return final.replace(',', ", ") # Driving Codestring = "14, 625, 498.002"print(Replace(string)) Output: 14.625.498, 002 Using replace() This is more of a logical approach in which we swap the symbols considering third variables. The replace method can also be used to replace the methods in strings. We can convert “, ” to a symbol then convert “.” to “, ” and the symbol to “.”. For more reference visit Python String Methods. Example: Python3 def Replace(str1): str1 = str1.replace(', ', 'third') str1 = str1.replace('.', ', ') str1 = str1.replace('third', '.') return str1 string = "14, 625, 498.002"print(Replace(string)) Output: 14.625.498, 002 rahulpoluri314 Python string-programs python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Feb, 2021" }, { "code": null, "e": 222, "s": 54, "text": "The problem is quite simple. Given a string, we need to replace all commas with dots and all dots with the commas. This can be achieved in two popular ways. Examples: " }, { "code": null, "e": 273, "s": 222, "text": "Input : 14, 625, 498.002\nOutput : 14.625.498, 002 " }, { "code": null, "e": 305, "s": 273, "text": "Using maketrans and translate()" }, { "code": null, "e": 770, "s": 305, "text": "maketrans: This static method returns a translation table usable for str.translate(). This builds a translation table, which is a mapping of integers or characters to integers, strings, or None.translate: This returns a copy of the string where all characters occurring in the optional argument are removed, and the remaining characters have been mapped through the translation table, given by the maketrans table. For more reference visit Python String Methods. " }, { "code": null, "e": 778, "s": 770, "text": "Python3" }, { "code": "# Python code to replace, with . and vice-versadef Replace(str1): maketrans = str1.maketrans final = str1.translate(maketrans(',.', '.,', ' ')) return final.replace(',', \", \") # Driving Codestring = \"14, 625, 498.002\"print(Replace(string))", "e": 1028, "s": 778, "text": null }, { "code": null, "e": 1037, "s": 1028, "text": "Output: " }, { "code": null, "e": 1053, "s": 1037, "text": "14.625.498, 002" }, { "code": null, "e": 1069, "s": 1053, "text": "Using replace()" }, { "code": null, "e": 1372, "s": 1069, "text": "This is more of a logical approach in which we swap the symbols considering third variables. The replace method can also be used to replace the methods in strings. We can convert “, ” to a symbol then convert “.” to “, ” and the symbol to “.”. For more reference visit Python String Methods. Example: " }, { "code": null, "e": 1380, "s": 1372, "text": "Python3" }, { "code": "def Replace(str1): str1 = str1.replace(', ', 'third') str1 = str1.replace('.', ', ') str1 = str1.replace('third', '.') return str1 string = \"14, 625, 498.002\"print(Replace(string))", "e": 1577, "s": 1380, "text": null }, { "code": null, "e": 1586, "s": 1577, "text": "Output: " }, { "code": null, "e": 1602, "s": 1586, "text": "14.625.498, 002" }, { "code": null, "e": 1617, "s": 1602, "text": "rahulpoluri314" }, { "code": null, "e": 1640, "s": 1617, "text": "Python string-programs" }, { "code": null, "e": 1654, "s": 1640, "text": "python-string" }, { "code": null, "e": 1661, "s": 1654, "text": "Python" }, { "code": null, "e": 1759, "s": 1661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1791, "s": 1759, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1818, "s": 1791, "text": "Python Classes and Objects" }, { "code": null, "e": 1839, "s": 1818, "text": "Python OOPs Concepts" }, { "code": null, "e": 1870, "s": 1839, "text": "Python | os.path.join() method" }, { "code": null, "e": 1926, "s": 1870, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1949, "s": 1926, "text": "Introduction To PYTHON" }, { "code": null, "e": 1991, "s": 1949, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2033, "s": 1991, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2072, "s": 2033, "text": "Python | datetime.timedelta() function" } ]
Get first n records of a Pandas DataFrame
05 Aug, 2020 Let us see how to fetch the first n records of a Pandas DataFrame. Lets first make a dataframe : # Import Required Libraryimport pandas as pd # Create a dictionary for the dataframedict = {'Name' : ['Sumit Tyagi', 'Sukritin', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age':[22, 20, 45, 21, 22], 'Marks':[90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframeprint(df) Output : Method 1 : Using head() method. Use pandas.DataFrame.head(n) to get the first n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the start). By default n = 5, it return first 5 rows if value of n is not passed to the method. # Getting first 3 rows from dfdf_first_3 = df.head(3) # Printing df_first_3print(df_first_3) Output : Method 2 : Using pandas.DataFrame.iloc(). Use pandas.DataFrame.iloc() to get the first n rows. It is similar to the list slicing. # Getting first 3 rows from dfdf_first_3 = df.iloc[:3] # Printing df_first_3print(df_first_3) Output : Method 3 : Display first n records of specific columns # Getting first 2 rows of columns Age and Marks from dfdf_first_2 = df[['Age', 'Marks']].head(2) # Printing df_first_2print(df_first_2) Output : Method 4 : Display first n records from last n columns. Display first n records for the last n columns using pandas.DataFrame.iloc() # Getting first n rows and last n columns from dfdf_first_2_row_last_2_col = df.iloc[:2, -2:] # Printing df_first_2_row_last_2_colprint(df_first_2_row_last_2_col) Output : Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Aug, 2020" }, { "code": null, "e": 125, "s": 28, "text": "Let us see how to fetch the first n records of a Pandas DataFrame. Lets first make a dataframe :" }, { "code": "# Import Required Libraryimport pandas as pd # Create a dictionary for the dataframedict = {'Name' : ['Sumit Tyagi', 'Sukritin', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age':[22, 20, 45, 21, 22], 'Marks':[90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframeprint(df)", "e": 503, "s": 125, "text": null }, { "code": null, "e": 514, "s": 503, "text": "Output : " }, { "code": null, "e": 783, "s": 514, "text": "Method 1 : Using head() method. Use pandas.DataFrame.head(n) to get the first n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the start). By default n = 5, it return first 5 rows if value of n is not passed to the method." }, { "code": "# Getting first 3 rows from dfdf_first_3 = df.head(3) # Printing df_first_3print(df_first_3)", "e": 877, "s": 783, "text": null }, { "code": null, "e": 888, "s": 877, "text": "Output : " }, { "code": null, "e": 1018, "s": 888, "text": "Method 2 : Using pandas.DataFrame.iloc(). Use pandas.DataFrame.iloc() to get the first n rows. It is similar to the list slicing." }, { "code": "# Getting first 3 rows from dfdf_first_3 = df.iloc[:3] # Printing df_first_3print(df_first_3)", "e": 1113, "s": 1018, "text": null }, { "code": null, "e": 1122, "s": 1113, "text": "Output :" }, { "code": null, "e": 1177, "s": 1122, "text": "Method 3 : Display first n records of specific columns" }, { "code": "# Getting first 2 rows of columns Age and Marks from dfdf_first_2 = df[['Age', 'Marks']].head(2) # Printing df_first_2print(df_first_2)", "e": 1314, "s": 1177, "text": null }, { "code": null, "e": 1325, "s": 1314, "text": "Output : " }, { "code": null, "e": 1458, "s": 1325, "text": "Method 4 : Display first n records from last n columns. Display first n records for the last n columns using pandas.DataFrame.iloc()" }, { "code": "# Getting first n rows and last n columns from dfdf_first_2_row_last_2_col = df.iloc[:2, -2:] # Printing df_first_2_row_last_2_colprint(df_first_2_row_last_2_col)", "e": 1622, "s": 1458, "text": null }, { "code": null, "e": 1631, "s": 1622, "text": "Output :" }, { "code": null, "e": 1655, "s": 1631, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1678, "s": 1655, "text": "Python Pandas-exercise" }, { "code": null, "e": 1692, "s": 1678, "text": "Python-pandas" }, { "code": null, "e": 1699, "s": 1692, "text": "Python" }, { "code": null, "e": 1797, "s": 1699, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1829, "s": 1797, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1856, "s": 1829, "text": "Python Classes and Objects" }, { "code": null, "e": 1877, "s": 1856, "text": "Python OOPs Concepts" }, { "code": null, "e": 1900, "s": 1877, "text": "Introduction To PYTHON" }, { "code": null, "e": 1956, "s": 1900, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1987, "s": 1956, "text": "Python | os.path.join() method" }, { "code": null, "e": 2029, "s": 1987, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2071, "s": 2029, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2110, "s": 2071, "text": "Python | Get unique values from a list" } ]
Program for Spearman’s Rank Correlation
19 Aug, 2021 Prerequisite : Correlation CoefficientGiven two arrays X[] and Y[]. Find Spearman’s Rank Correlation. In Spearman rank correlation instead of working with the data values themselves (as discussed in Correlation coefficient), it work with the ranks of these values. The observations are first ranked and then these ranks are used in correlation. The Algorithm for this correlation is as follows Rank each observation in X and store it in Rank_X Rank each observation in Y and store it in Rank_Y Obtain Pearson Correlation Coefficient for Rank_X and Rank_Y The formula used to calculate Pearson’s Correlation Coefficient (r or rho) of sets X and Y is as follows: Algorithm for calculating Pearson’s Coefficient of Sets X and Y function correlationCoefficient(X, Y) n = X.size sigma_x = sigma_y = sigma_xy = 0 sigma_xsq = sigma_ysq = 0 for i in 0...N-1 sigma_x = sigma_x + X[i] sigma_y = sigma_y + Y[i] sigma_xy = sigma_xy + X[i] * Y[i] sigma_xsq = sigma_xsq + X[i] * X[i] sigma_ysq = sigma_ysq + Y[i] * Y[i] num =( n * sigma_xy - sigma_x * sigma_y) den = sqrt( [n*sigma_xsq - (sigma_x)^ 2]*[ n*sigma_ysq - (sigma_y) ^ 2] ) return num/den While assigning ranks, it may encounter ties i.e two or more observations having the same rank. To resolve ties, this will use fractional ranking scheme. In this scheme, if n observations have the same rank then each observation gets a fractional rank given by: fractional_rank = (rank) + (n-1)/2 The next rank that gets assigned is rank + n and not rank + 1. For instance, if the 3 items have same rank r, then each gets fractional_rank as given above. The next rank that can be given to another observation is r + 3. Note that fractional ranks need not be fractions. They are the arithmetic mean of n consecutive ranks ex r, r + 1, r + 2 ... r + n-1. (r + r+1 + r+2 + ... + r+n-1) / n = r + (n-1)/2 Some Examples : Input : X = [15 18 19 20 21] Y = [25 26 28 27 29] Solution : Rank_X = [1 2 3 4 5] Rank_Y = [1 2 4 3 5 ] sigma_x = 1+2+3+4+5 = 15 sigma_y = 1+2+4+3+5 = 15 sigma_xy = 1*2+2*2+3*4+4*3+5*5 = 54 sigma_xsq = 1*1+2*2+3*3+4*4+5*5 = 55 sigma_ysq = 1*1+2*2+3*3+4*4+5*5 = 55 Substitute values in formula Coefficient = Pearson(Rank_X, Rank_Y) = 0.9 Input: X = [15 18 21 15 21 ] Y = [25 25 27 27 27 ] Solution: Rank_X = [1.5 3 4.5 1.5 4.5] Rank_Y = [1.5 1.5 4 4 4] Calculate and substitute values of sigma_x, sigma_y, sigma_xy, sigma_xsq, sigma_ysq. Coefficient = Pearson(Rank_X, Rank_Y) = 0.456435 The Algorithm for fractional ranking scheme is given below: function rankify(X) N = X.size() // Vector to store ranks Rank_X(N) for i = 0 ... N-1 r = 1 and s = 1 // Count no of smaller elements in 0...i-1 for j = 0...i-1 if X[j] < X[i] r = r+1 if X[j] == X[i] s = s+1 // Count no of smaller elements in i+1...N-1 for j = i+1...N-1 if X[j] < X[i] r = r+1 if X[j] == X[i] s = s+1 //Assign Fractional Rank Rank_X[i] = r + (s-1) * 0.5 return Rank_X Note: There is a direct formula to calculate Spearman’s coefficient given by However we need to put in a correction term to resolve each tie and hence this formula has not been discussed. Calculating Spearman’s coefficient from the correlation coefficient of ranks is the most general method. A CPP Program to evaluate Spearman’s coefficient is given below: C++ // Program to find correlation// coefficient#include <iostream>#include <vector>#include <cmath>using namespace std; typedef vector<float> Vector; // Utility Function to print// a Vectorvoid printVector(const Vector &X){ for (auto i: X) cout << i << " "; cout << endl;} // Function returns the rank vector// of the set of observationsVector rankify(Vector & X) { int N = X.size(); // Rank Vector Vector Rank_X(N); for(int i = 0; i < N; i++) { int r = 1, s = 1; // Count no of smaller elements // in 0 to i-1 for(int j = 0; j < i; j++) { if (X[j] < X[i] ) r++; if (X[j] == X[i] ) s++; } // Count no of smaller elements // in i+1 to N-1 for (int j = i+1; j < N; j++) { if (X[j] < X[i] ) r++; if (X[j] == X[i] ) s++; } // Use Fractional Rank formula // fractional_rank = r + (n-1)/2 Rank_X[i] = r + (s-1) * 0.5; } // Return Rank Vector return Rank_X;} // function that returns// Pearson correlation coefficient.float correlationCoefficient (Vector &X, Vector &Y){ int n = X.size(); float sum_X = 0, sum_Y = 0, sum_XY = 0; float squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating // correlation coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y)); return corr;} // Driver functionint main(){ Vector X = {15,18,21, 15, 21}; Vector Y= {25,25,27,27,27}; // Get ranks of vector X Vector rank_x = rankify(X); // Get ranks of vector y Vector rank_y = rankify(Y); cout << "Vector X" << endl; printVector(X); // Print rank vector of X cout << "Rankings of X" << endl; printVector(rank_x); // Print Vector Y cout << "Vector Y" << endl; printVector(Y); // Print rank vector of Y cout << "Rankings of Y" << endl; printVector(rank_y); // Print Spearmans coefficient cout << "Spearman's Rank correlation: " << endl; cout<<correlationCoefficient(rank_x, rank_y); return 0;} Output: Vector X 15 18 21 15 21 Rankings of X 1.5 3 4.5 1.5 4.5 Vector Y 25 25 27 27 27 Rankings of Y 1.5 1.5 4 4 4 Spearman's Rank correlation: 0.456435 Python code to calculate Spearman’s Rank Correlation: Python3 # Import pandas and scipy.statsimport pandas as pdimport scipy.stats # Two lists x and yx = [15,18,21, 15, 21]y = [25,25,27,27,27] # Create a function that takes in x's and y'sdef spearmans_rank_correlation(x, y): # Calculate the rank of x's xranks = pd.Series(x).rank() print("Rankings of X:") print(xranks) # Calculate the ranking of the y's yranks = pd.Series(y).rank() print("Rankings of Y:") print(yranks) # Calculate Pearson's correlation coefficient on the ranked versions of the data print("Spearman's Rank correlation:",scipy.stats.pearsonr(xranks, yranks)[0]) # Call the functionspearmans_rank_correlation(x, y) # This code is contributed by Manish KC# profile: mkumarchaudhary06 Output: Rankings of X: 0 1.5 1 3.0 2 4.5 3 1.5 4 4.5 dtype: float64 Rankings of Y: 0 1.5 1 1.5 2 4.0 3 4.0 4 4.0 dtype: float64 Spearman's Rank correlation: 0.456435464588 Python code to calculate Spearman’s Correlation using Scipy There is one simple way to directly get the spearman’s correlation value using scipy. Python3 # Import scipy.statsimport scipy.stats # Two lists x and yx = [15,18,21, 15, 21]y = [25,25,27,27,27] print(scipy.stats.spearmanr(x, y)[0]) # This code is contributed by Manish KC# Profile: mkumarchaudhary06 Output: 0.45643546458763845 References:https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient mkumarchaudhary06 rajeev0719singh kalrap615 Fraction statistical-algorithms Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Aug, 2021" }, { "code": null, "e": 449, "s": 54, "text": "Prerequisite : Correlation CoefficientGiven two arrays X[] and Y[]. Find Spearman’s Rank Correlation. In Spearman rank correlation instead of working with the data values themselves (as discussed in Correlation coefficient), it work with the ranks of these values. The observations are first ranked and then these ranks are used in correlation. The Algorithm for this correlation is as follows " }, { "code": null, "e": 612, "s": 449, "text": "Rank each observation in X and store it in Rank_X \nRank each observation in Y and store it in Rank_Y \nObtain Pearson Correlation Coefficient for Rank_X and Rank_Y" }, { "code": null, "e": 784, "s": 612, "text": "The formula used to calculate Pearson’s Correlation Coefficient (r or rho) of sets X and Y is as follows: Algorithm for calculating Pearson’s Coefficient of Sets X and Y " }, { "code": null, "e": 1275, "s": 784, "text": "function correlationCoefficient(X, Y)\n n = X.size\n sigma_x = sigma_y = sigma_xy = 0\n sigma_xsq = sigma_ysq = 0\n for i in 0...N-1\n sigma_x = sigma_x + X[i]\n sigma_y = sigma_y + Y[i]\n sigma_xy = sigma_xy + X[i] * Y[i]\n sigma_xsq = sigma_xsq + X[i] * X[i]\n sigma_ysq = sigma_ysq + Y[i] * Y[i] \n \n num =( n * sigma_xy - sigma_x * sigma_y)\n den = sqrt( [n*sigma_xsq - (sigma_x)^ 2]*[ n*sigma_ysq - (sigma_y) ^ 2] )\n return num/den" }, { "code": null, "e": 1538, "s": 1275, "text": "While assigning ranks, it may encounter ties i.e two or more observations having the same rank. To resolve ties, this will use fractional ranking scheme. In this scheme, if n observations have the same rank then each observation gets a fractional rank given by: " }, { "code": null, "e": 1573, "s": 1538, "text": "fractional_rank = (rank) + (n-1)/2" }, { "code": null, "e": 1930, "s": 1573, "text": "The next rank that gets assigned is rank + n and not rank + 1. For instance, if the 3 items have same rank r, then each gets fractional_rank as given above. The next rank that can be given to another observation is r + 3. Note that fractional ranks need not be fractions. They are the arithmetic mean of n consecutive ranks ex r, r + 1, r + 2 ... r + n-1. " }, { "code": null, "e": 1979, "s": 1930, "text": "(r + r+1 + r+2 + ... + r+n-1) / n = r + (n-1)/2 " }, { "code": null, "e": 1996, "s": 1979, "text": "Some Examples : " }, { "code": null, "e": 2740, "s": 1996, "text": "Input : X = [15 18 19 20 21]\n Y = [25 26 28 27 29]\nSolution : Rank_X = [1 2 3 4 5]\n Rank_Y = [1 2 4 3 5 ]\n sigma_x = 1+2+3+4+5 = 15\n sigma_y = 1+2+4+3+5 = 15\n sigma_xy = 1*2+2*2+3*4+4*3+5*5 = 54\n sigma_xsq = 1*1+2*2+3*3+4*4+5*5 = 55\n sigma_ysq = 1*1+2*2+3*3+4*4+5*5 = 55\n Substitute values in formula\n Coefficient = Pearson(Rank_X, Rank_Y) = 0.9\n\nInput: X = [15 18 21 15 21 ]\n Y = [25 25 27 27 27 ]\nSolution: Rank_X = [1.5 3 4.5 1.5 4.5]\n Rank_Y = [1.5 1.5 4 4 4]\n Calculate and substitute values of sigma_x, sigma_y,\n sigma_xy, sigma_xsq, sigma_ysq.\n Coefficient = Pearson(Rank_X, Rank_Y) = 0.456435" }, { "code": null, "e": 2800, "s": 2740, "text": "The Algorithm for fractional ranking scheme is given below:" }, { "code": null, "e": 3407, "s": 2800, "text": "function rankify(X)\n N = X.size() \n\n // Vector to store ranks\n Rank_X(N)\n for i = 0 ... N-1\n r = 1 and s = 1\n\n // Count no of smaller elements in 0...i-1\n for j = 0...i-1\n if X[j] < X[i]\n r = r+1\n if X[j] == X[i]\n s = s+1\n \n // Count no of smaller elements in i+1...N-1\n for j = i+1...N-1\n if X[j] < X[i]\n r = r+1\n if X[j] == X[i]\n s = s+1\n \n //Assign Fractional Rank\n Rank_X[i] = r + (s-1) * 0.5\n \n return Rank_X " }, { "code": null, "e": 3702, "s": 3407, "text": "Note: There is a direct formula to calculate Spearman’s coefficient given by However we need to put in a correction term to resolve each tie and hence this formula has not been discussed. Calculating Spearman’s coefficient from the correlation coefficient of ranks is the most general method. " }, { "code": null, "e": 3767, "s": 3702, "text": "A CPP Program to evaluate Spearman’s coefficient is given below:" }, { "code": null, "e": 3771, "s": 3767, "text": "C++" }, { "code": "// Program to find correlation// coefficient#include <iostream>#include <vector>#include <cmath>using namespace std; typedef vector<float> Vector; // Utility Function to print// a Vectorvoid printVector(const Vector &X){ for (auto i: X) cout << i << \" \"; cout << endl;} // Function returns the rank vector// of the set of observationsVector rankify(Vector & X) { int N = X.size(); // Rank Vector Vector Rank_X(N); for(int i = 0; i < N; i++) { int r = 1, s = 1; // Count no of smaller elements // in 0 to i-1 for(int j = 0; j < i; j++) { if (X[j] < X[i] ) r++; if (X[j] == X[i] ) s++; } // Count no of smaller elements // in i+1 to N-1 for (int j = i+1; j < N; j++) { if (X[j] < X[i] ) r++; if (X[j] == X[i] ) s++; } // Use Fractional Rank formula // fractional_rank = r + (n-1)/2 Rank_X[i] = r + (s-1) * 0.5; } // Return Rank Vector return Rank_X;} // function that returns// Pearson correlation coefficient.float correlationCoefficient (Vector &X, Vector &Y){ int n = X.size(); float sum_X = 0, sum_Y = 0, sum_XY = 0; float squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++) { // sum of elements of array X. sum_X = sum_X + X[i]; // sum of elements of array Y. sum_Y = sum_Y + Y[i]; // sum of X[i] * Y[i]. sum_XY = sum_XY + X[i] * Y[i]; // sum of square of array elements. squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } // use formula for calculating // correlation coefficient. float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y)); return corr;} // Driver functionint main(){ Vector X = {15,18,21, 15, 21}; Vector Y= {25,25,27,27,27}; // Get ranks of vector X Vector rank_x = rankify(X); // Get ranks of vector y Vector rank_y = rankify(Y); cout << \"Vector X\" << endl; printVector(X); // Print rank vector of X cout << \"Rankings of X\" << endl; printVector(rank_x); // Print Vector Y cout << \"Vector Y\" << endl; printVector(Y); // Print rank vector of Y cout << \"Rankings of Y\" << endl; printVector(rank_y); // Print Spearmans coefficient cout << \"Spearman's Rank correlation: \" << endl; cout<<correlationCoefficient(rank_x, rank_y); return 0;}", "e": 6559, "s": 3771, "text": null }, { "code": null, "e": 6568, "s": 6559, "text": "Output: " }, { "code": null, "e": 6759, "s": 6568, "text": "Vector X\n15 18 21 15 21 \nRankings of X\n1.5 3 4.5 1.5 4.5 \nVector Y\n25 25 27 27 27 \nRankings of Y\n1.5 1.5 4 4 4 \nSpearman's Rank correlation: \n0.456435" }, { "code": null, "e": 6814, "s": 6759, "text": "Python code to calculate Spearman’s Rank Correlation: " }, { "code": null, "e": 6822, "s": 6814, "text": "Python3" }, { "code": "# Import pandas and scipy.statsimport pandas as pdimport scipy.stats # Two lists x and yx = [15,18,21, 15, 21]y = [25,25,27,27,27] # Create a function that takes in x's and y'sdef spearmans_rank_correlation(x, y): # Calculate the rank of x's xranks = pd.Series(x).rank() print(\"Rankings of X:\") print(xranks) # Calculate the ranking of the y's yranks = pd.Series(y).rank() print(\"Rankings of Y:\") print(yranks) # Calculate Pearson's correlation coefficient on the ranked versions of the data print(\"Spearman's Rank correlation:\",scipy.stats.pearsonr(xranks, yranks)[0]) # Call the functionspearmans_rank_correlation(x, y) # This code is contributed by Manish KC# profile: mkumarchaudhary06", "e": 7557, "s": 6822, "text": null }, { "code": null, "e": 7567, "s": 7557, "text": "Output: " }, { "code": null, "e": 7761, "s": 7567, "text": "Rankings of X:\n0 1.5\n1 3.0\n2 4.5\n3 1.5\n4 4.5\ndtype: float64\nRankings of Y:\n0 1.5\n1 1.5\n2 4.0\n3 4.0\n4 4.0\ndtype: float64\nSpearman's Rank correlation: 0.456435464588" }, { "code": null, "e": 7909, "s": 7761, "text": "Python code to calculate Spearman’s Correlation using Scipy There is one simple way to directly get the spearman’s correlation value using scipy. " }, { "code": null, "e": 7917, "s": 7909, "text": "Python3" }, { "code": "# Import scipy.statsimport scipy.stats # Two lists x and yx = [15,18,21, 15, 21]y = [25,25,27,27,27] print(scipy.stats.spearmanr(x, y)[0]) # This code is contributed by Manish KC# Profile: mkumarchaudhary06", "e": 8124, "s": 7917, "text": null }, { "code": null, "e": 8134, "s": 8124, "text": "Output: " }, { "code": null, "e": 8154, "s": 8134, "text": "0.45643546458763845" }, { "code": null, "e": 8237, "s": 8154, "text": "References:https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient" }, { "code": null, "e": 8255, "s": 8237, "text": "mkumarchaudhary06" }, { "code": null, "e": 8271, "s": 8255, "text": "rajeev0719singh" }, { "code": null, "e": 8281, "s": 8271, "text": "kalrap615" }, { "code": null, "e": 8290, "s": 8281, "text": "Fraction" }, { "code": null, "e": 8313, "s": 8290, "text": "statistical-algorithms" }, { "code": null, "e": 8326, "s": 8313, "text": "Mathematical" }, { "code": null, "e": 8339, "s": 8326, "text": "Mathematical" } ]
Tailwind CSS Top/Right/Bottom/Left
23 Mar, 2022 These classes accept many values in tailwind CSS in which all the properties are covered in class form. These are the alternative to the CSS Top/Right/Bottom/Left properties. These classes are used to control the alignment of a positioned element. Remember we can use these properties only with positioned elements. Top/Right/Bottom/Left classes: .inset-0 .inset-y-0 .inset-x-0 .top-0 .right-0 .bottom-0 .left-0 The default value of top/right/bottom/left/inset utilities in Tailwind is 0 and auto. Note: You can change the number “0” with the valid “rem” values. inset-0: It is used to provide 0px value to top/right/bottom/left properties of element. Syntax: <element class="inset-0">...</element> Example: HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"></head><body> <div class="text-green-600 font-bold m-4"> <h1 class="text-3xl my-4" >GeeksforGeeks</h1> <p class=" text-2xl">Top/Right/Bottom/Left</p> </div> <div class="relative h-24 w-24 bg-green-400 m-4"> <div class="absolute inset-0 bg-green-800"></div> </div></body></html> Output: inset-0 inset-y-0: It is used to provide value 0px to the top and bottom property of the element. Syntax: <element class="inset-y-0">...</element> Example: HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"></head><body> <div class="text-green-600 font-bold m-4"> <h1 class="text-3xl my-4" >GeeksforGeeks</h1> <p class=" text-2xl">Top/Right/Bottom/Left</p> </div> <div class="relative h-28 w-28 bg-green-400 m-4"> <div class="absolute inset-y-0 w-16 bg-green-800"> </div> </div></body></html> Output: inset-y-0 inset-x-0: It is used to provide value 0px to the right and left property of the element. Syntax: <element class="inset-x-0">...</element> Example: HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"></head><body> <div class="text-green-600 font-bold m-4"> <h1 class="text-3xl my-4" >GeeksforGeeks</h1> <p class=" text-2xl">Top/Right/Bottom/Left</p> </div> <div class="relative h-28 w-28 bg-green-400 m-4"> <div class="absolute inset-x-0 h-9 bg-green-800"> </div> </div></body></html> Output: inset-x-0 top-0: It is used to provide value 0px to the top property of the element. Syntax: <element class="top-0">...</element> left-0: It is used to provide value 0px to the left property of the element. Syntax: <element class="left-0">...</element> Example: In this example, we are using the left-0 and top-0 classes. HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"></head><body> <div class="text-green-600 font-bold m-4"> <h1 class="text-3xl my-4" >GeeksforGeeks</h1> <p class=" text-2xl">Top/Right/Bottom/Left</p> </div> <div class="relative h-36 w-36 bg-green-400 m-4"> <div class="absolute left-0 top-0 w-16 h-16 bg-green-800"> </div> </div></body></html> Output: left-0 top-0 right-0: It is used to provide value 0px to the right property of the element. Syntax: <element class="right-0">...</element> bottom-0: It is used to provide value 0px to the bottom property of the element. Syntax: <element class="bottom-0">...</element> Example: In this example, we are using the right-0 and bottom-0 classes. HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"></head><body> <div class="text-green-600 font-bold m-4"> <h1 class="text-3xl my-4" >GeeksforGeeks</h1> <p class=" text-2xl">Top/Right/Bottom/Left</p> </div> <div class="relative h-36 w-36 bg-green-400 m-4"> <div class="absolute right-0 bottom-0 w-16 h-16 bg-green-800"> </div> </div></body></html> Output: right-0 bottom-0 Picked Tailwind CSS Tailwind-Layout CSS 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 Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? Design a Tribute Page using HTML & CSS How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 344, "s": 28, "text": "These classes accept many values in tailwind CSS in which all the properties are covered in class form. These are the alternative to the CSS Top/Right/Bottom/Left properties. These classes are used to control the alignment of a positioned element. Remember we can use these properties only with positioned elements." }, { "code": null, "e": 375, "s": 344, "text": "Top/Right/Bottom/Left classes:" }, { "code": null, "e": 384, "s": 375, "text": ".inset-0" }, { "code": null, "e": 395, "s": 384, "text": ".inset-y-0" }, { "code": null, "e": 406, "s": 395, "text": ".inset-x-0" }, { "code": null, "e": 413, "s": 406, "text": ".top-0" }, { "code": null, "e": 422, "s": 413, "text": ".right-0" }, { "code": null, "e": 432, "s": 422, "text": ".bottom-0" }, { "code": null, "e": 440, "s": 432, "text": ".left-0" }, { "code": null, "e": 526, "s": 440, "text": "The default value of top/right/bottom/left/inset utilities in Tailwind is 0 and auto." }, { "code": null, "e": 591, "s": 526, "text": "Note: You can change the number “0” with the valid “rem” values." }, { "code": null, "e": 680, "s": 591, "text": "inset-0: It is used to provide 0px value to top/right/bottom/left properties of element." }, { "code": null, "e": 688, "s": 680, "text": "Syntax:" }, { "code": null, "e": 727, "s": 688, "text": "<element class=\"inset-0\">...</element>" }, { "code": null, "e": 736, "s": 727, "text": "Example:" }, { "code": null, "e": 741, "s": 736, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\"></head><body> <div class=\"text-green-600 font-bold m-4\"> <h1 class=\"text-3xl my-4\" >GeeksforGeeks</h1> <p class=\" text-2xl\">Top/Right/Bottom/Left</p> </div> <div class=\"relative h-24 w-24 bg-green-400 m-4\"> <div class=\"absolute inset-0 bg-green-800\"></div> </div></body></html>", "e": 1174, "s": 741, "text": null }, { "code": null, "e": 1182, "s": 1174, "text": "Output:" }, { "code": null, "e": 1190, "s": 1182, "text": "inset-0" }, { "code": null, "e": 1280, "s": 1190, "text": "inset-y-0: It is used to provide value 0px to the top and bottom property of the element." }, { "code": null, "e": 1288, "s": 1280, "text": "Syntax:" }, { "code": null, "e": 1329, "s": 1288, "text": "<element class=\"inset-y-0\">...</element>" }, { "code": null, "e": 1338, "s": 1329, "text": "Example:" }, { "code": null, "e": 1343, "s": 1338, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\"></head><body> <div class=\"text-green-600 font-bold m-4\"> <h1 class=\"text-3xl my-4\" >GeeksforGeeks</h1> <p class=\" text-2xl\">Top/Right/Bottom/Left</p> </div> <div class=\"relative h-28 w-28 bg-green-400 m-4\"> <div class=\"absolute inset-y-0 w-16 bg-green-800\"> </div> </div></body></html>", "e": 1811, "s": 1343, "text": null }, { "code": null, "e": 1819, "s": 1811, "text": "Output:" }, { "code": null, "e": 1829, "s": 1819, "text": "inset-y-0" }, { "code": null, "e": 1919, "s": 1829, "text": "inset-x-0: It is used to provide value 0px to the right and left property of the element." }, { "code": null, "e": 1927, "s": 1919, "text": "Syntax:" }, { "code": null, "e": 1968, "s": 1927, "text": "<element class=\"inset-x-0\">...</element>" }, { "code": null, "e": 1977, "s": 1968, "text": "Example:" }, { "code": null, "e": 1982, "s": 1977, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\"></head><body> <div class=\"text-green-600 font-bold m-4\"> <h1 class=\"text-3xl my-4\" >GeeksforGeeks</h1> <p class=\" text-2xl\">Top/Right/Bottom/Left</p> </div> <div class=\"relative h-28 w-28 bg-green-400 m-4\"> <div class=\"absolute inset-x-0 h-9 bg-green-800\"> </div> </div></body></html>", "e": 2449, "s": 1982, "text": null }, { "code": null, "e": 2457, "s": 2449, "text": "Output:" }, { "code": null, "e": 2467, "s": 2457, "text": "inset-x-0" }, { "code": null, "e": 2542, "s": 2467, "text": "top-0: It is used to provide value 0px to the top property of the element." }, { "code": null, "e": 2550, "s": 2542, "text": "Syntax:" }, { "code": null, "e": 2587, "s": 2550, "text": "<element class=\"top-0\">...</element>" }, { "code": null, "e": 2664, "s": 2587, "text": "left-0: It is used to provide value 0px to the left property of the element." }, { "code": null, "e": 2672, "s": 2664, "text": "Syntax:" }, { "code": null, "e": 2710, "s": 2672, "text": "<element class=\"left-0\">...</element>" }, { "code": null, "e": 2779, "s": 2710, "text": "Example: In this example, we are using the left-0 and top-0 classes." }, { "code": null, "e": 2784, "s": 2779, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\"></head><body> <div class=\"text-green-600 font-bold m-4\"> <h1 class=\"text-3xl my-4\" >GeeksforGeeks</h1> <p class=\" text-2xl\">Top/Right/Bottom/Left</p> </div> <div class=\"relative h-36 w-36 bg-green-400 m-4\"> <div class=\"absolute left-0 top-0 w-16 h-16 bg-green-800\"> </div> </div></body></html>", "e": 3260, "s": 2784, "text": null }, { "code": null, "e": 3268, "s": 3260, "text": "Output:" }, { "code": null, "e": 3281, "s": 3268, "text": "left-0 top-0" }, { "code": null, "e": 3360, "s": 3281, "text": "right-0: It is used to provide value 0px to the right property of the element." }, { "code": null, "e": 3368, "s": 3360, "text": "Syntax:" }, { "code": null, "e": 3407, "s": 3368, "text": "<element class=\"right-0\">...</element>" }, { "code": null, "e": 3488, "s": 3407, "text": "bottom-0: It is used to provide value 0px to the bottom property of the element." }, { "code": null, "e": 3496, "s": 3488, "text": "Syntax:" }, { "code": null, "e": 3536, "s": 3496, "text": "<element class=\"bottom-0\">...</element>" }, { "code": null, "e": 3609, "s": 3536, "text": "Example: In this example, we are using the right-0 and bottom-0 classes." }, { "code": null, "e": 3614, "s": 3609, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\"></head><body> <div class=\"text-green-600 font-bold m-4\"> <h1 class=\"text-3xl my-4\" >GeeksforGeeks</h1> <p class=\" text-2xl\">Top/Right/Bottom/Left</p> </div> <div class=\"relative h-36 w-36 bg-green-400 m-4\"> <div class=\"absolute right-0 bottom-0 w-16 h-16 bg-green-800\"> </div> </div></body></html>", "e": 4094, "s": 3614, "text": null }, { "code": null, "e": 4102, "s": 4094, "text": "Output:" }, { "code": null, "e": 4119, "s": 4102, "text": "right-0 bottom-0" }, { "code": null, "e": 4126, "s": 4119, "text": "Picked" }, { "code": null, "e": 4139, "s": 4126, "text": "Tailwind CSS" }, { "code": null, "e": 4155, "s": 4139, "text": "Tailwind-Layout" }, { "code": null, "e": 4159, "s": 4155, "text": "CSS" }, { "code": null, "e": 4257, "s": 4159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4305, "s": 4257, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4367, "s": 4305, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4417, "s": 4367, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4475, "s": 4417, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 4525, "s": 4475, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 4562, "s": 4525, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 4601, "s": 4562, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4640, "s": 4601, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4704, "s": 4640, "text": "How to position a div at the bottom of its container using CSS?" } ]
How to use TextareaAutosize Component in ReactJS?
02 Mar, 2021 A textarea component for React which grows with content. Material UI for React has this component available for us, and it is very easy to integrate. We can use the TextareaAutosize Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import TextareaAutosize from '@material-ui/core/TextareaAutosize'; export default function App() { return ( <div style={{ display: 'block', padding: 30, width: 500 }}> <h4>How to use TextareaAutosize Component in ReactJS?</h4> <TextareaAutosize style={{width: 150}} placeholder="Enter your text here!" /> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/textarea-autosize/ React-Questions ReactJS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? How to Use Bootstrap with React? React-Router Hooks How to navigate on path by button click in react router ? How to check the version of ReactJS ? How to Create a Countdown Timer Using ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2021" }, { "code": null, "e": 261, "s": 28, "text": "A textarea component for React which grows with content. Material UI for React has this component available for us, and it is very easy to integrate. We can use the TextareaAutosize Component in ReactJS using the following approach." }, { "code": null, "e": 311, "s": 261, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 375, "s": 311, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 407, "s": 375, "text": "npx create-react-app foldername" }, { "code": null, "e": 507, "s": 407, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 521, "s": 507, "text": "cd foldername" }, { "code": null, "e": 630, "s": 521, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 660, "s": 630, "text": "npm install @material-ui/core" }, { "code": null, "e": 712, "s": 660, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 730, "s": 712, "text": "Project Structure" }, { "code": null, "e": 861, "s": 730, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. " }, { "code": null, "e": 868, "s": 861, "text": "App.js" }, { "code": "import React from 'react';import TextareaAutosize from '@material-ui/core/TextareaAutosize'; export default function App() { return ( <div style={{ display: 'block', padding: 30, width: 500 }}> <h4>How to use TextareaAutosize Component in ReactJS?</h4> <TextareaAutosize style={{width: 150}} placeholder=\"Enter your text here!\" /> </div> );}", "e": 1237, "s": 868, "text": null }, { "code": null, "e": 1350, "s": 1237, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 1360, "s": 1350, "text": "npm start" }, { "code": null, "e": 1459, "s": 1360, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 1524, "s": 1459, "text": "Reference: https://material-ui.com/components/textarea-autosize/" }, { "code": null, "e": 1540, "s": 1524, "text": "React-Questions" }, { "code": null, "e": 1548, "s": 1540, "text": "ReactJS" }, { "code": null, "e": 1646, "s": 1548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1684, "s": 1646, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 1711, "s": 1684, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 1750, "s": 1711, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 1802, "s": 1750, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 1841, "s": 1802, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 1874, "s": 1841, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 1893, "s": 1874, "text": "React-Router Hooks" }, { "code": null, "e": 1951, "s": 1893, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 1989, "s": 1951, "text": "How to check the version of ReactJS ?" } ]
How to insert line break before an element using CSS?
04 Apr, 2019 The white-space property is used to insert the line break before an element. This property controls the text wrapping and white-spacing. Line break between the lines: The line break can be added between the line of text. The white-space: preline; is used to insert line break before an element. Example 1: <!DOCTYPE html><html> <head> <title> Insert line break before an element </title> <!-- CSS style to insert line break before an element --> <style> p { color:green; white-space: pre-line; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Insert line break before an element </h2> <p> Data Structure Algorithm Computer Networks Web Technology </p></body> </html> Output: Line-break between HTML Elements: The line-break between HTML elements can be added by using CSS properties. There are two methods to force inline elements to add new line. Using display property: A block-level element starts on a new line, and takes up the entire width available to it. Using carriage return character (\A): We can add a new-line by using the ::before or ::after pseudo-elements. Example 2: <!DOCTYPE html><html> <head> <title> Insert line break and content before an element </title> <!--It adds the GeeksforGeeks A computer science portal --> <style> p::before { color:green; content: "GeeksforGeeks \A " "A computer science portal"; display: block; white-space: pre; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Insert content and line break before an element </h2> <p>Data Structure</p> <p>Algorithm</p></body> </html> Output: Example 3: This example uses carriage return character “\A” to add line break before an element. <!DOCTYPE html><html> <head> <title> Insert line break before an element </title> <!-- Style to add the line break --> <style> p::before { content: "\A"; white-space: pre; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Insert line break before an element </h2> <p>Data Structure</p> <p>Algorithm</p> <p>Operating System</p></body> </html> Output: Picked Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Apr, 2019" }, { "code": null, "e": 165, "s": 28, "text": "The white-space property is used to insert the line break before an element. This property controls the text wrapping and white-spacing." }, { "code": null, "e": 323, "s": 165, "text": "Line break between the lines: The line break can be added between the line of text. The white-space: preline; is used to insert line break before an element." }, { "code": null, "e": 334, "s": 323, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> Insert line break before an element </title> <!-- CSS style to insert line break before an element --> <style> p { color:green; white-space: pre-line; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Insert line break before an element </h2> <p> Data Structure Algorithm Computer Networks Web Technology </p></body> </html> ", "e": 871, "s": 334, "text": null }, { "code": null, "e": 879, "s": 871, "text": "Output:" }, { "code": null, "e": 1052, "s": 879, "text": "Line-break between HTML Elements: The line-break between HTML elements can be added by using CSS properties. There are two methods to force inline elements to add new line." }, { "code": null, "e": 1167, "s": 1052, "text": "Using display property: A block-level element starts on a new line, and takes up the entire width available to it." }, { "code": null, "e": 1277, "s": 1167, "text": "Using carriage return character (\\A): We can add a new-line by using the ::before or ::after pseudo-elements." }, { "code": null, "e": 1288, "s": 1277, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> Insert line break and content before an element </title> <!--It adds the GeeksforGeeks A computer science portal --> <style> p::before { color:green; content: \"GeeksforGeeks \\A \" \"A computer science portal\"; display: block; white-space: pre; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Insert content and line break before an element </h2> <p>Data Structure</p> <p>Algorithm</p></body> </html> ", "e": 1903, "s": 1288, "text": null }, { "code": null, "e": 1911, "s": 1903, "text": "Output:" }, { "code": null, "e": 2008, "s": 1911, "text": "Example 3: This example uses carriage return character “\\A” to add line break before an element." }, { "code": "<!DOCTYPE html><html> <head> <title> Insert line break before an element </title> <!-- Style to add the line break --> <style> p::before { content: \"\\A\"; white-space: pre; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Insert line break before an element </h2> <p>Data Structure</p> <p>Algorithm</p> <p>Operating System</p></body> </html> ", "e": 2487, "s": 2008, "text": null }, { "code": null, "e": 2495, "s": 2487, "text": "Output:" }, { "code": null, "e": 2502, "s": 2495, "text": "Picked" }, { "code": null, "e": 2519, "s": 2502, "text": "Web Technologies" }, { "code": null, "e": 2546, "s": 2519, "text": "Web technologies Questions" } ]
Iterate through a LinkedList using an Iterator in Java
An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise. The method next( ) returns the next element in the LinkedList and throws the exception NoSuchElementException if there is no next element. A program that demonstrates this is given as follows. Live Demo import java.util.LinkedList; import java.util.Iterator; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList elements are: "); for (Iterator i = l.iterator(); i.hasNext();) { System.out.println(i.next()); } } } The output of the above program is as follows − The LinkedList elements are: John Sara Susan Betty Nathan Now let us understand the above program. The LinkedList is created and LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList elements are: "); for (Iterator i = l.iterator(); i.hasNext();) { System.out.println(i.next()); }
[ { "code": null, "e": 1478, "s": 1187, "text": "An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise. The method next( ) returns the next element in the LinkedList and throws the exception NoSuchElementException if there is no next element." }, { "code": null, "e": 1532, "s": 1478, "text": "A program that demonstrates this is given as follows." }, { "code": null, "e": 1543, "s": 1532, "text": " Live Demo" }, { "code": null, "e": 1994, "s": 1543, "text": "import java.util.LinkedList;\nimport java.util.Iterator;\npublic class Demo {\n public static void main(String[] args) {\n LinkedList<String> l = new LinkedList<String>();\n l.add(\"John\");\n l.add(\"Sara\");\n l.add(\"Susan\");\n l.add(\"Betty\");\n l.add(\"Nathan\");\n System.out.println(\"The LinkedList elements are: \");\n for (Iterator i = l.iterator(); i.hasNext();) {\n System.out.println(i.next());\n }\n }\n}" }, { "code": null, "e": 2042, "s": 1994, "text": "The output of the above program is as follows −" }, { "code": null, "e": 2100, "s": 2042, "text": "The LinkedList elements are:\nJohn\nSara\nSusan\nBetty\nNathan" }, { "code": null, "e": 2141, "s": 2100, "text": "Now let us understand the above program." }, { "code": null, "e": 2392, "s": 2141, "text": "The LinkedList is created and LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows" }, { "code": null, "e": 2656, "s": 2392, "text": "LinkedList<String> l = new LinkedList<String>();\nl.add(\"John\");\nl.add(\"Sara\");\nl.add(\"Susan\");\nl.add(\"Betty\");\nl.add(\"Nathan\");\nSystem.out.println(\"The LinkedList elements are: \");\nfor (Iterator i = l.iterator(); i.hasNext();) {\n System.out.println(i.next());\n}" } ]
DAX Text - CONCATENATEX function
Concatenates the result of an expression evaluated for each row in a table. DAX CONCATENATEX function is new in Excel 2016. CONCATENATEX ( <table>, <expression>, [<delimiter>], [<OrderBy_Expression1>], [<Order>] ... ) table The table containing the rows for which the expression will be evaluated. expression The expression to be evaluated for each row of the table. delimiter Optional. A separator to use during concatenation. OrderBy_Expression1 Optional. Column by which the values are to be concatenated. Order Optional. ASC: To sort in an ascending order. DESC: To sort in a descending order. If omitted, default is ASC. A single text string. CONCATENATEX function takes as its first parameter, a table or an expression that returns a table. The second parameter is a column that contains the values you want to concatenate, or an expression that returns a value. CONCATENATEX (Products, [Product],", ", [Product Key], ASC) returns Air Purifier, Detergent Powder, Floor Cleaner, Hand Wash, Soap. = CONCATENATEX (Products, [Product],",", [Product Key], DESC) returns Soap, Hand Wash, Floor Cleaner, Detergent Powder, Air Purifier. = CONCATENATEX (Products, [Product],", ", [Product Key]) returns Air Purifier, Detergent Powder, Floor Cleaner, Hand Wash, Soap. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2077, "s": 2001, "text": "Concatenates the result of an expression evaluated for each row in a table." }, { "code": null, "e": 2125, "s": 2077, "text": "DAX CONCATENATEX function is new in Excel 2016." }, { "code": null, "e": 2224, "s": 2125, "text": "CONCATENATEX (\n <table>, <expression>, [<delimiter>], [<OrderBy_Expression1>], [<Order>] ...\n) \n" }, { "code": null, "e": 2230, "s": 2224, "text": "table" }, { "code": null, "e": 2304, "s": 2230, "text": "The table containing the rows for which the expression will be evaluated." }, { "code": null, "e": 2315, "s": 2304, "text": "expression" }, { "code": null, "e": 2373, "s": 2315, "text": "The expression to be evaluated for each row of the table." }, { "code": null, "e": 2383, "s": 2373, "text": "delimiter" }, { "code": null, "e": 2393, "s": 2383, "text": "Optional." }, { "code": null, "e": 2434, "s": 2393, "text": "A separator to use during concatenation." }, { "code": null, "e": 2454, "s": 2434, "text": "OrderBy_Expression1" }, { "code": null, "e": 2464, "s": 2454, "text": "Optional." }, { "code": null, "e": 2515, "s": 2464, "text": "Column by which the values are to be concatenated." }, { "code": null, "e": 2521, "s": 2515, "text": "Order" }, { "code": null, "e": 2531, "s": 2521, "text": "Optional." }, { "code": null, "e": 2567, "s": 2531, "text": "ASC: To sort in an ascending order." }, { "code": null, "e": 2604, "s": 2567, "text": "DESC: To sort in a descending order." }, { "code": null, "e": 2632, "s": 2604, "text": "If omitted, default is ASC." }, { "code": null, "e": 2654, "s": 2632, "text": "A single text string." }, { "code": null, "e": 2753, "s": 2654, "text": "CONCATENATEX function takes as its first parameter, a table or an expression that returns a table." }, { "code": null, "e": 2875, "s": 2753, "text": "The second parameter is a column that contains the values you want to concatenate, or an expression that returns a value." }, { "code": null, "e": 3287, "s": 2875, "text": "CONCATENATEX (Products, [Product],\", \", [Product Key], ASC)\n returns Air Purifier, Detergent Powder, Floor Cleaner, Hand Wash, Soap.\n \n= CONCATENATEX (Products, [Product],\",\", [Product Key], DESC) \n returns Soap, Hand Wash, Floor Cleaner, Detergent Powder, Air Purifier. \n\n= CONCATENATEX (Products, [Product],\", \", [Product Key]) \n returns Air Purifier, Detergent Powder, Floor Cleaner, Hand Wash, Soap." }, { "code": null, "e": 3322, "s": 3287, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3336, "s": 3322, "text": " Abhay Gadiya" }, { "code": null, "e": 3369, "s": 3336, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3383, "s": 3369, "text": " Randy Minder" }, { "code": null, "e": 3418, "s": 3383, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3432, "s": 3418, "text": " Randy Minder" }, { "code": null, "e": 3439, "s": 3432, "text": " Print" }, { "code": null, "e": 3450, "s": 3439, "text": " Add Notes" } ]
Build an Interactive Choropleth Map with Plotly and Dash | by Jun | Towards Data Science
Last week, I finished my final assignment in IBM Data Science course, which is to find an ideal suburb for opening an Italian restaurant based on location data. During the process, I web-scrapped property median price (i.e. House buy/rent and Unit buy/rent) for each suburb in Sydney and plotted them on Choropleth maps, respectively. However, I was wondering if it is possible to combine all these maps in one and select one of them just by clicking name from a dropdown menu. In addition, I want to add one more plot next to the map to show the top 10 suburbs with the highest median prices accordingly. These add-ons will make the map more informative and user-friendly. In this post, I will share my notes about how to create an interactive dashboard with a choropleth map and bar plot using Plotly and Dash. In addition, I assume that you have prior experience with Plotly. Install plotly, dash, and pandas on the system. I created a virtual environment using conda to keep the system organised and avoid mess up with other packages in the system. I have introduced conda virtual environment in my previous post if you want to know more about conda env. The following code will create a virtual environment that have all required packages for plotly and dash . conda create -n <whatever name you want for this env> -c plotly plotly=4.4.1 -c conda-forge dash pandas To be able to draw a map in plotly, we also need a token from Mapbox, which provides various nice map styles and most importantly is for free. In addition, two datasets were used in this dashboard and they can be download from my github (← You can also find the dash app code here). If you want to explore the dash app now, after finishing above steps, you need to assign your Mapbox token to mapbox_accesstoken in this script and run it in the same directory with the two datasets. Once the following message popped up, just open this address http://127.0.0.1:8050/ in your preferred browser and dash will be loading in there. $ python dash_project_medium.py Running on http://127.0.0.1:8050/ Debugger PIN: 880-084-162 * Serving Flask app "dash_project" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on As shown in the following figure, I have labelled the key functions used in the script for creating corresponding elements in the dashboard. The general principle in building this dashboard via plotly and dash is to 1) arrange and combine different elements together on a defined canvas; 2) compile all elements in one container:fig=go.Figure(data=trace2 + trace1, layout=layout) ; 3) pass this container to dcc.Graph, in which dcc is the dash core components, and dash will create a html-based web application for the dashboard. A key function of this dashboard is to show a specific parameter (i.e. House_buy, House_rent, Unit_buy and Unit_rent) in the two traces (choropleth map and bar plot) via the dropdown menu. My method is to create four layers with an argument visible=False for each trace. Then use the buttons feature of updatemenus to turn visible=True for a given parameter. Thus, there are four figure layers in each trace and only one is visible depends on which button is clicked in a given time point. Since map are not plotted on a cartesian system of coordinates (x/y), which is the coordinates system used in the bar plot, I set up two coordinates systems in the dashboard for the map and bar plot, respectively. As for the bar plot(trace2), its axes are assigned to xaxis='x2', yaxis='y2'. Instead, the map (trace1) has its own features within Layout, which was assigned to the variable mapbox1, the numbers following mapbox and x/y is arbitrary. Having said this, you can assign as many coordinates systems as you want, just make sure you anchor the right system to its trace in the Layout. Then within the Layout settings, we do adjustments for these two coordinates systems individually. Such as the position of traces in the dashboard via domain, the appearance of ticks on each axis via showticklabels, and the ascending order of bar via autorange. After concatenating all elements within fig=go.Figure, I assigned fig to dcc.Graph, wrapped up all codes as a py file, and run it. Boom, here comes my first interactive dashboard. I should note that I only used very basic Dash structure here, most of the codes are still written in Plotly. One drawback of my method is that stacking all four layers onto the same trace may slow down the app, this is because all data need to be loaded when the dash app is initialising. It will be more efficient to do real-time updating when a clicking dropdown menu event happened. Hopefully, further learning with advanced Dash code will find me a solution. Here are some resources for learning Dash: Dash User Guide Dash for beginners from Datacamp Dash Community Forum Awesome Dash Resource Guide on Github A detailed Dashboard building post As always, I welcome feedback, constructive criticism, and hearing about your data science projects. I can be reached on Linkedin.
[ { "code": null, "e": 507, "s": 172, "text": "Last week, I finished my final assignment in IBM Data Science course, which is to find an ideal suburb for opening an Italian restaurant based on location data. During the process, I web-scrapped property median price (i.e. House buy/rent and Unit buy/rent) for each suburb in Sydney and plotted them on Choropleth maps, respectively." }, { "code": null, "e": 1051, "s": 507, "text": "However, I was wondering if it is possible to combine all these maps in one and select one of them just by clicking name from a dropdown menu. In addition, I want to add one more plot next to the map to show the top 10 suburbs with the highest median prices accordingly. These add-ons will make the map more informative and user-friendly. In this post, I will share my notes about how to create an interactive dashboard with a choropleth map and bar plot using Plotly and Dash. In addition, I assume that you have prior experience with Plotly." }, { "code": null, "e": 1438, "s": 1051, "text": "Install plotly, dash, and pandas on the system. I created a virtual environment using conda to keep the system organised and avoid mess up with other packages in the system. I have introduced conda virtual environment in my previous post if you want to know more about conda env. The following code will create a virtual environment that have all required packages for plotly and dash ." }, { "code": null, "e": 1542, "s": 1438, "text": "conda create -n <whatever name you want for this env> -c plotly plotly=4.4.1 -c conda-forge dash pandas" }, { "code": null, "e": 1825, "s": 1542, "text": "To be able to draw a map in plotly, we also need a token from Mapbox, which provides various nice map styles and most importantly is for free. In addition, two datasets were used in this dashboard and they can be download from my github (← You can also find the dash app code here)." }, { "code": null, "e": 2170, "s": 1825, "text": "If you want to explore the dash app now, after finishing above steps, you need to assign your Mapbox token to mapbox_accesstoken in this script and run it in the same directory with the two datasets. Once the following message popped up, just open this address http://127.0.0.1:8050/ in your preferred browser and dash will be loading in there." }, { "code": null, "e": 2486, "s": 2170, "text": "$ python dash_project_medium.py Running on http://127.0.0.1:8050/ Debugger PIN: 880-084-162 * Serving Flask app \"dash_project\" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on" }, { "code": null, "e": 2627, "s": 2486, "text": "As shown in the following figure, I have labelled the key functions used in the script for creating corresponding elements in the dashboard." }, { "code": null, "e": 3016, "s": 2627, "text": "The general principle in building this dashboard via plotly and dash is to 1) arrange and combine different elements together on a defined canvas; 2) compile all elements in one container:fig=go.Figure(data=trace2 + trace1, layout=layout) ; 3) pass this container to dcc.Graph, in which dcc is the dash core components, and dash will create a html-based web application for the dashboard." }, { "code": null, "e": 3375, "s": 3016, "text": "A key function of this dashboard is to show a specific parameter (i.e. House_buy, House_rent, Unit_buy and Unit_rent) in the two traces (choropleth map and bar plot) via the dropdown menu. My method is to create four layers with an argument visible=False for each trace. Then use the buttons feature of updatemenus to turn visible=True for a given parameter." }, { "code": null, "e": 3506, "s": 3375, "text": "Thus, there are four figure layers in each trace and only one is visible depends on which button is clicked in a given time point." }, { "code": null, "e": 4100, "s": 3506, "text": "Since map are not plotted on a cartesian system of coordinates (x/y), which is the coordinates system used in the bar plot, I set up two coordinates systems in the dashboard for the map and bar plot, respectively. As for the bar plot(trace2), its axes are assigned to xaxis='x2', yaxis='y2'. Instead, the map (trace1) has its own features within Layout, which was assigned to the variable mapbox1, the numbers following mapbox and x/y is arbitrary. Having said this, you can assign as many coordinates systems as you want, just make sure you anchor the right system to its trace in the Layout." }, { "code": null, "e": 4362, "s": 4100, "text": "Then within the Layout settings, we do adjustments for these two coordinates systems individually. Such as the position of traces in the dashboard via domain, the appearance of ticks on each axis via showticklabels, and the ascending order of bar via autorange." }, { "code": null, "e": 4542, "s": 4362, "text": "After concatenating all elements within fig=go.Figure, I assigned fig to dcc.Graph, wrapped up all codes as a py file, and run it. Boom, here comes my first interactive dashboard." }, { "code": null, "e": 5006, "s": 4542, "text": "I should note that I only used very basic Dash structure here, most of the codes are still written in Plotly. One drawback of my method is that stacking all four layers onto the same trace may slow down the app, this is because all data need to be loaded when the dash app is initialising. It will be more efficient to do real-time updating when a clicking dropdown menu event happened. Hopefully, further learning with advanced Dash code will find me a solution." }, { "code": null, "e": 5049, "s": 5006, "text": "Here are some resources for learning Dash:" }, { "code": null, "e": 5065, "s": 5049, "text": "Dash User Guide" }, { "code": null, "e": 5098, "s": 5065, "text": "Dash for beginners from Datacamp" }, { "code": null, "e": 5119, "s": 5098, "text": "Dash Community Forum" }, { "code": null, "e": 5157, "s": 5119, "text": "Awesome Dash Resource Guide on Github" }, { "code": null, "e": 5192, "s": 5157, "text": "A detailed Dashboard building post" } ]
Merge Sort Program in C
Merge sort is a sorting technique based on divide and conquer technique. With the worst-case time complexity being Ο(n log n), it is one of the most respected algorithms. We shall see the implementation of merge sort in C programming language here − #include <stdio.h> #define max 10 int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 }; int b[10]; void merging(int low, int mid, int high) { int l1, l2, i; for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(a[l1] <= a[l2]) b[i] = a[l1++]; else b[i] = a[l2++]; } while(l1 <= mid) b[i++] = a[l1++]; while(l2 <= high) b[i++] = a[l2++]; for(i = low; i <= high; i++) a[i] = b[i]; } void sort(int low, int high) { int mid; if(low < high) { mid = (low + high) / 2; sort(low, mid); sort(mid+1, high); merging(low, mid, high); } else { return; } } int main() { int i; printf("List before sorting\n"); for(i = 0; i <= max; i++) printf("%d ", a[i]); sort(0, max); printf("\nList after sorting\n"); for(i = 0; i <= max; i++) printf("%d ", a[i]); } If we compile and run the above program, it will produce the following result − List before sorting 10 14 19 26 27 31 33 35 42 44 0 List after sorting 0 10 14 19 26 27 31 33 35 42 44 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2751, "s": 2580, "text": "Merge sort is a sorting technique based on divide and conquer technique. With the worst-case time complexity being Ο(n log n), it is one of the most respected algorithms." }, { "code": null, "e": 2830, "s": 2751, "text": "We shall see the implementation of merge sort in C programming language here −" }, { "code": null, "e": 3770, "s": 2830, "text": "#include <stdio.h>\n\n#define max 10\n\nint a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };\nint b[10];\n\nvoid merging(int low, int mid, int high) {\n int l1, l2, i;\n\n for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {\n if(a[l1] <= a[l2])\n b[i] = a[l1++];\n else\n b[i] = a[l2++];\n }\n \n while(l1 <= mid) \n b[i++] = a[l1++];\n\n while(l2 <= high) \n b[i++] = a[l2++];\n\n for(i = low; i <= high; i++)\n a[i] = b[i];\n}\n\nvoid sort(int low, int high) {\n int mid;\n \n if(low < high) {\n mid = (low + high) / 2;\n sort(low, mid);\n sort(mid+1, high);\n merging(low, mid, high);\n } else { \n return;\n } \n}\n\nint main() { \n int i;\n\n printf(\"List before sorting\\n\");\n \n for(i = 0; i <= max; i++)\n printf(\"%d \", a[i]);\n\n sort(0, max);\n\n printf(\"\\nList after sorting\\n\");\n \n for(i = 0; i <= max; i++)\n printf(\"%d \", a[i]);\n}" }, { "code": null, "e": 3850, "s": 3770, "text": "If we compile and run the above program, it will produce the following result −" }, { "code": null, "e": 3954, "s": 3850, "text": "List before sorting\n10 14 19 26 27 31 33 35 42 44 0\nList after sorting\n0 10 14 19 26 27 31 33 35 42 44\n" }, { "code": null, "e": 3989, "s": 3954, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4001, "s": 3989, "text": " Ravi Kiran" }, { "code": null, "e": 4036, "s": 4001, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 4055, "s": 4036, "text": " Arnab Chakraborty" }, { "code": null, "e": 4090, "s": 4055, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4105, "s": 4090, "text": " Parth Panjabi" }, { "code": null, "e": 4138, "s": 4105, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 4157, "s": 4138, "text": " Arnab Chakraborty" }, { "code": null, "e": 4191, "s": 4157, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4219, "s": 4191, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4255, "s": 4219, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4283, "s": 4255, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4290, "s": 4283, "text": " Print" }, { "code": null, "e": 4301, "s": 4290, "text": " Add Notes" } ]
Using pandas categories properly is tricky... here's why | Towards Data Science
Categorical datatypes are often touted as an easy win for cutting down DataFrame memory usage in pandas, and they can indeed be a useful tool. However, if you imagined you could just throw in a .astype("category") at the start of your code and have everything else behave the same (but more efficiently), you’re likely to be disappointed. This article focuses on some of the real world problems you are likely to face when using categorical datatypes in pandas; either adjusting your existing mindset to write new code using categories, or trying to migrate existing pipelines into flows using categorical columns. The behaviour described in this article is current as of pandas==1.2.3 (released March 2021), but don’t worry if you’re reading this at a much later date, the behaviour described is unlikely to change significantly in future versions — but leave a comment if it has! If categorical data can be a pain, then why not just avoid it altogether? Well, using categories can bring some significant benefits: Memory usage — for string columns where there are many repeated values, categories can drastically reduce the amount of memory required to store the data in memory Runtime performance — there are optimizations in place which can improve execution speed for certain operations Library integrations — in some cases libraries have special functionality for categorical columns, for example lightgbm handles categorical columns differently when building models Let’s do an obligatory ‘happy path’ example. Here’s what things look like in a simple world where everyone smiles at each other: df_size = 100_000df1 = pd.DataFrame( { "float_1": np.random.rand(df_size), "species": np.random.choice(["cat", "dog", "ape", "gorilla"], size=df_size), })df1_cat = df1.astype({"species": "category"}) Here we have created two dataframes, df1 which contains species as an object column and df1_cat which is a copy of the same dataframe but with species as a categorical datatype. >> df1.memory_usage(deep=True)Index 128float_1 800000species 6100448dtype: int64 We can see here how expensive it is to keep a column with strings in terms of our memory usage — here the column of strings occupies about 6MB, if these strings were longer, it would take even more; compare that to the 0.8MB taken up by the float column. We could afford nearly 8 float64 columns for the price of that one string column...pricey. >> df1_cat.memory_usage(deep=True)Index 128float_1 800000species 100416dtype: int64 Looking at the memory usage after having cast to a category we see a pretty drastic improvement, about 60x less memory used, very nice. We can now afford 8 of these string columns for the price of one float64 column, oh how the tables have turned. This is cool, however, it’s only really cool if we can keep it that way... Seems like a weird thing to say? Well... working with categories can be a lot like playing with those wobbly dolls that spring right back up when you push them over; they will all too easily rock right back into objects if you don’t pay very close attention to each operation using the categorical columns. In the best case scenario, this is annoying, in the worst case it kills your performance (because casting types is expensive), and/or blows out your memory (because you could only fit this data into your memory when stored as a category). It’s probable that at some point you’re going to want to do something with your categorical columns, one of those things might be a transformation. This is the first place that we’re going to have to show some diligence... Since categorical columns are often text based columns let’s look at an example using string manipulations, we can do these manipulations on categorical columns in the same way that we do ordinarily for text based object columns; by using the .str accessor. On non-categorical string series: >> %timeit df1["species"].str.upper()25.6 ms ± 2.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) On categorical string series: >> %timeit df1_cat["species"].str.upper()1.85 ms ± 41.1 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each) The categorical version is a clear winner on performance, about 14x faster in this case (this is because the internal optimizations mean that the .str.upper() is only called once on the unique category values and then a series constructed from the outcome, instead of once per value in the series). However, this is where we run into our first major gotcha... >> df1_cat["species"].str.upper().memory_usage(deep=True)6100576 We’ve lost our categorical type, the result is an object type column and the data compression is gone; the result is now once again at it’s 6MB size. We could recast back to a category after this but that is a lot of to-ing and fro-ing between types, it makes our code messier and doesn’t reduce our peak memory usage. Oftentimes an efficient alternative is to rewrite your code manipulating categorical columns to operate directly on the categories themselves rather than on the series of their values. This takes a bit of change in mindset (and implementation), you can think of it as just doing an operation once for each unique value in the column, rather than each instance in the column. If you only have a column 2 unique values in its categories spread over 100,000 rows, it makes sense that you would only do the operation 2 times, rather than 100,000 times. For example, in the above case we could do the following: %timeit df1_cat["species"].cat.rename_categories(str.upper)239 μs ± 13.9 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each) That’s about 10x faster than either of the previous options, and the main benefit is that we never convert the categorical series into an expensive intermediate object column state, so we keep our memory efficiency, very nice. It’s a toy example but the principles hold for more complex examples, if there isn’t a specific .cat accessor method which helps for your specific case, consider operating on the df1_cat[“species”].dtype.categories which contain the unique categorical values, rather than on the whole series. In all but the simplest of use cases, we are likely to have not just one dataframe, but multiple dataframes which we’ll probably want to stick together at some point. For an example, we’re going to drum up a small ‘reference’ dataset which contains the habitats of the species of our first dataset: df2 = pd.DataFrame( { "species": ["cat", "dog", "ape", "gorilla", "snake"], "habitat": ["house", "house", "jungle", "jungle", "jungle"], })df2_cat = df2.astype({"species": "category", "habitat": "category"}) As before, we’ve created one categorical version of this dataset, and one with object strings. One thing that’s important to note here is that we have an extra species (snake) which we don’t have in df1 which is the dataframe we’ll be merging with, this will be important later (but don’t worry there won’t be a test). I won’t show an example of merging together two object columns because you all know what happens, object + object = object, there is no magic, it’s just a merge. For this little test, we’re going to take one of our categorical dataframes and merge it with the object type column on another dataframe. >> df1.merge(df2_cat, on="species").dtypesfloat_1 float64species objecthabitat categorydtype: object So here we had species as object on the left and category on the right. We can see that when we merge we get category + object = object for the merge column in the resultant dataframe. So blah blah blah, this hits us in the memory again when we snap back to objects. Not super surprising, but again, something to be mindful of when working with categories. Hopefully I’ve set you up to think that I’m leading up to category + category = category . Well let’s take a look: >> df1_cat.merge(df2_cat, on="species").dtypesfloat_1 float64species objecthabitat categorydtype: object Call the police, I have been deceived... category + category = object . So what’s the sting in the tail? Well in a merge, in order to preserve the categorical type, the two categorical types must be exactly the same. Unlike the other data types in pandas (where, for example, all float64 columns have the same data type), when we talk about the categorical datatypes, the datatype is actually described by the set of values that can exist in that particular category, so you can imagine that a category containing ["cat", "dog", "mouse"] is a different type to the category containing [“cheese”, “milk”, “eggs”] . Although in our case they appear pretty much the same (one is a subset of the other), in df2 we have a species present which isn’t present in df1 (the slippery snake). We can think of the behaviour on merge columns like this: category1 + category2 = object category1 + category1 = category1 So adapting the previous example we can get the result we want and expect: >> df1_cat.astype({"species": df2_cat["species"].dtype}).merge( df2_cat, on="species" ).dtypesfloat_1 float64species categoryhabitat categorydtype: object Above it can be seen that setting the categorical types to match and then merging gives us the desired results... finally. Grouping with categories has personally bitten me in the ankles a couple of times when adapting code to work with categorical datatypes. Once causing behaviour to change unexpectedly, giving a dataframe full of null values and another time causing the operation to hang indefinitely (even though it previously took only a couple of seconds with object datatypes). When you group on a categorical datatype, by default you group on every value in the datatype even if it isn’t present in the data itself. What does that mean? It’s probably best illustrated with an example. habitat_df = ( df1_cat.astype({"species": df2_cat["species"].dtype}) .merge(df2_cat, on="species"))house_animals_df = habitat_df.loc[habitat_df["habitat"] == "house"] So here habitat_df is the merge example from the previous section (where both species and habitat end up being categorical), and house_animals_df contains just animals which live in a house, in our case cat and dog. Let’s try to find the average float_1 value for each of these species . >> house_animals_df.groupby("species")["float_1"].mean()speciesape NaNcat 0.501507dog 0.501023gorilla NaNsnake NaNName: float_1, dtype: float64 Something looks a bit off, we now get a bunch of null values in our groupby. By default when grouping by on categorical columns, pandas returns a result for each value in the category, even when not present in the data. This can be annoying (since it’s an unexpected change in behaviour), and it can also hurt performance if the datatype contains a lot of groups which aren’t present in the relevant dataframe — particularly if grouping on multiple different categorical column. To get the result we want, we can pass observed=True into the groupby call, this ensures that we only get groups for values in the data. >> house_animals_df.groupby("species", observed=True)["float_1"].mean()speciescat 0.501507dog 0.501023Name: float_1, dtype: float64 Resolved yes, but it’s yet another gotcha to keep us on our toes. This case is a little more niche but it adds a bit of colour to the kinds of unexpected problems that you can sometimes run into if you don’t keep your wits about you using categoricals. There are scenarios where you might move row values into columns, for example, the groupby-unstack combo which is somewhat of a pro-gamer move. >> species_df = habitat_df.groupby(["habitat", "species"], observed=True)["float_1"].mean().unstack()>> species_dfspecies cat ape dog gorillahabitat house 0.501507 NaN 0.501023 NaNjungle NaN 0.501284 NaN 0.501108 So we’ve got a dataframe now with the species in the columns, all looks normal so far, let’s add another column and see what happens. >> species_df["new_col"] = 1TypeError: 'fill_value=new_col' is not present in this Categorical's categories Normally this code would be completely fine, we’re just trying to add a new column called new_col which always has the value 1. Just glancing at the dataframe, nothing looks wrong and the error seems kind of confusing, which Categorical is it talking about, we’re just trying to add a new column? What happens is that the .unstack() (which for the uninitiated, flips the index into the columns much like a pivot) moves the categorical index into the column index. It’s not possible to add an entry to a categorical index which isn’t in the categorical datatype already, hence the error. This isn’t immediately obvious though and you could be forgiven for scratching your head if you ever ended up here. There probably isn’t a strong case for ever having a categorical column index, but if accidentally end up with one and/or you start to see strange errors similar to this it may be worth checking datatypes of all of the things you’re working with and make sure there’s nothing weird and categorical going on. Pandas categorical dtypes are cool, and can have some good performance benefits. When adopting the use of categorical datatypes it’s important to be aware of how the datatype behaves in different common situations and especially important to make sure categoricals stay categorical throughout the flow of the program and don’t flip back to object. Here’s a high level summary of things to be mindful of: When operating on categorical columns, select options which operate on the categories in the datatype rather than the values in the series which contain the datatype. This should allow you to preserve the categorical nature and also improve performance. When merging on categorical columns, be aware that to preserve the categorical nature, the categorical types in the merge columns of each dataframe must match exactly. When grouping on categorical columns, by default you will get a result for each value in the datatype, even if it’s not present in the data, you can change this using observed=True in the .groupby . When things that you expect to work unexpectedly stop working, consider whether a strange interaction with categoricals may be at play Best of luck, and happy catting!
[ { "code": null, "e": 511, "s": 172, "text": "Categorical datatypes are often touted as an easy win for cutting down DataFrame memory usage in pandas, and they can indeed be a useful tool. However, if you imagined you could just throw in a .astype(\"category\") at the start of your code and have everything else behave the same (but more efficiently), you’re likely to be disappointed." }, { "code": null, "e": 787, "s": 511, "text": "This article focuses on some of the real world problems you are likely to face when using categorical datatypes in pandas; either adjusting your existing mindset to write new code using categories, or trying to migrate existing pipelines into flows using categorical columns." }, { "code": null, "e": 1054, "s": 787, "text": "The behaviour described in this article is current as of pandas==1.2.3 (released March 2021), but don’t worry if you’re reading this at a much later date, the behaviour described is unlikely to change significantly in future versions — but leave a comment if it has!" }, { "code": null, "e": 1188, "s": 1054, "text": "If categorical data can be a pain, then why not just avoid it altogether? Well, using categories can bring some significant benefits:" }, { "code": null, "e": 1352, "s": 1188, "text": "Memory usage — for string columns where there are many repeated values, categories can drastically reduce the amount of memory required to store the data in memory" }, { "code": null, "e": 1464, "s": 1352, "text": "Runtime performance — there are optimizations in place which can improve execution speed for certain operations" }, { "code": null, "e": 1645, "s": 1464, "text": "Library integrations — in some cases libraries have special functionality for categorical columns, for example lightgbm handles categorical columns differently when building models" }, { "code": null, "e": 1774, "s": 1645, "text": "Let’s do an obligatory ‘happy path’ example. Here’s what things look like in a simple world where everyone smiles at each other:" }, { "code": null, "e": 1994, "s": 1774, "text": "df_size = 100_000df1 = pd.DataFrame( { \"float_1\": np.random.rand(df_size), \"species\": np.random.choice([\"cat\", \"dog\", \"ape\", \"gorilla\"], size=df_size), })df1_cat = df1.astype({\"species\": \"category\"})" }, { "code": null, "e": 2172, "s": 1994, "text": "Here we have created two dataframes, df1 which contains species as an object column and df1_cat which is a copy of the same dataframe but with species as a categorical datatype." }, { "code": null, "e": 2269, "s": 2172, "text": ">> df1.memory_usage(deep=True)Index 128float_1 800000species 6100448dtype: int64" }, { "code": null, "e": 2615, "s": 2269, "text": "We can see here how expensive it is to keep a column with strings in terms of our memory usage — here the column of strings occupies about 6MB, if these strings were longer, it would take even more; compare that to the 0.8MB taken up by the float column. We could afford nearly 8 float64 columns for the price of that one string column...pricey." }, { "code": null, "e": 2713, "s": 2615, "text": ">> df1_cat.memory_usage(deep=True)Index 128float_1 800000species 100416dtype: int64" }, { "code": null, "e": 2961, "s": 2713, "text": "Looking at the memory usage after having cast to a category we see a pretty drastic improvement, about 60x less memory used, very nice. We can now afford 8 of these string columns for the price of one float64 column, oh how the tables have turned." }, { "code": null, "e": 3036, "s": 2961, "text": "This is cool, however, it’s only really cool if we can keep it that way..." }, { "code": null, "e": 3343, "s": 3036, "text": "Seems like a weird thing to say? Well... working with categories can be a lot like playing with those wobbly dolls that spring right back up when you push them over; they will all too easily rock right back into objects if you don’t pay very close attention to each operation using the categorical columns." }, { "code": null, "e": 3582, "s": 3343, "text": "In the best case scenario, this is annoying, in the worst case it kills your performance (because casting types is expensive), and/or blows out your memory (because you could only fit this data into your memory when stored as a category)." }, { "code": null, "e": 3805, "s": 3582, "text": "It’s probable that at some point you’re going to want to do something with your categorical columns, one of those things might be a transformation. This is the first place that we’re going to have to show some diligence..." }, { "code": null, "e": 4063, "s": 3805, "text": "Since categorical columns are often text based columns let’s look at an example using string manipulations, we can do these manipulations on categorical columns in the same way that we do ordinarily for text based object columns; by using the .str accessor." }, { "code": null, "e": 4097, "s": 4063, "text": "On non-categorical string series:" }, { "code": null, "e": 4205, "s": 4097, "text": ">> %timeit df1[\"species\"].str.upper()25.6 ms ± 2.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)" }, { "code": null, "e": 4235, "s": 4205, "text": "On categorical string series:" }, { "code": null, "e": 4349, "s": 4235, "text": ">> %timeit df1_cat[\"species\"].str.upper()1.85 ms ± 41.1 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)" }, { "code": null, "e": 4709, "s": 4349, "text": "The categorical version is a clear winner on performance, about 14x faster in this case (this is because the internal optimizations mean that the .str.upper() is only called once on the unique category values and then a series constructed from the outcome, instead of once per value in the series). However, this is where we run into our first major gotcha..." }, { "code": null, "e": 4774, "s": 4709, "text": ">> df1_cat[\"species\"].str.upper().memory_usage(deep=True)6100576" }, { "code": null, "e": 5093, "s": 4774, "text": "We’ve lost our categorical type, the result is an object type column and the data compression is gone; the result is now once again at it’s 6MB size. We could recast back to a category after this but that is a lot of to-ing and fro-ing between types, it makes our code messier and doesn’t reduce our peak memory usage." }, { "code": null, "e": 5642, "s": 5093, "text": "Oftentimes an efficient alternative is to rewrite your code manipulating categorical columns to operate directly on the categories themselves rather than on the series of their values. This takes a bit of change in mindset (and implementation), you can think of it as just doing an operation once for each unique value in the column, rather than each instance in the column. If you only have a column 2 unique values in its categories spread over 100,000 rows, it makes sense that you would only do the operation 2 times, rather than 100,000 times." }, { "code": null, "e": 5700, "s": 5642, "text": "For example, in the above case we could do the following:" }, { "code": null, "e": 5831, "s": 5700, "text": "%timeit df1_cat[\"species\"].cat.rename_categories(str.upper)239 μs ± 13.9 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)" }, { "code": null, "e": 6058, "s": 5831, "text": "That’s about 10x faster than either of the previous options, and the main benefit is that we never convert the categorical series into an expensive intermediate object column state, so we keep our memory efficiency, very nice." }, { "code": null, "e": 6351, "s": 6058, "text": "It’s a toy example but the principles hold for more complex examples, if there isn’t a specific .cat accessor method which helps for your specific case, consider operating on the df1_cat[“species”].dtype.categories which contain the unique categorical values, rather than on the whole series." }, { "code": null, "e": 6650, "s": 6351, "text": "In all but the simplest of use cases, we are likely to have not just one dataframe, but multiple dataframes which we’ll probably want to stick together at some point. For an example, we’re going to drum up a small ‘reference’ dataset which contains the habitats of the species of our first dataset:" }, { "code": null, "e": 6878, "s": 6650, "text": "df2 = pd.DataFrame( { \"species\": [\"cat\", \"dog\", \"ape\", \"gorilla\", \"snake\"], \"habitat\": [\"house\", \"house\", \"jungle\", \"jungle\", \"jungle\"], })df2_cat = df2.astype({\"species\": \"category\", \"habitat\": \"category\"})" }, { "code": null, "e": 7197, "s": 6878, "text": "As before, we’ve created one categorical version of this dataset, and one with object strings. One thing that’s important to note here is that we have an extra species (snake) which we don’t have in df1 which is the dataframe we’ll be merging with, this will be important later (but don’t worry there won’t be a test)." }, { "code": null, "e": 7359, "s": 7197, "text": "I won’t show an example of merging together two object columns because you all know what happens, object + object = object, there is no magic, it’s just a merge." }, { "code": null, "e": 7498, "s": 7359, "text": "For this little test, we’re going to take one of our categorical dataframes and merge it with the object type column on another dataframe." }, { "code": null, "e": 7611, "s": 7498, "text": ">> df1.merge(df2_cat, on=\"species\").dtypesfloat_1 float64species objecthabitat categorydtype: object" }, { "code": null, "e": 7968, "s": 7611, "text": "So here we had species as object on the left and category on the right. We can see that when we merge we get category + object = object for the merge column in the resultant dataframe. So blah blah blah, this hits us in the memory again when we snap back to objects. Not super surprising, but again, something to be mindful of when working with categories." }, { "code": null, "e": 8083, "s": 7968, "text": "Hopefully I’ve set you up to think that I’m leading up to category + category = category . Well let’s take a look:" }, { "code": null, "e": 8200, "s": 8083, "text": ">> df1_cat.merge(df2_cat, on=\"species\").dtypesfloat_1 float64species objecthabitat categorydtype: object" }, { "code": null, "e": 8272, "s": 8200, "text": "Call the police, I have been deceived... category + category = object ." }, { "code": null, "e": 8982, "s": 8272, "text": "So what’s the sting in the tail? Well in a merge, in order to preserve the categorical type, the two categorical types must be exactly the same. Unlike the other data types in pandas (where, for example, all float64 columns have the same data type), when we talk about the categorical datatypes, the datatype is actually described by the set of values that can exist in that particular category, so you can imagine that a category containing [\"cat\", \"dog\", \"mouse\"] is a different type to the category containing [“cheese”, “milk”, “eggs”] . Although in our case they appear pretty much the same (one is a subset of the other), in df2 we have a species present which isn’t present in df1 (the slippery snake)." }, { "code": null, "e": 9040, "s": 8982, "text": "We can think of the behaviour on merge columns like this:" }, { "code": null, "e": 9071, "s": 9040, "text": "category1 + category2 = object" }, { "code": null, "e": 9105, "s": 9071, "text": "category1 + category1 = category1" }, { "code": null, "e": 9180, "s": 9105, "text": "So adapting the previous example we can get the result we want and expect:" }, { "code": null, "e": 9353, "s": 9180, "text": ">> df1_cat.astype({\"species\": df2_cat[\"species\"].dtype}).merge( df2_cat, on=\"species\" ).dtypesfloat_1 float64species categoryhabitat categorydtype: object" }, { "code": null, "e": 9476, "s": 9353, "text": "Above it can be seen that setting the categorical types to match and then merging gives us the desired results... finally." }, { "code": null, "e": 9840, "s": 9476, "text": "Grouping with categories has personally bitten me in the ankles a couple of times when adapting code to work with categorical datatypes. Once causing behaviour to change unexpectedly, giving a dataframe full of null values and another time causing the operation to hang indefinitely (even though it previously took only a couple of seconds with object datatypes)." }, { "code": null, "e": 9979, "s": 9840, "text": "When you group on a categorical datatype, by default you group on every value in the datatype even if it isn’t present in the data itself." }, { "code": null, "e": 10048, "s": 9979, "text": "What does that mean? It’s probably best illustrated with an example." }, { "code": null, "e": 10228, "s": 10048, "text": "habitat_df = ( df1_cat.astype({\"species\": df2_cat[\"species\"].dtype}) .merge(df2_cat, on=\"species\"))house_animals_df = habitat_df.loc[habitat_df[\"habitat\"] == \"house\"]" }, { "code": null, "e": 10516, "s": 10228, "text": "So here habitat_df is the merge example from the previous section (where both species and habitat end up being categorical), and house_animals_df contains just animals which live in a house, in our case cat and dog. Let’s try to find the average float_1 value for each of these species ." }, { "code": null, "e": 10704, "s": 10516, "text": ">> house_animals_df.groupby(\"species\")[\"float_1\"].mean()speciesape NaNcat 0.501507dog 0.501023gorilla NaNsnake NaNName: float_1, dtype: float64" }, { "code": null, "e": 11183, "s": 10704, "text": "Something looks a bit off, we now get a bunch of null values in our groupby. By default when grouping by on categorical columns, pandas returns a result for each value in the category, even when not present in the data. This can be annoying (since it’s an unexpected change in behaviour), and it can also hurt performance if the datatype contains a lot of groups which aren’t present in the relevant dataframe — particularly if grouping on multiple different categorical column." }, { "code": null, "e": 11320, "s": 11183, "text": "To get the result we want, we can pass observed=True into the groupby call, this ensures that we only get groups for values in the data." }, { "code": null, "e": 11458, "s": 11320, "text": ">> house_animals_df.groupby(\"species\", observed=True)[\"float_1\"].mean()speciescat 0.501507dog 0.501023Name: float_1, dtype: float64" }, { "code": null, "e": 11524, "s": 11458, "text": "Resolved yes, but it’s yet another gotcha to keep us on our toes." }, { "code": null, "e": 11855, "s": 11524, "text": "This case is a little more niche but it adds a bit of colour to the kinds of unexpected problems that you can sometimes run into if you don’t keep your wits about you using categoricals. There are scenarios where you might move row values into columns, for example, the groupby-unstack combo which is somewhat of a pro-gamer move." }, { "code": null, "e": 12158, "s": 11855, "text": ">> species_df = habitat_df.groupby([\"habitat\", \"species\"], observed=True)[\"float_1\"].mean().unstack()>> species_dfspecies cat ape dog gorillahabitat house 0.501507 NaN 0.501023 NaNjungle NaN 0.501284 NaN 0.501108" }, { "code": null, "e": 12292, "s": 12158, "text": "So we’ve got a dataframe now with the species in the columns, all looks normal so far, let’s add another column and see what happens." }, { "code": null, "e": 12400, "s": 12292, "text": ">> species_df[\"new_col\"] = 1TypeError: 'fill_value=new_col' is not present in this Categorical's categories" }, { "code": null, "e": 12697, "s": 12400, "text": "Normally this code would be completely fine, we’re just trying to add a new column called new_col which always has the value 1. Just glancing at the dataframe, nothing looks wrong and the error seems kind of confusing, which Categorical is it talking about, we’re just trying to add a new column?" }, { "code": null, "e": 13103, "s": 12697, "text": "What happens is that the .unstack() (which for the uninitiated, flips the index into the columns much like a pivot) moves the categorical index into the column index. It’s not possible to add an entry to a categorical index which isn’t in the categorical datatype already, hence the error. This isn’t immediately obvious though and you could be forgiven for scratching your head if you ever ended up here." }, { "code": null, "e": 13411, "s": 13103, "text": "There probably isn’t a strong case for ever having a categorical column index, but if accidentally end up with one and/or you start to see strange errors similar to this it may be worth checking datatypes of all of the things you’re working with and make sure there’s nothing weird and categorical going on." }, { "code": null, "e": 13759, "s": 13411, "text": "Pandas categorical dtypes are cool, and can have some good performance benefits. When adopting the use of categorical datatypes it’s important to be aware of how the datatype behaves in different common situations and especially important to make sure categoricals stay categorical throughout the flow of the program and don’t flip back to object." }, { "code": null, "e": 13815, "s": 13759, "text": "Here’s a high level summary of things to be mindful of:" }, { "code": null, "e": 14069, "s": 13815, "text": "When operating on categorical columns, select options which operate on the categories in the datatype rather than the values in the series which contain the datatype. This should allow you to preserve the categorical nature and also improve performance." }, { "code": null, "e": 14237, "s": 14069, "text": "When merging on categorical columns, be aware that to preserve the categorical nature, the categorical types in the merge columns of each dataframe must match exactly." }, { "code": null, "e": 14436, "s": 14237, "text": "When grouping on categorical columns, by default you will get a result for each value in the datatype, even if it’s not present in the data, you can change this using observed=True in the .groupby ." }, { "code": null, "e": 14571, "s": 14436, "text": "When things that you expect to work unexpectedly stop working, consider whether a strange interaction with categoricals may be at play" } ]
Maximum AND Value | Practice | GeeksforGeeks
Given an array arr[] of N positive elements. The task is to find the Maximum AND Value generated by any pair(arri, arrj) from the array such that i != j. Note: AND is bitwise '&' operator. Example 1: Input: N = 4 arr[] = {4, 8, 12, 16} Output: 8 Explanation: Pair (8,12) has the Maximum AND Value 8. Example 2: Input: N = 4 arr[] = {4, 8, 16, 2} Output: 0 Explanation: Any two pairs of the array has Maximum AND Value 0. 0 vishnu12654 days ago public static int maxAND (int arr[], int N) { int res = 0; int pattern = 0; for(int bit=31;bit>=0;bit--){ int value = (1<<bit); if(value < 0){ value = value * -1; } pattern = pattern + value ; int count = 0; for(int i=0;i<arr.length;i++){ if((arr[i] & pattern) == pattern){ count++; } } if(count>=2){ res = res + value; } else{ pattern = pattern - value; } } return res; } 0 gujjulassr1 month ago 0.9/1.9 class Solution{ // Function for finding maximum AND value. public static int maxAND (int arr[], int N) { // Your code here // You can add extra function (if required) int max=0; for(int i=0;i<arr.length;i++){ max=Math.max(max,arr[i]); } int sb=(int)((Math.log(max)/(Math.log(2)))); sb=(int)Math.pow(2,sb); int res=0; int count=0; while(sb>=1){ for(int i=0;i<arr.length;i++){ if(res==0 && (sb&arr[i])==sb){ count++; } else if(res!=0 && (sb&arr[i])==sb && (res&arr[i])==res){ count++; } } if(count>=2){ res+=sb; } // System.out.println(res+" "+count); count=0; sb=sb/2; } return res; } } +1 srujannwankhede7862 months ago class Solution{ public static int maxAND (int arr[], int N) { int pattern = 0; int res = 0; for(int i = 16; i>=0; i--){ int count = 0; for(int j =0; j<arr.length; j++){ if( (arr[j] & (1<<i)) == (1<<i) ) count++; } if(count>=2){ pattern = check(pattern,(1<<i), arr); res = pattern; } } return res; } public static int check(int p,int incr, int[] arr){ int c = 0; for(int j =0; j<arr.length; j++){ if((arr[j]&(p+incr)) == (p+incr) ) c++; } if(c>=2){ return (p+incr); } return p; }} -3 kaustubhug2 months ago class Solution{ public static int maxinarray(int arr[], int N) { int max = arr[0]; for(int i = 1; i<N;i++) max = Math.max(max,arr[i]); return max; } public static int chkBits(int pattern, int arr[], int N) { int count = 0; for(int i = 0; i<N; i++) { if((pattern & arr[i]) == pattern) count+=1; } return count; } public static int maxAND (int arr[], int N) { int max = maxinarray(arr,N); int count = 0, res = 0; int m = (int)(Math.floor(Math.log(max)/Math.log(2))); for(int bits = m; bits >=0; bits--) { count = chkBits(res|(1<<bits),arr,N); if(count>=2) res |= (1<<bits); } return res; } -1 geminicode3 months ago Nlog(M) solution giving TLE in python !!!! -1 kake13373 months ago int m=log2(*max_element(arr,arr+N)); int r=0,p=0; while(m>=0) { p=p|(1<<m); int c=0; for(int i=0;i<N;i++) { if((arr[i]&p)==p) c++; if(c==2) break; } if(c==2) r=p; else p=r; m--; } return r; +1 shubham211019973 months ago int maxAND (int arr[], int n) { // Naive Approach int max=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { int res= arr[i] & arr[j]; if(res>max) max=res; } } } note:- time complexity is high and pass230 cases .Anyone can suggest how to optimize the code. +1 chessnoobdj4 months ago C++ int maxAND (int arr[], int N) { int mx = *max_element(arr, arr+N); int len = log2(mx)+1, ans = 0; for(int i=len; i>=0; i--){ int curr = ans|(1<<i), cnt = 0; for(int j=0; j<N; j++){ if((curr&arr[j]) == curr) cnt += 1; if(cnt == 2) break; } if(cnt == 2) ans = curr; } return ans; } -2 anutiger4 months ago int helper(vector<int> &arr,int i,int ans){ int cnt = 0; for(int j : arr){ int chk1 = j & ans; int chk = (1 << i) & j; if(chk1 == ans and chk != 0){ cnt++; } } return cnt; } int maxAND (int arr[], int N) { int ans = 0; vector<int> res; for(int i = 0; i < N ; i ++) res.push_back(arr[i]); for(int i = 31; i >=0 ; i--){ int temp = helper(res,i,ans); if(temp >= 2){ ans = ans | (1 << i); } } return ans; } 0 kamaan551 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 428, "s": 238, "text": "Given an array arr[] of N positive elements. The task is to find the Maximum AND Value generated by any pair(arri, arrj) from the array such that i != j.\nNote: AND is bitwise '&' operator. " }, { "code": null, "e": 440, "s": 428, "text": "\nExample 1:" }, { "code": null, "e": 542, "s": 440, "text": "Input: \nN = 4\narr[] = {4, 8, 12, 16}\nOutput: 8\nExplanation:\nPair (8,12) has the Maximum AND Value 8.\n" }, { "code": null, "e": 553, "s": 542, "text": "Example 2:" }, { "code": null, "e": 664, "s": 553, "text": "Input:\nN = 4\narr[] = {4, 8, 16, 2}\nOutput: 0\nExplanation: Any two pairs of the array has \nMaximum AND Value 0." }, { "code": null, "e": 666, "s": 664, "text": "0" }, { "code": null, "e": 687, "s": 666, "text": "vishnu12654 days ago" }, { "code": null, "e": 1349, "s": 687, "text": "public static int maxAND (int arr[], int N) {\n int res = 0;\n int pattern = 0;\n for(int bit=31;bit>=0;bit--){\n int value = (1<<bit);\n if(value < 0){\n value = value * -1;\n }\n pattern = pattern + value ;\n \n int count = 0;\n for(int i=0;i<arr.length;i++){\n if((arr[i] & pattern) == pattern){\n count++;\n }\n }\n if(count>=2){\n res = res + value;\n }\n else{\n pattern = pattern - value;\n }\n }\n return res;\n }" }, { "code": null, "e": 1351, "s": 1349, "text": "0" }, { "code": null, "e": 1373, "s": 1351, "text": "gujjulassr1 month ago" }, { "code": null, "e": 1381, "s": 1373, "text": "0.9/1.9" }, { "code": null, "e": 2252, "s": 1381, "text": "class Solution{ // Function for finding maximum AND value. public static int maxAND (int arr[], int N) { // Your code here // You can add extra function (if required) int max=0; for(int i=0;i<arr.length;i++){ max=Math.max(max,arr[i]); } int sb=(int)((Math.log(max)/(Math.log(2)))); sb=(int)Math.pow(2,sb); int res=0; int count=0; while(sb>=1){ for(int i=0;i<arr.length;i++){ if(res==0 && (sb&arr[i])==sb){ count++; } else if(res!=0 && (sb&arr[i])==sb && (res&arr[i])==res){ count++; } } if(count>=2){ res+=sb; } // System.out.println(res+\" \"+count); count=0; sb=sb/2; } return res; } }" }, { "code": null, "e": 2255, "s": 2252, "text": "+1" }, { "code": null, "e": 2286, "s": 2255, "text": "srujannwankhede7862 months ago" }, { "code": null, "e": 3006, "s": 2288, "text": "class Solution{ public static int maxAND (int arr[], int N) { int pattern = 0; int res = 0; for(int i = 16; i>=0; i--){ int count = 0; for(int j =0; j<arr.length; j++){ if( (arr[j] & (1<<i)) == (1<<i) ) count++; } if(count>=2){ pattern = check(pattern,(1<<i), arr); res = pattern; } } return res; } public static int check(int p,int incr, int[] arr){ int c = 0; for(int j =0; j<arr.length; j++){ if((arr[j]&(p+incr)) == (p+incr) ) c++; } if(c>=2){ return (p+incr); } return p; }}" }, { "code": null, "e": 3009, "s": 3006, "text": "-3" }, { "code": null, "e": 3032, "s": 3009, "text": "kaustubhug2 months ago" }, { "code": null, "e": 3048, "s": 3032, "text": "class Solution{" }, { "code": null, "e": 3104, "s": 3053, "text": " public static int maxinarray(int arr[], int N)" }, { "code": null, "e": 3110, "s": 3104, "text": " {" }, { "code": null, "e": 3136, "s": 3110, "text": " int max = arr[0];" }, { "code": null, "e": 3168, "s": 3136, "text": " for(int i = 1; i<N;i++)" }, { "code": null, "e": 3204, "s": 3168, "text": " max = Math.max(max,arr[i]);" }, { "code": null, "e": 3233, "s": 3213, "text": " return max;" }, { "code": null, "e": 3239, "s": 3233, "text": " }" }, { "code": null, "e": 3305, "s": 3244, "text": " public static int chkBits(int pattern, int arr[], int N)" }, { "code": null, "e": 3311, "s": 3305, "text": " {" }, { "code": null, "e": 3335, "s": 3311, "text": " int count = 0;" }, { "code": null, "e": 3368, "s": 3335, "text": " for(int i = 0; i<N; i++)" }, { "code": null, "e": 3378, "s": 3368, "text": " {" }, { "code": null, "e": 3424, "s": 3378, "text": " if((pattern & arr[i]) == pattern)" }, { "code": null, "e": 3446, "s": 3424, "text": " count+=1;" }, { "code": null, "e": 3456, "s": 3446, "text": " }" }, { "code": null, "e": 3478, "s": 3456, "text": " return count;" }, { "code": null, "e": 3484, "s": 3478, "text": " }" }, { "code": null, "e": 3539, "s": 3489, "text": " public static int maxAND (int arr[], int N) {" }, { "code": null, "e": 3577, "s": 3539, "text": " int max = maxinarray(arr,N); " }, { "code": null, "e": 3609, "s": 3577, "text": " int count = 0, res = 0;" }, { "code": null, "e": 3671, "s": 3609, "text": " int m = (int)(Math.floor(Math.log(max)/Math.log(2)));" }, { "code": null, "e": 3715, "s": 3671, "text": " for(int bits = m; bits >=0; bits--)" }, { "code": null, "e": 3725, "s": 3715, "text": " {" }, { "code": null, "e": 3775, "s": 3725, "text": " count = chkBits(res|(1<<bits),arr,N);" }, { "code": null, "e": 3800, "s": 3775, "text": " if(count>=2)" }, { "code": null, "e": 3830, "s": 3800, "text": " res |= (1<<bits);" }, { "code": null, "e": 3840, "s": 3830, "text": " }" }, { "code": null, "e": 3860, "s": 3840, "text": " return res;" }, { "code": null, "e": 3866, "s": 3860, "text": " }" }, { "code": null, "e": 3869, "s": 3866, "text": "-1" }, { "code": null, "e": 3892, "s": 3869, "text": "geminicode3 months ago" }, { "code": null, "e": 3935, "s": 3892, "text": "Nlog(M) solution giving TLE in python !!!!" }, { "code": null, "e": 3938, "s": 3935, "text": "-1" }, { "code": null, "e": 3959, "s": 3938, "text": "kake13373 months ago" }, { "code": null, "e": 4305, "s": 3959, "text": " int m=log2(*max_element(arr,arr+N));\n int r=0,p=0;\n while(m>=0)\n {\n p=p|(1<<m);\n int c=0;\n for(int i=0;i<N;i++)\n {\n if((arr[i]&p)==p)\n c++;\n if(c==2)\n break;\n }\n if(c==2)\n r=p;\n else\n p=r;\n m--;\n }\n return r;" }, { "code": null, "e": 4308, "s": 4305, "text": "+1" }, { "code": null, "e": 4336, "s": 4308, "text": "shubham211019973 months ago" }, { "code": null, "e": 4646, "s": 4336, "text": "int maxAND (int arr[], int n) { // Naive Approach int max=0; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { int res= arr[i] & arr[j]; if(res>max) max=res; } }" }, { "code": null, "e": 4648, "s": 4646, "text": "}" }, { "code": null, "e": 4745, "s": 4650, "text": "note:- time complexity is high and pass230 cases .Anyone can suggest how to optimize the code." }, { "code": null, "e": 4748, "s": 4745, "text": "+1" }, { "code": null, "e": 4772, "s": 4748, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 4776, "s": 4772, "text": "C++" }, { "code": null, "e": 5240, "s": 4776, "text": "int maxAND (int arr[], int N)\n {\n int mx = *max_element(arr, arr+N);\n int len = log2(mx)+1, ans = 0;\n for(int i=len; i>=0; i--){\n int curr = ans|(1<<i), cnt = 0;\n for(int j=0; j<N; j++){\n if((curr&arr[j]) == curr)\n cnt += 1;\n if(cnt == 2)\n break;\n }\n if(cnt == 2)\n ans = curr;\n }\n return ans;\n }" }, { "code": null, "e": 5243, "s": 5240, "text": "-2" }, { "code": null, "e": 5264, "s": 5243, "text": "anutiger4 months ago" }, { "code": null, "e": 5884, "s": 5264, "text": " int helper(vector<int> &arr,int i,int ans){\n int cnt = 0;\n for(int j : arr){\n int chk1 = j & ans;\n int chk = (1 << i) & j;\n if(chk1 == ans and chk != 0){\n cnt++;\n }\n }\n return cnt;\n }\n int maxAND (int arr[], int N)\n {\n int ans = 0;\n vector<int> res;\n for(int i = 0; i < N ; i ++) res.push_back(arr[i]);\n for(int i = 31; i >=0 ; i--){\n int temp = helper(res,i,ans);\n if(temp >= 2){\n ans = ans | (1 << i);\n }\n }\n return ans;\n }" }, { "code": null, "e": 5886, "s": 5884, "text": "0" }, { "code": null, "e": 5896, "s": 5886, "text": "kamaan551" }, { "code": null, "e": 5922, "s": 5896, "text": "This comment was deleted." }, { "code": null, "e": 6068, "s": 5922, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6104, "s": 6068, "text": " Login to access your submissions. " }, { "code": null, "e": 6114, "s": 6104, "text": "\nProblem\n" }, { "code": null, "e": 6124, "s": 6114, "text": "\nContest\n" }, { "code": null, "e": 6187, "s": 6124, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6335, "s": 6187, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6543, "s": 6335, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6649, "s": 6543, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Tryit Editor v3.7
Tryit: HTML paragraph with br
[]
Complex numbers in C++
In this section we will see how to create and use complex numbers in C++. We can create complex number class in C++, that can hold the real and imaginary part of the complex number as member elements. There will be some member functions that are used to handle this class. In this example we are creating one complex type class, a function to display the complex number into correct format. Two additional methods to add and subtract two complex numbers etc. Live Demo #include<iostream> using namespace std; class complex { int real, img; public: complex() { //default constructor to initialize complex number to 0+0i real = 0; img = 0; } complex(int r, int i) { //parameterized constructor to initialize complex number. real = r; img = i; } void set(); void get(); void display(); friend complex add(complex, complex); friend complex sub(complex, complex); }; void complex::set() { cout << "Enter Real part: "; cin >> real; cout << "Enter Imaginary Part: "; cin >> img; } void complex::get() { cout << "The complex number is: "<< real << "+" << img << "i" << endl; } void complex::display() { if(img < 0) if(img == -1) cout << "The complex number is: "<< real << "-i" << endl; else cout << "The complex number is: "<< real << img << "i" << endl; else if(img == 1) cout << "The complex number is: "<< real << " + i"<< endl; else cout << "The complex number is: "<< real << " + " << img << "i" << endl; } complex add(complex c1, complex c2) { complex res; res.real = c1.real + c2.real;//addition for real part res.img = c1.img + c2.img;//addition for imaginary part return res;//the result after addition } complex sub(complex c1, complex c2) { complex res; res.real = c1.real - c2.real;//subtraction for real part res.img = c1.img - c2.img;//subtraction for imaginary part return res;//the result after subtraction } main() { complex n1(3, 2), n2(4, -3); complex result; result = add(n1,n2); result.display(); result = sub(n1,n2); result.display(); } The complex number is: 7-i The complex number is: -1 + 5i
[ { "code": null, "e": 1335, "s": 1062, "text": "In this section we will see how to create and use complex numbers in C++. We can\ncreate complex number class in C++, that can hold the real and imaginary part of the\ncomplex number as member elements. There will be some member functions that\nare used to handle this class." }, { "code": null, "e": 1521, "s": 1335, "text": "In this example we are creating one complex type class, a function to display\nthe complex number into correct format. Two additional methods to add and\nsubtract two complex numbers etc." }, { "code": null, "e": 1532, "s": 1521, "text": " Live Demo" }, { "code": null, "e": 3252, "s": 1532, "text": "#include<iostream>\nusing namespace std;\nclass complex {\n int real, img;\n public:\n complex() {\n //default constructor to initialize complex number to 0+0i\n real = 0; img = 0;\n }\n complex(int r, int i) {\n //parameterized constructor to initialize complex number.\n real = r; img = i;\n }\n void set();\n void get();\n void display();\n friend complex add(complex, complex);\n friend complex sub(complex, complex);\n};\nvoid complex::set() {\n cout << \"Enter Real part: \";\n cin >> real;\n cout << \"Enter Imaginary Part: \";\n cin >> img;\n}\nvoid complex::get() {\n cout << \"The complex number is: \"<< real << \"+\" << img << \"i\" << endl;\n}\nvoid complex::display() {\n if(img < 0)\n if(img == -1)\n cout << \"The complex number is: \"<< real << \"-i\" << endl;\n else\n cout << \"The complex number is: \"<< real << img << \"i\" << endl;\n else\n if(img == 1)\n cout << \"The complex number is: \"<< real << \" + i\"<< endl;\n else\n cout << \"The complex number is: \"<< real << \" + \" << img << \"i\" <<\n endl;\n}\ncomplex add(complex c1, complex c2) {\n complex res;\n res.real = c1.real + c2.real;//addition for real part\n res.img = c1.img + c2.img;//addition for imaginary part\n return res;//the result after addition\n}\ncomplex sub(complex c1, complex c2) {\n complex res;\n res.real = c1.real - c2.real;//subtraction for real part\n res.img = c1.img - c2.img;//subtraction for imaginary part\n return res;//the result after subtraction\n}\nmain() {\n complex n1(3, 2), n2(4, -3);\n complex result;\n result = add(n1,n2);\n result.display();\n result = sub(n1,n2);\n result.display();\n}" }, { "code": null, "e": 3310, "s": 3252, "text": "The complex number is: 7-i\nThe complex number is: -1 + 5i" } ]
How to set the Background Color of the RichTextBox in C#? - GeeksforGeeks
17 Jul, 2019 In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc. In RichTextBox, you are allowed to change the background color of the RichTextBox control using BackColor Property which makes your RichTextBox control more attractive. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the background color of the RichTextBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the RichTextBox control from the ToolBox and drop it on the windows form. You are allowed to place a RichTextBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RichTextBox control set the background color of the RichTextBox control.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can sort the elements present in the RichTextBox control programmatically with the help of given syntax: public override System.Drawing.Color BackColor { get; set; } Here, Color indicates the background color of the RichTextBox. The following steps show how to set the BackColor property of the RichTextBox dynamically: Step 1: Create a RichTextBox using the RichTextBox() constructor is provided by the RichTextBox class.// Creating RichTextBox using RichTextBox class constructor RichTextBox rbox = new RichTextBox(); // Creating RichTextBox using RichTextBox class constructor RichTextBox rbox = new RichTextBox(); Step 2: After creating RichTextBox, set the BackColor Property of the RichTextBox provided by the RichTextBox class.// Setting the background color rbox.BackColor = Color.Aqua; // Setting the background color rbox.BackColor = Color.Aqua; Step 3: And last add this RichTextBox control to the form using Add() method.// Add this RichTextBox to the form this.Controls.Add(rbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = "Enter Text"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.BackColor = Color.Aqua; rbox.Text = "!..Welcome to GeeksforGeeks..!"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}Output: // Add this RichTextBox to the form this.Controls.Add(rbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = "Enter Text"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.BackColor = Color.Aqua; rbox.Text = "!..Welcome to GeeksforGeeks..!"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework Extension Method in C# C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1 Different ways to sort an array in descending order in C#
[ { "code": null, "e": 23613, "s": 23585, "text": "\n17 Jul, 2019" }, { "code": null, "e": 24128, "s": 23613, "text": "In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc. In RichTextBox, you are allowed to change the background color of the RichTextBox control using BackColor Property which makes your RichTextBox control more attractive. You can set this property in two different ways:" }, { "code": null, "e": 24246, "s": 24128, "text": "1. Design-Time: It is the easiest way to set the background color of the RichTextBox as shown in the following steps:" }, { "code": null, "e": 24362, "s": 24246, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 24549, "s": 24362, "text": "Step 2: Drag the RichTextBox control from the ToolBox and drop it on the windows form. You are allowed to place a RichTextBox control anywhere on the windows form according to your need." }, { "code": null, "e": 24694, "s": 24549, "text": "Step 3: After drag and drop you will go to the properties of the RichTextBox control set the background color of the RichTextBox control.Output:" }, { "code": null, "e": 24702, "s": 24694, "text": "Output:" }, { "code": null, "e": 24891, "s": 24702, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can sort the elements present in the RichTextBox control programmatically with the help of given syntax:" }, { "code": null, "e": 24952, "s": 24891, "text": "public override System.Drawing.Color BackColor { get; set; }" }, { "code": null, "e": 25106, "s": 24952, "text": "Here, Color indicates the background color of the RichTextBox. The following steps show how to set the BackColor property of the RichTextBox dynamically:" }, { "code": null, "e": 25307, "s": 25106, "text": "Step 1: Create a RichTextBox using the RichTextBox() constructor is provided by the RichTextBox class.// Creating RichTextBox using RichTextBox class constructor\nRichTextBox rbox = new RichTextBox();\n" }, { "code": null, "e": 25406, "s": 25307, "text": "// Creating RichTextBox using RichTextBox class constructor\nRichTextBox rbox = new RichTextBox();\n" }, { "code": null, "e": 25584, "s": 25406, "text": "Step 2: After creating RichTextBox, set the BackColor Property of the RichTextBox provided by the RichTextBox class.// Setting the background color\nrbox.BackColor = Color.Aqua;\n" }, { "code": null, "e": 25646, "s": 25584, "text": "// Setting the background color\nrbox.BackColor = Color.Aqua;\n" }, { "code": null, "e": 26782, "s": 25646, "text": "Step 3: And last add this RichTextBox control to the form using Add() method.// Add this RichTextBox to the form\nthis.Controls.Add(rbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = \"Enter Text\"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.BackColor = Color.Aqua; rbox.Text = \"!..Welcome to GeeksforGeeks..!\"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}Output:" }, { "code": null, "e": 26844, "s": 26782, "text": "// Add this RichTextBox to the form\nthis.Controls.Add(rbox);\n" }, { "code": null, "e": 26853, "s": 26844, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = \"Enter Text\"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.BackColor = Color.Aqua; rbox.Text = \"!..Welcome to GeeksforGeeks..!\"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}", "e": 27836, "s": 26853, "text": null }, { "code": null, "e": 27844, "s": 27836, "text": "Output:" }, { "code": null, "e": 27847, "s": 27844, "text": "C#" }, { "code": null, "e": 27945, "s": 27847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27954, "s": 27945, "text": "Comments" }, { "code": null, "e": 27967, "s": 27954, "text": "Old Comments" }, { "code": null, "e": 27990, "s": 27967, "text": "C# | Method Overriding" }, { "code": null, "e": 28018, "s": 27990, "text": "C# Dictionary with examples" }, { "code": null, "e": 28064, "s": 28018, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28079, "s": 28064, "text": "C# | Delegates" }, { "code": null, "e": 28119, "s": 28079, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28150, "s": 28119, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28173, "s": 28150, "text": "Extension Method in C#" }, { "code": null, "e": 28195, "s": 28173, "text": "C# | Abstract Classes" }, { "code": null, "e": 28235, "s": 28195, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
How to rotate X-axis tick labels in Pandas bar plot?
Using plt.xticks(x, labels, rotation='vertical'), we can rotate our tick’s label. Create two lists, x, and y. Create two lists, x, and y. Create labels with a list of different cities. Create labels with a list of different cities. Adjust the subplot layout parameters, where bottom = 0.15. Adjust the subplot layout parameters, where bottom = 0.15. Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 1. Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 1. Plot the line using plt.plot(), using x and y (Step 1). Plot the line using plt.plot(), using x and y (Step 1). Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x and label data. Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x and label data. Set or retrieve auto-scaling margins, value is 0.2. Set or retrieve auto-scaling margins, value is 0.2. Set the title of the figure at index 1, the title is "Horizontal tick label". Set the title of the figure at index 1, the title is "Horizontal tick label". Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 2. Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 2. Plot line using plt.plot() method, using x and y (Step 1). Plot line using plt.plot() method, using x and y (Step 1). Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x, label data, and rotation = ’vertical’. Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x, label data, and rotation = ’vertical’. Set or retrieve auto-scaling margins, value is 0.2. Set or retrieve auto-scaling margins, value is 0.2. Set the title of the figure at index 2, the title is "Vertical tick label". Set the title of the figure at index 2, the title is "Vertical tick label". Use plt.show() to show the figure. Use plt.show() to show the figure. import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [1, 4, 9, 6] labels = ['Delhi', 'Mumbai', 'Hyderabad', 'Chennai'] plt.subplots_adjust(bottom=0.15) plt.subplot(121) plt.plot(x, y) plt.xticks(x, labels) plt.margins(0.2) plt.title("Horizontal tick label") plt.subplot(122) plt.plot(x, y) plt.xticks(x, labels, rotation='vertical') plt.margins(0.2) plt.title("Vertical tick label") plt.show()
[ { "code": null, "e": 1144, "s": 1062, "text": "Using plt.xticks(x, labels, rotation='vertical'), we can rotate our tick’s label." }, { "code": null, "e": 1172, "s": 1144, "text": "Create two lists, x, and y." }, { "code": null, "e": 1200, "s": 1172, "text": "Create two lists, x, and y." }, { "code": null, "e": 1247, "s": 1200, "text": "Create labels with a list of different cities." }, { "code": null, "e": 1294, "s": 1247, "text": "Create labels with a list of different cities." }, { "code": null, "e": 1353, "s": 1294, "text": "Adjust the subplot layout parameters, where bottom = 0.15." }, { "code": null, "e": 1412, "s": 1353, "text": "Adjust the subplot layout parameters, where bottom = 0.15." }, { "code": null, "e": 1490, "s": 1412, "text": "Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 1." }, { "code": null, "e": 1568, "s": 1490, "text": "Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 1." }, { "code": null, "e": 1624, "s": 1568, "text": "Plot the line using plt.plot(), using x and y (Step 1)." }, { "code": null, "e": 1680, "s": 1624, "text": "Plot the line using plt.plot(), using x and y (Step 1)." }, { "code": null, "e": 1838, "s": 1680, "text": "Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x and label data." }, { "code": null, "e": 1996, "s": 1838, "text": "Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x and label data." }, { "code": null, "e": 2048, "s": 1996, "text": "Set or retrieve auto-scaling margins, value is 0.2." }, { "code": null, "e": 2100, "s": 2048, "text": "Set or retrieve auto-scaling margins, value is 0.2." }, { "code": null, "e": 2178, "s": 2100, "text": "Set the title of the figure at index 1, the title is \"Horizontal tick label\"." }, { "code": null, "e": 2256, "s": 2178, "text": "Set the title of the figure at index 1, the title is \"Horizontal tick label\"." }, { "code": null, "e": 2334, "s": 2256, "text": "Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 2." }, { "code": null, "e": 2412, "s": 2334, "text": "Add a subplot to the current figure, where nrow = 1, ncols = 2 and index = 2." }, { "code": null, "e": 2471, "s": 2412, "text": "Plot line using plt.plot() method, using x and y (Step 1)." }, { "code": null, "e": 2530, "s": 2471, "text": "Plot line using plt.plot() method, using x and y (Step 1)." }, { "code": null, "e": 2712, "s": 2530, "text": "Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x, label data, and rotation = ’vertical’." }, { "code": null, "e": 2894, "s": 2712, "text": "Get or set the current tick locations and labels of the X-axis. Pass no arguments to return the current values without modifying them, with x, label data, and rotation = ’vertical’." }, { "code": null, "e": 2946, "s": 2894, "text": "Set or retrieve auto-scaling margins, value is 0.2." }, { "code": null, "e": 2998, "s": 2946, "text": "Set or retrieve auto-scaling margins, value is 0.2." }, { "code": null, "e": 3074, "s": 2998, "text": "Set the title of the figure at index 2, the title is \"Vertical tick label\"." }, { "code": null, "e": 3150, "s": 3074, "text": "Set the title of the figure at index 2, the title is \"Vertical tick label\"." }, { "code": null, "e": 3185, "s": 3150, "text": "Use plt.show() to show the figure." }, { "code": null, "e": 3220, "s": 3185, "text": "Use plt.show() to show the figure." }, { "code": null, "e": 3618, "s": 3220, "text": "import matplotlib.pyplot as plt\n\nx = [1, 2, 3, 4]\ny = [1, 4, 9, 6]\nlabels = ['Delhi', 'Mumbai', 'Hyderabad', 'Chennai']\nplt.subplots_adjust(bottom=0.15)\n\nplt.subplot(121)\nplt.plot(x, y)\nplt.xticks(x, labels)\nplt.margins(0.2)\nplt.title(\"Horizontal tick label\")\n\nplt.subplot(122)\nplt.plot(x, y)\nplt.xticks(x, labels, rotation='vertical')\nplt.margins(0.2)\nplt.title(\"Vertical tick label\")\n\nplt.show()" } ]
Find element with the maximum set bits in an array - GeeksforGeeks
26 Nov, 2021 Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000 (5 set bits)Input: arr[] = {3, 2, 4, 7, 1, 10, 5, 8, 9, 6} Output: 7 Approach: Traverse the array and find the count of set bits in the current element and find the element with the maximum number of set bits.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; ; // Function to return the element from the array// which has the maximum set bitsint maxBitElement(int arr[], int n){ // To store the required element and // the maximum set bits so far int num = 0, max = -1; for (int i = 0; i < n; i++) { // Count of set bits in // the current element int cnt = __builtin_popcount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num;} // Driver codeint main(){ int arr[] = { 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 }; int n = sizeof(arr)/ sizeof(arr[0]) ; cout << maxBitElement(arr, n) << endl; return 0 ; // This code is contributed by AnkitRai01} // Java implementation of the approachclass GFG { // Function to return the element from the array // which has the maximum set bits static int maxBitElement(int arr[], int n) { // To store the required element and // the maximum set bits so far int num = 0, max = -1; for (int i = 0; i < n; i++) { // Count of set bits in // the current element int cnt = Integer.bitCount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num; } // Driver code public static void main(String[] args) { int arr[] = { 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 }; int n = arr.length; System.out.print(maxBitElement(arr, n)); }} # Python 3 implementation of the approach # Function to return the element from the array# which has the maximum set bitsdef maxBitElement(arr, n): # To store the required element and # the maximum set bits so far num = 0 max = -1 for i in range(n): # Count of set bits in # the current element cnt = bin(arr[i]).count('1') # Update the max if (cnt > max): max = cnt num = arr[i] return num # Driver codeif __name__ == '__main__': arr = [3, 2, 4, 7, 1, 10, 5, 8, 9, 6] n = len(arr) print(maxBitElement(arr, n)) # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function to return the element from the array // which has the maximum set bits static int maxBitElement(int []arr, int n) { // To store the required element and // the maximum set bits so far int num = 0, max = -1; for (int i = 0; i < n; i++) { // Count of set bits in // the current element int cnt = BitCount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num; } static int BitCount(int n) { int count = 0; while (n != 0) { count++; n &= (n - 1); } return count; } // Driver code public static void Main(String[] args) { int []arr = { 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 }; int n = arr.Length; Console.Write(maxBitElement(arr, n)); }} // This code contributed by Rajput-Ji <?php// PHP implementation of the approach // Function to return the element from// the array which has the maximum set bitsfunction maxBitElement($arr, $n){ // To store the required element and // the maximum set bits so far $num = 0; $max = -1; for ($i = 0; $i < $n; $i++) { // Count of set bits in // the current element $cnt = BitCount($arr[$i]); // Update the max if ($cnt > $max) { $max = $cnt; $num = $arr[$i]; } } return $num;} function BitCount($n){ $count = 0; while ($n != 0) { $count++; $n &= ($n - 1); } return $count;} // Driver code$arr = array(3, 2, 4, 7, 1, 10, 5, 8, 9, 6 );$n = count($arr);echo(maxBitElement($arr, $n)); // This code contributed by PrinciRaj1992?> <script> // Javascript implementation of the approach // Function to return the element from the array// which has the maximum set bitsfunction maxBitElement(arr, n){ // To store the required element and // the maximum set bits so far let num = 0, max = -1; for (let i = 0; i < n; i++) { // Count of set bits in // the current element let cnt = BitCount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num;} function BitCount(n){ let count = 0; while (n != 0) { count++; n &= (n - 1); } return count;} // Driver code let arr = [ 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 ]; let n = arr.length; document.write(maxBitElement(arr, n)); </script> 7 Time Complexity: O(n) Auxiliary Space: O(1) Rajput-Ji ankthon princiraj1992 SURENDRA_GANGWAR rishavmahato348 subhammahato348 Arrays Bit Magic Mathematical Arrays Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Trapping Rain Water Find duplicates in O(n) time and O(1) extra space | Set 1 Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division Count set bits in an integer
[ { "code": null, "e": 24740, "s": 24712, "text": "\n26 Nov, 2021" }, { "code": null, "e": 24856, "s": 24740, "text": "Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: " }, { "code": null, "e": 25114, "s": 24856, "text": "Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000 (5 set bits)Input: arr[] = {3, 2, 4, 7, 1, 10, 5, 8, 9, 6} Output: 7 " }, { "code": null, "e": 25308, "s": 25116, "text": "Approach: Traverse the array and find the count of set bits in the current element and find the element with the maximum number of set bits.Below is the implementation of the above approach: " }, { "code": null, "e": 25312, "s": 25308, "text": "C++" }, { "code": null, "e": 25317, "s": 25312, "text": "Java" }, { "code": null, "e": 25325, "s": 25317, "text": "Python3" }, { "code": null, "e": 25328, "s": 25325, "text": "C#" }, { "code": null, "e": 25332, "s": 25328, "text": "PHP" }, { "code": null, "e": 25343, "s": 25332, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; ; // Function to return the element from the array// which has the maximum set bitsint maxBitElement(int arr[], int n){ // To store the required element and // the maximum set bits so far int num = 0, max = -1; for (int i = 0; i < n; i++) { // Count of set bits in // the current element int cnt = __builtin_popcount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num;} // Driver codeint main(){ int arr[] = { 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 }; int n = sizeof(arr)/ sizeof(arr[0]) ; cout << maxBitElement(arr, n) << endl; return 0 ; // This code is contributed by AnkitRai01}", "e": 26137, "s": 25343, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the element from the array // which has the maximum set bits static int maxBitElement(int arr[], int n) { // To store the required element and // the maximum set bits so far int num = 0, max = -1; for (int i = 0; i < n; i++) { // Count of set bits in // the current element int cnt = Integer.bitCount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num; } // Driver code public static void main(String[] args) { int arr[] = { 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 }; int n = arr.length; System.out.print(maxBitElement(arr, n)); }}", "e": 26956, "s": 26137, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the element from the array# which has the maximum set bitsdef maxBitElement(arr, n): # To store the required element and # the maximum set bits so far num = 0 max = -1 for i in range(n): # Count of set bits in # the current element cnt = bin(arr[i]).count('1') # Update the max if (cnt > max): max = cnt num = arr[i] return num # Driver codeif __name__ == '__main__': arr = [3, 2, 4, 7, 1, 10, 5, 8, 9, 6] n = len(arr) print(maxBitElement(arr, n)) # This code is contributed by# Surendra_Gangwar", "e": 27633, "s": 26956, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the element from the array // which has the maximum set bits static int maxBitElement(int []arr, int n) { // To store the required element and // the maximum set bits so far int num = 0, max = -1; for (int i = 0; i < n; i++) { // Count of set bits in // the current element int cnt = BitCount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num; } static int BitCount(int n) { int count = 0; while (n != 0) { count++; n &= (n - 1); } return count; } // Driver code public static void Main(String[] args) { int []arr = { 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 }; int n = arr.Length; Console.Write(maxBitElement(arr, n)); }} // This code contributed by Rajput-Ji", "e": 28680, "s": 27633, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the element from// the array which has the maximum set bitsfunction maxBitElement($arr, $n){ // To store the required element and // the maximum set bits so far $num = 0; $max = -1; for ($i = 0; $i < $n; $i++) { // Count of set bits in // the current element $cnt = BitCount($arr[$i]); // Update the max if ($cnt > $max) { $max = $cnt; $num = $arr[$i]; } } return $num;} function BitCount($n){ $count = 0; while ($n != 0) { $count++; $n &= ($n - 1); } return $count;} // Driver code$arr = array(3, 2, 4, 7, 1, 10, 5, 8, 9, 6 );$n = count($arr);echo(maxBitElement($arr, $n)); // This code contributed by PrinciRaj1992?>", "e": 29493, "s": 28680, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the element from the array// which has the maximum set bitsfunction maxBitElement(arr, n){ // To store the required element and // the maximum set bits so far let num = 0, max = -1; for (let i = 0; i < n; i++) { // Count of set bits in // the current element let cnt = BitCount(arr[i]); // Update the max if (cnt > max) { max = cnt; num = arr[i]; } } return num;} function BitCount(n){ let count = 0; while (n != 0) { count++; n &= (n - 1); } return count;} // Driver code let arr = [ 3, 2, 4, 7, 1, 10, 5, 8, 9, 6 ]; let n = arr.length; document.write(maxBitElement(arr, n)); </script>", "e": 30289, "s": 29493, "text": null }, { "code": null, "e": 30291, "s": 30289, "text": "7" }, { "code": null, "e": 30315, "s": 30293, "text": "Time Complexity: O(n)" }, { "code": null, "e": 30337, "s": 30315, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30347, "s": 30337, "text": "Rajput-Ji" }, { "code": null, "e": 30355, "s": 30347, "text": "ankthon" }, { "code": null, "e": 30369, "s": 30355, "text": "princiraj1992" }, { "code": null, "e": 30386, "s": 30369, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 30402, "s": 30386, "text": "rishavmahato348" }, { "code": null, "e": 30418, "s": 30402, "text": "subhammahato348" }, { "code": null, "e": 30425, "s": 30418, "text": "Arrays" }, { "code": null, "e": 30435, "s": 30425, "text": "Bit Magic" }, { "code": null, "e": 30448, "s": 30435, "text": "Mathematical" }, { "code": null, "e": 30455, "s": 30448, "text": "Arrays" }, { "code": null, "e": 30468, "s": 30455, "text": "Mathematical" }, { "code": null, "e": 30478, "s": 30468, "text": "Bit Magic" }, { "code": null, "e": 30576, "s": 30478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30585, "s": 30576, "text": "Comments" }, { "code": null, "e": 30598, "s": 30585, "text": "Old Comments" }, { "code": null, "e": 30623, "s": 30598, "text": "Window Sliding Technique" }, { "code": null, "e": 30672, "s": 30623, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30710, "s": 30672, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30730, "s": 30710, "text": "Trapping Rain Water" }, { "code": null, "e": 30788, "s": 30730, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30815, "s": 30788, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30861, "s": 30815, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30929, "s": 30861, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 30975, "s": 30929, "text": "Cyclic Redundancy Check and Modulo-2 Division" } ]
Make all array elements equal with minimum cost
22 Jun, 2022 Given an array which contains integer values, we need to make all values of this array equal to some integer value with minimum cost where the cost of changing an array value x to y is abs(x-y). Examples : Input : arr[] = [1, 100, 101] Output : 100 We can change all its values to 100 with minimum cost, |1 - 100| + |100 - 100| + |101 - 100| = 100 Input : arr[] = [4, 6] Output : 2 We can change all its values to 5 with minimum cost, |4 - 5| + |5 - 6| = 2 This problem can be solved by observing the cost while changing the target equal value, i.e. we will see the change in cost when target equal value is changed. It can be observed that, as we increase the target equal value the total cost decreases up to a limit and then starts increasing i.e. the cost graph with respect to target equal value is of U-shape and as cost graph is in U-shape, the ternary search can be applied to this search space and our goal is to get that bottom most point of the curve which will represent the smallest cost. We will make smallest and largest value of the array as the limit of our search space and then we will keep skipping 1/3 part of the search space until we reach to the bottom most point of our U-curve. Please see below code for better understanding. C++ Java Python3 C# PHP Javascript // C++ program to find minimum cost to// make all elements equal#include <bits/stdc++.h>using namespace std; // Utility method to compute cost, when// all values of array are made equal to Xint computeCost(int arr[], int N, int X){ int cost = 0; for (int i = 0; i < N; i++) cost += abs(arr[i] - X); return cost;} // Method to find minimum cost to make all// elements equalint minCostToMakeElementEqual(int arr[], int N){ int low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (int i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int cost1 = computeCost(arr, N, mid1); int cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return computeCost(arr, N, (low + high) / 2);} // Driver code to test above methodint main(){ int arr[] = { 1, 100, 101 }; int N = sizeof(arr) / sizeof(int); cout << minCostToMakeElementEqual(arr, N); return 0;} // JAVA Code for Make all array elements// equal with minimum costclass GFG { // Utility method to compute cost, when // all values of array are made equal to X public static int computeCost(int arr[], int N, int X) { int cost = 0; for (int i = 0; i < N; i++) cost += Math.abs(arr[i] - X); return cost; } // Method to find minimum cost to make all // elements equal public static int minCostToMakeElementEqual(int arr[], int N) { int low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (int i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int cost1 = computeCost(arr, N, mid1); int cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return computeCost(arr, N, (low + high) / 2); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 1, 100, 101 }; int N = arr.length; System.out.println(minCostToMakeElementEqual(arr, N)); }}// This code is contributed by Arnav Kr. Mandal. # Python3 program to find minimum # cost to make all elements equal # Utility method to compute cost, when# all values of array are made equal to Xdef computeCost(arr, N, X): cost = 0 for i in range(N): cost += abs(arr[i] - X) return cost # Method to find minimum cost to# make all elements equaldef minCostToMakeElementEqual(arr, N): low = high = arr[0] # Setting limits for ternary search # by smallest and largest element for i in range(N): if (low > arr[i]): low = arr[i] if (high < arr[i]): high = arr[i] # loop until difference between low and # high become less than 3, because after # that mid1 and mid2 will start repeating while ((high - low) > 2): # mid1 and mid2 are representative # array equal values of search space mid1 = low + (high - low) // 3 mid2 = high - (high - low) // 3 cost1 = computeCost(arr, N, mid1) cost2 = computeCost(arr, N, mid2) # if mid2 point gives more total # cost, skip third part if (cost1 < cost2): high = mid2 # if mid1 point gives more total # cost, skip first part else: low = mid1 # computeCost gets optimum cost by # sending average of low and high as X return computeCost(arr, N, (low + high) // 2) # Driver codearr = [1, 100, 101]N = len(arr)print(minCostToMakeElementEqual(arr, N)) # This code is contributed by Anant Agarwal. // C# Code to Make all array elements// equal with minimum costusing System; class GFG { // Utility method to compute cost, when // all values of array are made equal to X public static int computeCost(int[] arr, int N, int X) { int cost = 0; for (int i = 0; i < N; i++) cost += Math.Abs(arr[i] - X); return cost; } // Method to find minimum cost to // make all elements equal public static int minCostToMakeElementEqual(int[] arr, int N) { int low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (int i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int cost1 = computeCost(arr, N, mid1); int cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return computeCost(arr, N, (low + high) / 2); } /* Driver program to test above function */ public static void Main() { int[] arr = { 1, 100, 101 }; int N = arr.Length; Console.Write(minCostToMakeElementEqual(arr, N)); }} // This code is contributed by nitin mittal <?php// PHP program to find minimum cost// to make all elements equal // Utility method to compute cost,// when all values of array are// made equal to Xfunction computeCost($arr, $N, $X){ $cost = 0; for ($i = 0; $i < $N; $i++) $cost += abs($arr[$i] - $X); return $cost;} // Method to find minimum cost// to make all elements equalfunction minCostToMakeElementEqual($arr, $N){ $low; $high; $low = $high = $arr[0]; // setting limits for ternary // search by smallest and // largest element for ($i = 0; $i < $N; $i++) { if ($low > $arr[$i]) $low = $arr[$i]; if ($high < $arr[$i]) $high = $arr[$i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while (($high - $low) > 2) { // mid1 and mid2 are representative // array equal values of search space $mid1 = $low + (floor($high - $low) / 3); $mid2 = $high - ($high - $low) / 3; $cost1 = computeCost($arr, $N, $mid1); $cost2 = computeCost($arr, $N, $mid2); // if mid2 point gives more total // cost, skip third part if ($cost1 < $cost2) $high = $mid2; // if mid1 point gives more // total cost, skip first part else $low = $mid1; } // computeCost gets optimum cost by // sending average of low and high as X return computeCost($arr, $N, ($low + $high) / 2);} // Driver Code$arr = array( 1, 100, 101 );$N = sizeof($arr) / sizeof($arr[0]);echo minCostToMakeElementEqual($arr, $N); // This code is contributed by nitin mittal.?> <script> // Javascript program to find minimum cost to// make all elements equal // Utility method to compute cost, when // all values of array are made equal to X function computeCost(arr, N, X) { let cost = 0; for (let i = 0; i < N; i++) cost += Math.abs(arr[i] - X); return cost; } // Method to find minimum cost to make all // elements equal function minCostToMakeElementEqual(arr, N) { let low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (let i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space let mid1 = low + (high - low) / 3; let mid2 = high - (high - low) / 3; let cost1 = computeCost(arr, N, mid1); let cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return Math.round(computeCost(arr, N, (low + high) / 2)); } // Driver Code let arr = [ 1, 100, 101 ]; let N = arr.length; document.write(minCostToMakeElementEqual(arr, N)); </script> 100 Time Complexity: O(NlogN)Auxiliary Space: O(1) Alternate Solution Think geometrically. Assume that array elements are co-ordinates on x axis. The problem reduces to finding another co-ordinate such that the sum of distances between this choice and other co-ordinates is minimized. Observe that: If number of coordinates are odd then y = middle element. If even then y is any number in between middle 2 co-ordinates. Say Input = [a, b, c, d]. Output is any number between b and c including both. Hence the cost is sum which can be computed easily now that we have chosen y. sum|(y-ai)| for all i. It is really easy to code it. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first.int minCostToMakeElementEqual(int a[], int n){ // If there are odd elements, we choose // middle element int y; if (n % 2 == 1) y = a[n / 2]; // If there are even elements, then we choose // the average of middle two. else y = (a[n / 2] + a[(n - 2) / 2]) / 2; // After deciding the final value, find the // result. int s = 0; for(int i = 0; i < n; i++) s += abs(a[i] - y); return s;} // Driver codeint main(){ int a[] = { 1, 100, 101 }; int n = sizeof(a) / sizeof(a[0]); cout << (minCostToMakeElementEqual(a, n));} // This code is contributed by chitranayal import java.io.*;import java.util.*; class GFG{ // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first. public static int minCostToMakeElementEqual(int a[], int n){ // If there are odd elements, we choose // middle element int y; if (n % 2 == 1) y = a[n / 2]; // If there are even elements, then we // choose the average of middle two. else y = (a[n / 2] + a[(n - 2) / 2]) / 2; // After deciding the final value, // find the result. int s = 0; for(int i = 0; i < n; i++) s += Math.abs(a[i] - y); return s;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 100, 101 }; int n = a.length; System.out.println(minCostToMakeElementEqual(a, n));}} // This code is contributed by parascoding # This function assumes that a[] is# sorted. If a[] is not sorted, we need# to sort it first.def minCostToMakeElementEqual(a): l = len(a) # If there are odd elements, we choose # middle element if (l%2 == 1): y = a[l//2] # If there are even elements, then we choose # the average of middle two. else: y = (a[l//2] + a[(l-2)//2])//2 # After deciding the final value, find the # result. s = 0 for i in range(l): s += abs(a[i]-y) return s # Driver codea = [1, 100, 101]print(minCostToMakeElementEqual(a)) using System;using System.Collections.Generic; class GFG{ // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first. static int minCostToMakeElementEqual(int[] a, int n){ // If there are odd elements, we choose // middle element int y; if (n % 2 == 1) y = a[n / 2]; // If there are even elements, then we // choose the average of middle two. else y = (a[n / 2] + a[(n - 2) / 2]) / 2; // After deciding the final value, // find the result. int s = 0; for(int i = 0; i < n; i++) s += Math.Abs(a[i] - y); return s;} // Driver codestatic void Main(){ int[] a = { 1, 100, 101 }; int n = a.Length; Console.WriteLine( minCostToMakeElementEqual(a, n));}} // This code is contributed by divyeshrabadiya07 <script> // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first.function minCostToMakeElementEqual( a, n){ // If there are odd elements, we choose // middle element let y; if (n % 2 == 1) y = a[Math.trunc(n / 2)]; // If there are even elements, then we choose // the average of middle two. else y = Math.trunc((a[n / 2] + a[(n - 2) / 2]) / 2); // After deciding the final value, find the // result. let s = 0; for(let i = 0; i < n; i++) s += Math.abs(a[i] - y); return s;} // Driver program let a = [ 1, 100, 101 ]; let n = a.length; document.write(minCostToMakeElementEqual(a, n)); </script> 100 Time Complexity: O(n)Auxiliary Space: O(1) This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal dhruvprakash1994saraswathi ukasp parascoding divyeshrabadiya07 souravghosh0416 jana_sayantan susobhanakhuli Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Search Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 250, "s": 54, "text": "Given an array which contains integer values, we need to make all values of this array equal to some integer value with minimum cost where the cost of changing an array value x to y is abs(x-y). " }, { "code": null, "e": 262, "s": 250, "text": "Examples : " }, { "code": null, "e": 516, "s": 262, "text": "Input : arr[] = [1, 100, 101]\nOutput : 100\nWe can change all its values to 100 with minimum cost,\n|1 - 100| + |100 - 100| + |101 - 100| = 100\n\nInput : arr[] = [4, 6]\nOutput : 2\nWe can change all its values to 5 with minimum cost,\n|4 - 5| + |5 - 6| = 2" }, { "code": null, "e": 1264, "s": 516, "text": "This problem can be solved by observing the cost while changing the target equal value, i.e. we will see the change in cost when target equal value is changed. It can be observed that, as we increase the target equal value the total cost decreases up to a limit and then starts increasing i.e. the cost graph with respect to target equal value is of U-shape and as cost graph is in U-shape, the ternary search can be applied to this search space and our goal is to get that bottom most point of the curve which will represent the smallest cost. We will make smallest and largest value of the array as the limit of our search space and then we will keep skipping 1/3 part of the search space until we reach to the bottom most point of our U-curve. " }, { "code": null, "e": 1312, "s": 1264, "text": "Please see below code for better understanding." }, { "code": null, "e": 1316, "s": 1312, "text": "C++" }, { "code": null, "e": 1321, "s": 1316, "text": "Java" }, { "code": null, "e": 1329, "s": 1321, "text": "Python3" }, { "code": null, "e": 1332, "s": 1329, "text": "C#" }, { "code": null, "e": 1336, "s": 1332, "text": "PHP" }, { "code": null, "e": 1347, "s": 1336, "text": "Javascript" }, { "code": "// C++ program to find minimum cost to// make all elements equal#include <bits/stdc++.h>using namespace std; // Utility method to compute cost, when// all values of array are made equal to Xint computeCost(int arr[], int N, int X){ int cost = 0; for (int i = 0; i < N; i++) cost += abs(arr[i] - X); return cost;} // Method to find minimum cost to make all// elements equalint minCostToMakeElementEqual(int arr[], int N){ int low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (int i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int cost1 = computeCost(arr, N, mid1); int cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return computeCost(arr, N, (low + high) / 2);} // Driver code to test above methodint main(){ int arr[] = { 1, 100, 101 }; int N = sizeof(arr) / sizeof(int); cout << minCostToMakeElementEqual(arr, N); return 0;}", "e": 3032, "s": 1347, "text": null }, { "code": "// JAVA Code for Make all array elements// equal with minimum costclass GFG { // Utility method to compute cost, when // all values of array are made equal to X public static int computeCost(int arr[], int N, int X) { int cost = 0; for (int i = 0; i < N; i++) cost += Math.abs(arr[i] - X); return cost; } // Method to find minimum cost to make all // elements equal public static int minCostToMakeElementEqual(int arr[], int N) { int low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (int i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int cost1 = computeCost(arr, N, mid1); int cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return computeCost(arr, N, (low + high) / 2); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 1, 100, 101 }; int N = arr.length; System.out.println(minCostToMakeElementEqual(arr, N)); }}// This code is contributed by Arnav Kr. Mandal.", "e": 5083, "s": 3032, "text": null }, { "code": "# Python3 program to find minimum # cost to make all elements equal # Utility method to compute cost, when# all values of array are made equal to Xdef computeCost(arr, N, X): cost = 0 for i in range(N): cost += abs(arr[i] - X) return cost # Method to find minimum cost to# make all elements equaldef minCostToMakeElementEqual(arr, N): low = high = arr[0] # Setting limits for ternary search # by smallest and largest element for i in range(N): if (low > arr[i]): low = arr[i] if (high < arr[i]): high = arr[i] # loop until difference between low and # high become less than 3, because after # that mid1 and mid2 will start repeating while ((high - low) > 2): # mid1 and mid2 are representative # array equal values of search space mid1 = low + (high - low) // 3 mid2 = high - (high - low) // 3 cost1 = computeCost(arr, N, mid1) cost2 = computeCost(arr, N, mid2) # if mid2 point gives more total # cost, skip third part if (cost1 < cost2): high = mid2 # if mid1 point gives more total # cost, skip first part else: low = mid1 # computeCost gets optimum cost by # sending average of low and high as X return computeCost(arr, N, (low + high) // 2) # Driver codearr = [1, 100, 101]N = len(arr)print(minCostToMakeElementEqual(arr, N)) # This code is contributed by Anant Agarwal.", "e": 6552, "s": 5083, "text": null }, { "code": "// C# Code to Make all array elements// equal with minimum costusing System; class GFG { // Utility method to compute cost, when // all values of array are made equal to X public static int computeCost(int[] arr, int N, int X) { int cost = 0; for (int i = 0; i < N; i++) cost += Math.Abs(arr[i] - X); return cost; } // Method to find minimum cost to // make all elements equal public static int minCostToMakeElementEqual(int[] arr, int N) { int low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (int i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int cost1 = computeCost(arr, N, mid1); int cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return computeCost(arr, N, (low + high) / 2); } /* Driver program to test above function */ public static void Main() { int[] arr = { 1, 100, 101 }; int N = arr.Length; Console.Write(minCostToMakeElementEqual(arr, N)); }} // This code is contributed by nitin mittal", "e": 8614, "s": 6552, "text": null }, { "code": "<?php// PHP program to find minimum cost// to make all elements equal // Utility method to compute cost,// when all values of array are// made equal to Xfunction computeCost($arr, $N, $X){ $cost = 0; for ($i = 0; $i < $N; $i++) $cost += abs($arr[$i] - $X); return $cost;} // Method to find minimum cost// to make all elements equalfunction minCostToMakeElementEqual($arr, $N){ $low; $high; $low = $high = $arr[0]; // setting limits for ternary // search by smallest and // largest element for ($i = 0; $i < $N; $i++) { if ($low > $arr[$i]) $low = $arr[$i]; if ($high < $arr[$i]) $high = $arr[$i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while (($high - $low) > 2) { // mid1 and mid2 are representative // array equal values of search space $mid1 = $low + (floor($high - $low) / 3); $mid2 = $high - ($high - $low) / 3; $cost1 = computeCost($arr, $N, $mid1); $cost2 = computeCost($arr, $N, $mid2); // if mid2 point gives more total // cost, skip third part if ($cost1 < $cost2) $high = $mid2; // if mid1 point gives more // total cost, skip first part else $low = $mid1; } // computeCost gets optimum cost by // sending average of low and high as X return computeCost($arr, $N, ($low + $high) / 2);} // Driver Code$arr = array( 1, 100, 101 );$N = sizeof($arr) / sizeof($arr[0]);echo minCostToMakeElementEqual($arr, $N); // This code is contributed by nitin mittal.?>", "e": 10315, "s": 8614, "text": null }, { "code": "<script> // Javascript program to find minimum cost to// make all elements equal // Utility method to compute cost, when // all values of array are made equal to X function computeCost(arr, N, X) { let cost = 0; for (let i = 0; i < N; i++) cost += Math.abs(arr[i] - X); return cost; } // Method to find minimum cost to make all // elements equal function minCostToMakeElementEqual(arr, N) { let low, high; low = high = arr[0]; // setting limits for ternary search by // smallest and largest element for (let i = 0; i < N; i++) { if (low > arr[i]) low = arr[i]; if (high < arr[i]) high = arr[i]; } /* loop until difference between low and high become less than 3, because after that mid1 and mid2 will start repeating */ while ((high - low) > 2) { // mid1 and mid2 are representative array // equal values of search space let mid1 = low + (high - low) / 3; let mid2 = high - (high - low) / 3; let cost1 = computeCost(arr, N, mid1); let cost2 = computeCost(arr, N, mid2); // if mid2 point gives more total cost, // skip third part if (cost1 < cost2) high = mid2; // if mid1 point gives more total cost, // skip first part else low = mid1; } // computeCost gets optimum cost by sending // average of low and high as X return Math.round(computeCost(arr, N, (low + high) / 2)); } // Driver Code let arr = [ 1, 100, 101 ]; let N = arr.length; document.write(minCostToMakeElementEqual(arr, N)); </script>", "e": 12133, "s": 10315, "text": null }, { "code": null, "e": 12137, "s": 12133, "text": "100" }, { "code": null, "e": 12186, "s": 12139, "text": "Time Complexity: O(NlogN)Auxiliary Space: O(1)" }, { "code": null, "e": 12736, "s": 12186, "text": "Alternate Solution Think geometrically. Assume that array elements are co-ordinates on x axis. The problem reduces to finding another co-ordinate such that the sum of distances between this choice and other co-ordinates is minimized. Observe that: If number of coordinates are odd then y = middle element. If even then y is any number in between middle 2 co-ordinates. Say Input = [a, b, c, d]. Output is any number between b and c including both. Hence the cost is sum which can be computed easily now that we have chosen y. sum|(y-ai)| for all i. " }, { "code": null, "e": 12767, "s": 12736, "text": "It is really easy to code it. " }, { "code": null, "e": 12771, "s": 12767, "text": "C++" }, { "code": null, "e": 12776, "s": 12771, "text": "Java" }, { "code": null, "e": 12784, "s": 12776, "text": "Python3" }, { "code": null, "e": 12787, "s": 12784, "text": "C#" }, { "code": null, "e": 12798, "s": 12787, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first.int minCostToMakeElementEqual(int a[], int n){ // If there are odd elements, we choose // middle element int y; if (n % 2 == 1) y = a[n / 2]; // If there are even elements, then we choose // the average of middle two. else y = (a[n / 2] + a[(n - 2) / 2]) / 2; // After deciding the final value, find the // result. int s = 0; for(int i = 0; i < n; i++) s += abs(a[i] - y); return s;} // Driver codeint main(){ int a[] = { 1, 100, 101 }; int n = sizeof(a) / sizeof(a[0]); cout << (minCostToMakeElementEqual(a, n));} // This code is contributed by chitranayal", "e": 13580, "s": 12798, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG{ // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first. public static int minCostToMakeElementEqual(int a[], int n){ // If there are odd elements, we choose // middle element int y; if (n % 2 == 1) y = a[n / 2]; // If there are even elements, then we // choose the average of middle two. else y = (a[n / 2] + a[(n - 2) / 2]) / 2; // After deciding the final value, // find the result. int s = 0; for(int i = 0; i < n; i++) s += Math.abs(a[i] - y); return s;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 100, 101 }; int n = a.length; System.out.println(minCostToMakeElementEqual(a, n));}} // This code is contributed by parascoding", "e": 14472, "s": 13580, "text": null }, { "code": "# This function assumes that a[] is# sorted. If a[] is not sorted, we need# to sort it first.def minCostToMakeElementEqual(a): l = len(a) # If there are odd elements, we choose # middle element if (l%2 == 1): y = a[l//2] # If there are even elements, then we choose # the average of middle two. else: y = (a[l//2] + a[(l-2)//2])//2 # After deciding the final value, find the # result. s = 0 for i in range(l): s += abs(a[i]-y) return s # Driver codea = [1, 100, 101]print(minCostToMakeElementEqual(a))", "e": 15034, "s": 14472, "text": null }, { "code": "using System;using System.Collections.Generic; class GFG{ // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first. static int minCostToMakeElementEqual(int[] a, int n){ // If there are odd elements, we choose // middle element int y; if (n % 2 == 1) y = a[n / 2]; // If there are even elements, then we // choose the average of middle two. else y = (a[n / 2] + a[(n - 2) / 2]) / 2; // After deciding the final value, // find the result. int s = 0; for(int i = 0; i < n; i++) s += Math.Abs(a[i] - y); return s;} // Driver codestatic void Main(){ int[] a = { 1, 100, 101 }; int n = a.Length; Console.WriteLine( minCostToMakeElementEqual(a, n));}} // This code is contributed by divyeshrabadiya07", "e": 15924, "s": 15034, "text": null }, { "code": "<script> // This function assumes that a[] is// sorted. If a[] is not sorted, we need// to sort it first.function minCostToMakeElementEqual( a, n){ // If there are odd elements, we choose // middle element let y; if (n % 2 == 1) y = a[Math.trunc(n / 2)]; // If there are even elements, then we choose // the average of middle two. else y = Math.trunc((a[n / 2] + a[(n - 2) / 2]) / 2); // After deciding the final value, find the // result. let s = 0; for(let i = 0; i < n; i++) s += Math.abs(a[i] - y); return s;} // Driver program let a = [ 1, 100, 101 ]; let n = a.length; document.write(minCostToMakeElementEqual(a, n)); </script>", "e": 16662, "s": 15924, "text": null }, { "code": null, "e": 16666, "s": 16662, "text": "100" }, { "code": null, "e": 16709, "s": 16666, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 17133, "s": 16709, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17146, "s": 17133, "text": "nitin mittal" }, { "code": null, "e": 17173, "s": 17146, "text": "dhruvprakash1994saraswathi" }, { "code": null, "e": 17179, "s": 17173, "text": "ukasp" }, { "code": null, "e": 17191, "s": 17179, "text": "parascoding" }, { "code": null, "e": 17209, "s": 17191, "text": "divyeshrabadiya07" }, { "code": null, "e": 17225, "s": 17209, "text": "souravghosh0416" }, { "code": null, "e": 17239, "s": 17225, "text": "jana_sayantan" }, { "code": null, "e": 17254, "s": 17239, "text": "susobhanakhuli" }, { "code": null, "e": 17261, "s": 17254, "text": "Arrays" }, { "code": null, "e": 17271, "s": 17261, "text": "Searching" }, { "code": null, "e": 17278, "s": 17271, "text": "Arrays" }, { "code": null, "e": 17288, "s": 17278, "text": "Searching" }, { "code": null, "e": 17386, "s": 17288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17418, "s": 17386, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 17432, "s": 17418, "text": "Linear Search" }, { "code": null, "e": 17517, "s": 17432, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 17540, "s": 17517, "text": "Introduction to Arrays" }, { "code": null, "e": 17596, "s": 17540, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 17610, "s": 17596, "text": "Binary Search" }, { "code": null, "e": 17624, "s": 17610, "text": "Linear Search" }, { "code": null, "e": 17680, "s": 17624, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 17728, "s": 17680, "text": "Search an element in a sorted and rotated array" } ]
How to Add Customize Tabs in Android?
15 Jun, 2022 In this article, custom tabs are added in android. TabLayout provides a horizontal layout to display tabs. TabLayouts can be added using viewPager also, check here, but it can not be customized. Whenever the user clicks on the tab it will lead to the transaction of one Fragment to another. Custom tabs can be created to achieve this same task. Icons, animation, text, etc according to our need can be added with tabs. Below image shows an example of a custom tab: Approach: Step 1: Create an AlgorithmFragment by right click on java package, select new ? Fragment(Blank). Step 2: Follow the above step for CourseFragment and LoginFragment. Step 3: Now add the following code in the fragment_algorithm.xml file. Here a TextView is added in the layout. fragment_algorithm.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Fragments.AlgorithmFragment" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Algorithm" android:textSize="30sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout> Step 4: Now add the following code in fragment_course.xml file. Here a textView is added in the layout. fragment_course.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Fragments.AlgorithmFragment" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Course" android:textSize="30sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout> Step 5: Now add the following code in fragment_profile.xml file. Here a textView is added in the layout. fragment_profile.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Fragments.AlgorithmFragment" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Algorithm" android:textSize="30sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout> Step 6: Now add the following code in the tab_bar.xml file. In this file, design the layout of the custom tabs. Here for every fragment, a TextView and an icon (ImageView) is added. tab_bar.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout android:background="@color/colorPrimaryDark" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="70dp" android:orientation="horizontal"> <LinearLayout android:onClick="onClick" android:id="@+id/algo_lay" android:layout_marginTop="4dp" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="70dp" android:orientation="vertical"> <ImageView android:layout_gravity="center" android:src="@drawable/ic_algorithm" android:layout_width="wrap_content" android:layout_height="35dp" android:id="@+id/first_icon"/> <TextView android:id="@+id/commerce_first_text" android:textColor="#FFFF" android:layout_marginTop="3dp" android:textStyle="bold" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:text="Algorith" /> </LinearLayout> <LinearLayout android:onClick="onClick" android:id="@+id/course_lay" android:layout_marginTop="4dp" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="70dp" android:orientation="vertical"> <ImageView android:layout_gravity="center" android:src="@drawable/ic_course" android:layout_width="wrap_content" android:layout_height="35dp" android:id="@+id/sec_icon"/> <TextView android:id="@+id/commerce_sec_text" android:textColor="#FFFF" android:layout_marginTop="3dp" android:textStyle="bold" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:text="Course" /> </LinearLayout> <LinearLayout android:onClick="onClick" android:id="@+id/profile_lay" android:layout_marginTop="4dp" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="70dp" android:orientation="vertical"> <ImageView android:layout_gravity="center" android:src="@drawable/ic_account" android:layout_width="wrap_content" android:layout_height="35dp" android:id="@+id/third_icon"/> <TextView android:id="@+id/commerce_third_text" android:textColor="#FFFF" android:layout_marginTop="3dp" android:textStyle="bold" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:text="Profile" /> </LinearLayout> </LinearLayout> Step 7: Now add the following code in the activity_main.xml file. In this file, add the layout of the custom tabs and a container for the fragment. 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" tools:context=".MainActivity" android:orientation="vertical"> <include layout="@layout/tab_bar"/> <FrameLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" /></LinearLayout> Step 8: Now add the following code in the MainActivity.java file. In this file, add OnNavigationItemSelectedListener that helps to navigate between the fragments. It will switch the fragment when the user taps on the icon. MainActivity.java package org.geeksforgeeks.customtabs; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.FrameLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportFragmentManager().beginTransaction() .add(R.id.layout,new AlgorithmFragment()).commit(); } public void onClick(View v){ switch (v.getId()){ case R.id.algo_lay: getSupportFragmentManager().beginTransaction() .replace(R.id.layout, new AlgorithmFragment()).commit(); break; case R.id.course_lay: getSupportFragmentManager().beginTransaction() .replace(new CourseFragment().commit(),R.id.layout); break; case R.id.profile_lay: getSupportFragmentManager().beginTransaction() .replace(R.id.layout, new ProfileFragment()).commit(); break; } }} Output: Media error: Format(s) not supported or source(s) not found Code_r android 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": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 518, "s": 52, "text": "In this article, custom tabs are added in android. TabLayout provides a horizontal layout to display tabs. TabLayouts can be added using viewPager also, check here, but it can not be customized. Whenever the user clicks on the tab it will lead to the transaction of one Fragment to another. Custom tabs can be created to achieve this same task. Icons, animation, text, etc according to our need can be added with tabs. Below image shows an example of a custom tab: " }, { "code": null, "e": 530, "s": 518, "text": "Approach: " }, { "code": null, "e": 628, "s": 530, "text": "Step 1: Create an AlgorithmFragment by right click on java package, select new ? Fragment(Blank)." }, { "code": null, "e": 696, "s": 628, "text": "Step 2: Follow the above step for CourseFragment and LoginFragment." }, { "code": null, "e": 810, "s": 696, "text": "Step 3: Now add the following code in the fragment_algorithm.xml file. Here a TextView is added in the layout. " }, { "code": null, "e": 833, "s": 810, "text": "fragment_algorithm.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Fragments.AlgorithmFragment\" android:orientation=\"vertical\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Algorithm\" android:textSize=\"30sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /></androidx.constraintlayout.widget.ConstraintLayout>", "e": 1709, "s": 833, "text": null }, { "code": null, "e": 1814, "s": 1709, "text": "Step 4: Now add the following code in fragment_course.xml file. Here a textView is added in the layout. " }, { "code": null, "e": 1834, "s": 1814, "text": "fragment_course.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Fragments.AlgorithmFragment\" android:orientation=\"vertical\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Course\" android:textSize=\"30sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /></androidx.constraintlayout.widget.ConstraintLayout>", "e": 2707, "s": 1834, "text": null }, { "code": null, "e": 2814, "s": 2707, "text": "Step 5: Now add the following code in fragment_profile.xml file. Here a textView is added in the layout. " }, { "code": null, "e": 2835, "s": 2814, "text": "fragment_profile.xml" }, { "code": " <?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Fragments.AlgorithmFragment\" android:orientation=\"vertical\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Algorithm\" android:textSize=\"30sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /></androidx.constraintlayout.widget.ConstraintLayout>", "e": 3717, "s": 2835, "text": null }, { "code": null, "e": 3901, "s": 3717, "text": "Step 6: Now add the following code in the tab_bar.xml file. In this file, design the layout of the custom tabs. Here for every fragment, a TextView and an icon (ImageView) is added. " }, { "code": null, "e": 3913, "s": 3901, "text": "tab_bar.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout android:background=\"@color/colorPrimaryDark\" xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"70dp\" android:orientation=\"horizontal\"> <LinearLayout android:onClick=\"onClick\" android:id=\"@+id/algo_lay\" android:layout_marginTop=\"4dp\" android:layout_weight=\"1\" android:layout_width=\"match_parent\" android:layout_height=\"70dp\" android:orientation=\"vertical\"> <ImageView android:layout_gravity=\"center\" android:src=\"@drawable/ic_algorithm\" android:layout_width=\"wrap_content\" android:layout_height=\"35dp\" android:id=\"@+id/first_icon\"/> <TextView android:id=\"@+id/commerce_first_text\" android:textColor=\"#FFFF\" android:layout_marginTop=\"3dp\" android:textStyle=\"bold\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:textAlignment=\"center\" android:text=\"Algorith\" /> </LinearLayout> <LinearLayout android:onClick=\"onClick\" android:id=\"@+id/course_lay\" android:layout_marginTop=\"4dp\" android:layout_weight=\"1\" android:layout_width=\"match_parent\" android:layout_height=\"70dp\" android:orientation=\"vertical\"> <ImageView android:layout_gravity=\"center\" android:src=\"@drawable/ic_course\" android:layout_width=\"wrap_content\" android:layout_height=\"35dp\" android:id=\"@+id/sec_icon\"/> <TextView android:id=\"@+id/commerce_sec_text\" android:textColor=\"#FFFF\" android:layout_marginTop=\"3dp\" android:textStyle=\"bold\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:textAlignment=\"center\" android:text=\"Course\" /> </LinearLayout> <LinearLayout android:onClick=\"onClick\" android:id=\"@+id/profile_lay\" android:layout_marginTop=\"4dp\" android:layout_weight=\"1\" android:layout_width=\"match_parent\" android:layout_height=\"70dp\" android:orientation=\"vertical\"> <ImageView android:layout_gravity=\"center\" android:src=\"@drawable/ic_account\" android:layout_width=\"wrap_content\" android:layout_height=\"35dp\" android:id=\"@+id/third_icon\"/> <TextView android:id=\"@+id/commerce_third_text\" android:textColor=\"#FFFF\" android:layout_marginTop=\"3dp\" android:textStyle=\"bold\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:textAlignment=\"center\" android:text=\"Profile\" /> </LinearLayout> </LinearLayout>", "e": 6902, "s": 3913, "text": null }, { "code": null, "e": 7052, "s": 6902, "text": "Step 7: Now add the following code in the activity_main.xml file. In this file, add the layout of the custom tabs and a container for the fragment. " }, { "code": null, "e": 7070, "s": 7052, "text": "activity_main.xml" }, { "code": "<?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\" tools:context=\".MainActivity\" android:orientation=\"vertical\"> <include layout=\"@layout/tab_bar\"/> <FrameLayout android:id=\"@+id/layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /></LinearLayout>", "e": 7646, "s": 7070, "text": null }, { "code": null, "e": 7871, "s": 7646, "text": "Step 8: Now add the following code in the MainActivity.java file. In this file, add OnNavigationItemSelectedListener that helps to navigate between the fragments. It will switch the fragment when the user taps on the icon. " }, { "code": null, "e": 7889, "s": 7871, "text": "MainActivity.java" }, { "code": "package org.geeksforgeeks.customtabs; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.FrameLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportFragmentManager().beginTransaction() .add(R.id.layout,new AlgorithmFragment()).commit(); } public void onClick(View v){ switch (v.getId()){ case R.id.algo_lay: getSupportFragmentManager().beginTransaction() .replace(R.id.layout, new AlgorithmFragment()).commit(); break; case R.id.course_lay: getSupportFragmentManager().beginTransaction() .replace(new CourseFragment().commit(),R.id.layout); break; case R.id.profile_lay: getSupportFragmentManager().beginTransaction() .replace(R.id.layout, new ProfileFragment()).commit(); break; } }}", "e": 9113, "s": 7889, "text": null }, { "code": null, "e": 9121, "s": 9113, "text": "Output:" }, { "code": null, "e": 9181, "s": 9121, "text": "Media error: Format(s) not supported or source(s) not found" }, { "code": null, "e": 9190, "s": 9183, "text": "Code_r" }, { "code": null, "e": 9198, "s": 9190, "text": "android" }, { "code": null, "e": 9203, "s": 9198, "text": "Java" }, { "code": null, "e": 9208, "s": 9203, "text": "Java" }, { "code": null, "e": 9306, "s": 9208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9321, "s": 9306, "text": "Stream In Java" }, { "code": null, "e": 9342, "s": 9321, "text": "Introduction to Java" }, { "code": null, "e": 9363, "s": 9342, "text": "Constructors in Java" }, { "code": null, "e": 9382, "s": 9363, "text": "Exceptions in Java" }, { "code": null, "e": 9399, "s": 9382, "text": "Generics in Java" }, { "code": null, "e": 9429, "s": 9399, "text": "Functional Interfaces in Java" }, { "code": null, "e": 9455, "s": 9429, "text": "Java Programming Examples" }, { "code": null, "e": 9471, "s": 9455, "text": "Strings in Java" }, { "code": null, "e": 9508, "s": 9471, "text": "Differences between JDK, JRE and JVM" } ]
Python String | min()
07 Jan, 2018 min() is an inbuilt function in Python programming language that returns the minimum alphabetical character in a string. Syntax: min(string) Parameter:min() method takes a string as a parameter Return value: Returns a character which is alphabetically the lowest character in the string. Below is the Python implementation of the method min() # python program to demonstrate the use of # min() function # minimum alphabetical character in # "geeks" string = "geeks" print(min(string)) # minimum alphabetical character in # "raj"string = "raj" print(min(string)) Output: e a python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jan, 2018" }, { "code": null, "e": 174, "s": 53, "text": "min() is an inbuilt function in Python programming language that returns the minimum alphabetical character in a string." }, { "code": null, "e": 182, "s": 174, "text": "Syntax:" }, { "code": null, "e": 194, "s": 182, "text": "min(string)" }, { "code": null, "e": 247, "s": 194, "text": "Parameter:min() method takes a string as a parameter" }, { "code": null, "e": 261, "s": 247, "text": "Return value:" }, { "code": null, "e": 341, "s": 261, "text": "Returns a character which is alphabetically the lowest character in the string." }, { "code": null, "e": 396, "s": 341, "text": "Below is the Python implementation of the method min()" }, { "code": "# python program to demonstrate the use of # min() function # minimum alphabetical character in # \"geeks\" string = \"geeks\" print(min(string)) # minimum alphabetical character in # \"raj\"string = \"raj\" print(min(string))", "e": 618, "s": 396, "text": null }, { "code": null, "e": 626, "s": 618, "text": "Output:" }, { "code": null, "e": 631, "s": 626, "text": "e\na\n" }, { "code": null, "e": 645, "s": 631, "text": "python-string" }, { "code": null, "e": 652, "s": 645, "text": "Python" }, { "code": null, "e": 750, "s": 652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 782, "s": 750, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 809, "s": 782, "text": "Python Classes and Objects" }, { "code": null, "e": 830, "s": 809, "text": "Python OOPs Concepts" }, { "code": null, "e": 853, "s": 830, "text": "Introduction To PYTHON" }, { "code": null, "e": 909, "s": 853, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 940, "s": 909, "text": "Python | os.path.join() method" }, { "code": null, "e": 982, "s": 940, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1024, "s": 982, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1063, "s": 1024, "text": "Python | Get unique values from a list" } ]
list pop_front() function in C++ STL
13 Jun, 2022 The list::pop_front() is a built-in function in C++ STL which is used to remove an element from the front of a list container. This function thus decreases the size of the container by 1 as it deletes the element from the front of a list. Syntax: list_name.pop_front(); Parameters: The function does not accept any parameter. Return Value: This function does not returns anything. Below program illustrate the list::pop_front() function in C++ STL: CPP // CPP program to illustrate the// list::pop_front() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Adding elements to the list // using push_back() demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // Initial List: cout << "Initial List: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; // removing an element from the front of List // using pop_front demoList.pop_front(); // List after removing element from front cout << "\n\nList after removing an element from front: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << " "; return 0;} Initial List: 10 20 30 40 List after removing an element from front: 20 30 40 Time Complexity: O(n) Auxiliary Space: O(1) utkarshgupta110092 CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Priority Queue in C++ Standard Template Library (STL) Substring in C++ Object Oriented Programming in C++ C++ Classes and Objects Sorting a vector in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 299, "s": 52, "text": "The list::pop_front() is a built-in function in C++ STL which is used to remove an element from the front of a list container. This function thus decreases the size of the container by 1 as it deletes the element from the front of a list. Syntax:" }, { "code": null, "e": 322, "s": 299, "text": "list_name.pop_front();" }, { "code": null, "e": 502, "s": 322, "text": "Parameters: The function does not accept any parameter. Return Value: This function does not returns anything. Below program illustrate the list::pop_front() function in C++ STL: " }, { "code": null, "e": 506, "s": 502, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::pop_front() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Adding elements to the list // using push_back() demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // Initial List: cout << \"Initial List: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << \" \"; // removing an element from the front of List // using pop_front demoList.pop_front(); // List after removing element from front cout << \"\\n\\nList after removing an element from front: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) cout << *itr << \" \"; return 0;}", "e": 1230, "s": 506, "text": null }, { "code": null, "e": 1310, "s": 1230, "text": "Initial List: 10 20 30 40 \n\nList after removing an element from front: 20 30 40" }, { "code": null, "e": 1332, "s": 1310, "text": "Time Complexity: O(n)" }, { "code": null, "e": 1354, "s": 1332, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1373, "s": 1354, "text": "utkarshgupta110092" }, { "code": null, "e": 1387, "s": 1373, "text": "CPP-Functions" }, { "code": null, "e": 1396, "s": 1387, "text": "cpp-list" }, { "code": null, "e": 1400, "s": 1396, "text": "STL" }, { "code": null, "e": 1404, "s": 1400, "text": "C++" }, { "code": null, "e": 1408, "s": 1404, "text": "STL" }, { "code": null, "e": 1412, "s": 1408, "text": "CPP" }, { "code": null, "e": 1510, "s": 1412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1537, "s": 1510, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1580, "s": 1537, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1614, "s": 1580, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1639, "s": 1614, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1658, "s": 1639, "text": "Inheritance in C++" }, { "code": null, "e": 1712, "s": 1658, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1729, "s": 1712, "text": "Substring in C++" }, { "code": null, "e": 1764, "s": 1729, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 1788, "s": 1764, "text": "C++ Classes and Objects" } ]
How to add active class on click event in custom list group in Bootstrap 4 ?
03 Aug, 2021 In Bootstrap 4, Javascript or jQuery events are used to add active class on click event in custom list group. Syntax: $(document).ready(function() { $('selector').click(function() { $('selector.active').removeClass("active"); $(this).addClass("active"); }); }); Following examples illustrates how to add active class on click event in custom list group using jQuery in different ways. Example 1: Below example illustrates how to add active class on click event in custom list group using jQuery through for loop. <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <center> <div class="container"> <h1 class="text-success">GeeksforGeeks</h1> <h3>Active Item in a List Group</h3> </div> </center> <div class="list-group"> <a href="#!" class="list-group-item list-group-item-action flex-column align-items-start active"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-2 h5">DSA Courses Available soon</h5> <small>1 days ago</small> </div> <p class="mb-2"> This course is will take you from basics to advance as well as it will certify you on the basis of your performance. </p> <small>Students, Working Professionals</small> </a> <a href="#!" class="list-group-item list-group-item-action flex-column align-items-start"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-2 h5">Placement 100</h5> <small>2 days ago</small> </div> <p class="mb-2"> This course will guide you for placements with theory, lecture videos, weekly assessments, contests and doubt assistance. </p> <small>Pre-final, Final year students</small> </a> <a href="#!" class="list-group-item list-group-item-action flex-column align-items-start"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-2 h5"> Machine Learning Foundation With Python </h5> <small>4 days ago</small> </div> <p class="mb-2"> Learn about the concepts of Machine Learning, effective machine learning techniques from basics with Python. </p> <small> Students, Working Professionals seeking a career in ML </small> </a> </div> <script> $(".list-group-item").click(function() { // Select all list items var listItems = $(".list-group-item"); // Remove 'active' tag for all list items for (let i = 0; i < listItems.length; i++) { listItems[i].classList.remove("active"); } // Add 'active' tag for currently selected item this.classList.add("active"); }); </script></body> </html> Output: Example 2: Below example illustrates how to add active class on click event in custom list group using jQuery along with addClass and removeClass of jQuery class attribute manipulation. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1 class="text-success text-center">GeeksforGeeks</h1> <h3>Active Item in a List Group</h3> <ul class="list-group"> <li class="list-group-item active">Active item</li> <li class="list-group-item">Click me to active item</li> <li class="list-group-item">Click me too active item item</li> </ul> </div> <script> $(document).ready(function() { $('li').click(function() { $('li.list-group-item.active').removeClass("active"); $(this).addClass("active"); }); }); </script></body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. JavaScript-Misc jQuery-Misc Picked Bootstrap JavaScript JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Aug, 2021" }, { "code": null, "e": 162, "s": 52, "text": "In Bootstrap 4, Javascript or jQuery events are used to add active class on click event in custom list group." }, { "code": null, "e": 170, "s": 162, "text": "Syntax:" }, { "code": null, "e": 339, "s": 170, "text": "$(document).ready(function() {\n $('selector').click(function() {\n $('selector.active').removeClass(\"active\");\n $(this).addClass(\"active\");\n });\n});\n" }, { "code": null, "e": 462, "s": 339, "text": "Following examples illustrates how to add active class on click event in custom list group using jQuery in different ways." }, { "code": null, "e": 590, "s": 462, "text": "Example 1: Below example illustrates how to add active class on click event in custom list group using jQuery through for loop." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <center> <div class=\"container\"> <h1 class=\"text-success\">GeeksforGeeks</h1> <h3>Active Item in a List Group</h3> </div> </center> <div class=\"list-group\"> <a href=\"#!\" class=\"list-group-item list-group-item-action flex-column align-items-start active\"> <div class=\"d-flex w-100 justify-content-between\"> <h5 class=\"mb-2 h5\">DSA Courses Available soon</h5> <small>1 days ago</small> </div> <p class=\"mb-2\"> This course is will take you from basics to advance as well as it will certify you on the basis of your performance. </p> <small>Students, Working Professionals</small> </a> <a href=\"#!\" class=\"list-group-item list-group-item-action flex-column align-items-start\"> <div class=\"d-flex w-100 justify-content-between\"> <h5 class=\"mb-2 h5\">Placement 100</h5> <small>2 days ago</small> </div> <p class=\"mb-2\"> This course will guide you for placements with theory, lecture videos, weekly assessments, contests and doubt assistance. </p> <small>Pre-final, Final year students</small> </a> <a href=\"#!\" class=\"list-group-item list-group-item-action flex-column align-items-start\"> <div class=\"d-flex w-100 justify-content-between\"> <h5 class=\"mb-2 h5\"> Machine Learning Foundation With Python </h5> <small>4 days ago</small> </div> <p class=\"mb-2\"> Learn about the concepts of Machine Learning, effective machine learning techniques from basics with Python. </p> <small> Students, Working Professionals seeking a career in ML </small> </a> </div> <script> $(\".list-group-item\").click(function() { // Select all list items var listItems = $(\".list-group-item\"); // Remove 'active' tag for all list items for (let i = 0; i < listItems.length; i++) { listItems[i].classList.remove(\"active\"); } // Add 'active' tag for currently selected item this.classList.add(\"active\"); }); </script></body> </html>", "e": 4061, "s": 590, "text": null }, { "code": null, "e": 4069, "s": 4061, "text": "Output:" }, { "code": null, "e": 4255, "s": 4069, "text": "Example 2: Below example illustrates how to add active class on click event in custom list group using jQuery along with addClass and removeClass of jQuery class attribute manipulation." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\"href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1 class=\"text-success text-center\">GeeksforGeeks</h1> <h3>Active Item in a List Group</h3> <ul class=\"list-group\"> <li class=\"list-group-item active\">Active item</li> <li class=\"list-group-item\">Click me to active item</li> <li class=\"list-group-item\">Click me too active item item</li> </ul> </div> <script> $(document).ready(function() { $('li').click(function() { $('li.list-group-item.active').removeClass(\"active\"); $(this).addClass(\"active\"); }); }); </script></body> </html>", "e": 5470, "s": 4255, "text": null }, { "code": null, "e": 5478, "s": 5470, "text": "Output:" }, { "code": null, "e": 5746, "s": 5478, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 5762, "s": 5746, "text": "JavaScript-Misc" }, { "code": null, "e": 5774, "s": 5762, "text": "jQuery-Misc" }, { "code": null, "e": 5781, "s": 5774, "text": "Picked" }, { "code": null, "e": 5791, "s": 5781, "text": "Bootstrap" }, { "code": null, "e": 5802, "s": 5791, "text": "JavaScript" }, { "code": null, "e": 5809, "s": 5802, "text": "JQuery" }, { "code": null, "e": 5826, "s": 5809, "text": "Web Technologies" }, { "code": null, "e": 5853, "s": 5826, "text": "Web technologies Questions" } ]
Program to count number of distinct Squares and Cubes upto N
24 Mar, 2021 Given a number N, the task is to find No. of perfect Squares and perfect Cubes from 1 to a given integer, N ( Both Inclusive ).Note: Numbers which are both perfect Square and perfect Cube should be counted once.Examples: Input: N = 70 Output: 10 Numbers that are perfect Square or perfect Cube 1, 4, 8, 9, 16, 25, 27, 36, 49, 64Input: N = 25 Output: 6 Numbers that are perfect Square or perfect Cube 1, 4, 8, 9, 16, 25 A Naive approach is to check all numbers from 1 to N, if it is a square or cube.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <iostream>#include <math.h> // For sqrt() and cbrt()using namespace std; // Function to check if the// number is a perfect squarebool isSquare(int num){ int root = sqrt(num); return (root * root) == num;} // Function to check if the// number is a perfect cubebool isCube(int num){ int root = cbrt(num); return (root * root * root) == num;} // Function to count the number// of perfect squares and cubesint countSC(int N){ int count = 0; for (int i = 1; i <= N; i++) { // If a number is perfect square, if (isSquare(i)) count++; // Else if the number is cube or not else if (isCube(i)) count++; } return count;} // Driver codeint main(){ int N = 20; cout<< "Number of squares and cubes is " << countSC(N); return 0;} // Java implementation of// above approachclass GFG{ // Function to check if the// number is a perfect squarestatic boolean isSquare(int num){ int root = (int)Math.sqrt(num); return (root * root) == num;} // Function to check if the// number is a perfect cubestatic boolean isCube(int num){ int root = (int)Math.cbrt(num); return (root * root * root) == num;} // Function to count the number// of perfect squares and cubesstatic int countSC(int N){ int count = 0; for (int i = 1; i <= N; i++) { // If a number is perfect // square, if (isSquare(i)) count++; // Else if the number is // cube or not else if (isCube(i)) count++; } return count;} // Driver codepublic static void main(String[] args){ int N = 20; System.out.println("Number of squares " + "and cubes is " + countSC(N));}} // This code is contributed// by ChitraNayal # Python 3 implementation of# above approach # Function to check if the# number is a perfect squaredef isSquare(num) : root = int(num ** (1 / 2)) return (root * root) == num # Function to check if the# number is a perfect cubedef isCube(num) : root = int(num ** (1 / 3)) return (root * root * root ) == num # Function to count the number# of perfect squares and cubesdef countSC(N) : count = 0 for i in range(1, N + 1) : # If a number is perfect square, if isSquare(i) : count += 1 # Else if the number is cube elif isCube(i) : count += 1 return count # Driver codeif __name__ == "__main__" : N = 20 print("Number of squares and cubes is ", countSC(N)) # This code is contributed by ANKITRAI1 // C# implementation of// above approachusing System; class GFG{ // Function to check if the// number is a perfect squarestatic bool isSquare(int num){ int root = (int)Math.Sqrt(num); return (root * root) == num;} // Function to check if the// number is a perfect cubestatic bool isCube(int num){ int root = (int)Math.Pow(num, (1.0 / 3.0)); return (root * root * root) == num;} // Function to count the number// of perfect squares and cubesstatic int countSC(int N){ int count = 0; for (int i = 1; i <= N; i++) { // If a number is perfect // square, if (isSquare(i)) count++; // Else if the number is // cube or not else if (isCube(i)) count++; } return count;} // Driver codepublic static void Main(){ int N = 20; Console.Write("Number of squares and " + "cubes is " + countSC(N));}} // This code is contributed// by ChitraNayal <?php// PHP implementation of above approach // Function to check if the// number is a perfect squarefunction isSquare($num){ $root = (int)sqrt($num); return ($root * $root) == $num;} // Function to check if the// number is a perfect cubefunction isCube($num){ $root = (int)pow($num, 1 / 3); return ($root * $root * $root) == $num;} // Function to count the number// of perfect squares and cubesfunction countSC($N){ $count = 0; for ($i = 1; $i <= $N; $i++) { // If a number is // perfect square, if (isSquare($i)) $count++; // Else if the number // is cube or not else if (isCube($i)) $count++; } return $count;} // Driver code$N = 20; echo "Number of squares and " . "cubes is " . countSC($N); // This code is contributed// by ChitraNayal?> <script> // Javascript implementation of above approach // Function to check if the // number is a perfect square function isSquare(num) { let root = parseInt(Math.sqrt(num), 10); return (root * root) == num; } // Function to check if the // number is a perfect cube function isCube(num) { let root = parseInt(Math.cbrt(num), 10); return (root * root * root) == num; } // Function to count the number // of perfect squares and cubes function countSC(N) { let count = 0; for (let i = 1; i <= N; i++) { // If a number is perfect square, if (isSquare(i)) count++; // Else if the number is cube or not else if (isCube(i)) count++; } return count; } let N = 20; document.write("Number of squares and cubes is " + countSC(N)); </script> Number of squares and cubes is 5 Efficient Approach: Number of squares from 1 to N is floor(sqrt(N)).Number of cubes from 1 to N is floor(cbrt(N)).Eliminate the numbers which are both square and cube ( like 1, 64.... ) by subtracting floor(sqrt(cbrt(N))) from it. Number of squares from 1 to N is floor(sqrt(N)). Number of cubes from 1 to N is floor(cbrt(N)). Eliminate the numbers which are both square and cube ( like 1, 64.... ) by subtracting floor(sqrt(cbrt(N))) from it. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <iostream>#include <math.h> // For sqrt() and cbrt()using namespace std; // Function to count the number// of perfect squares and cubesint countSC(int N){ int res = (int)sqrt(N) + (int)cbrt(N) - (int)(sqrt(cbrt(N))); return res;} // Driver codeint main(){ int N = 20; cout << "Number of squares and cubes is " << countSC(N); return 0;} // Java implementation of// above approachclass GFG{ // Function to count the number// of perfect squares and cubesstatic int countSC(int N){ int res = (int)Math.sqrt(N) + (int)Math.cbrt(N) - (int)(Math.sqrt(Math.cbrt(N))); return res;} // Driver codepublic static void main(String[] args){ int N = 20; System.out.println("Number of squares " + "and cubes is " + countSC(N));}} // This code is contributed// by ChitraNayal # Python implementation of# above approachimport math # for sqrt() # Function to count the number# of perfect squares and cubesdef countSC(N): res = (int(math.sqrt(N)) + int(N ** (1 / 3)) - int(math.sqrt(N ** (1 / 3)))) return res # Driver codeN = 20print("Number of squares and cubes is", countSC(N)) # This code is contributed# by vaibhav29498 //C# implementation of// above approachusing System;public class GFG { // Function to count the number // of perfect squares and cubes static int countSC(int N) { int res = (int)(Math.Sqrt(N) + Math.Ceiling(Math.Pow(N, (double)1 / 3)) - (Math.Sqrt(Math.Ceiling(Math.Pow(N, (double)1 / 3))))); return res; } // Driver code public static void Main() { int N = 20; Console.Write("Number of squares " + "and cubes is " + countSC(N)); }} /*This code is contributed by 29AjayKumar*/ <?php// PHP implementation of above approach // Function to count the number// of perfect squares and cubesfunction countSC($N){ $res = sqrt($N) + pow($N, 1 / 3) - (sqrt(pow($N, 1 / 3))); return floor($res);} // Driver code$N = 20; echo "Number of squares and cubes is " , countSC($N); // This code is contributed// by Shashank?> <script> // Javascript implementation of above approach // Function to count the number // of perfect squares and cubes function countSC(N) { let res = parseInt(Math.sqrt(N), 10) + parseInt(Math.cbrt(N), 10) - parseInt(Math.sqrt(parseInt(Math.cbrt(N), 10)), 10); return res; } let N = 20; document.write("Number of squares and cubes is " + countSC(N)); </script> Number of squares and cubes is 5 ankthon vaibhav29498 ukasp Shashank12 29AjayKumar Akanksha_Rai divyeshrabadiya07 divyesh072019 CPP-Functions cpp-math maths-cube maths-perfect-square Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Mar, 2021" }, { "code": null, "e": 275, "s": 52, "text": "Given a number N, the task is to find No. of perfect Squares and perfect Cubes from 1 to a given integer, N ( Both Inclusive ).Note: Numbers which are both perfect Square and perfect Cube should be counted once.Examples: " }, { "code": null, "e": 475, "s": 275, "text": "Input: N = 70 Output: 10 Numbers that are perfect Square or perfect Cube 1, 4, 8, 9, 16, 25, 27, 36, 49, 64Input: N = 25 Output: 6 Numbers that are perfect Square or perfect Cube 1, 4, 8, 9, 16, 25 " }, { "code": null, "e": 606, "s": 477, "text": "A Naive approach is to check all numbers from 1 to N, if it is a square or cube.Below is the implementation of above approach: " }, { "code": null, "e": 610, "s": 606, "text": "C++" }, { "code": null, "e": 615, "s": 610, "text": "Java" }, { "code": null, "e": 623, "s": 615, "text": "Python3" }, { "code": null, "e": 626, "s": 623, "text": "C#" }, { "code": null, "e": 630, "s": 626, "text": "PHP" }, { "code": null, "e": 641, "s": 630, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <iostream>#include <math.h> // For sqrt() and cbrt()using namespace std; // Function to check if the// number is a perfect squarebool isSquare(int num){ int root = sqrt(num); return (root * root) == num;} // Function to check if the// number is a perfect cubebool isCube(int num){ int root = cbrt(num); return (root * root * root) == num;} // Function to count the number// of perfect squares and cubesint countSC(int N){ int count = 0; for (int i = 1; i <= N; i++) { // If a number is perfect square, if (isSquare(i)) count++; // Else if the number is cube or not else if (isCube(i)) count++; } return count;} // Driver codeint main(){ int N = 20; cout<< \"Number of squares and cubes is \" << countSC(N); return 0;}", "e": 1492, "s": 641, "text": null }, { "code": "// Java implementation of// above approachclass GFG{ // Function to check if the// number is a perfect squarestatic boolean isSquare(int num){ int root = (int)Math.sqrt(num); return (root * root) == num;} // Function to check if the// number is a perfect cubestatic boolean isCube(int num){ int root = (int)Math.cbrt(num); return (root * root * root) == num;} // Function to count the number// of perfect squares and cubesstatic int countSC(int N){ int count = 0; for (int i = 1; i <= N; i++) { // If a number is perfect // square, if (isSquare(i)) count++; // Else if the number is // cube or not else if (isCube(i)) count++; } return count;} // Driver codepublic static void main(String[] args){ int N = 20; System.out.println(\"Number of squares \" + \"and cubes is \" + countSC(N));}} // This code is contributed// by ChitraNayal", "e": 2493, "s": 1492, "text": null }, { "code": "# Python 3 implementation of# above approach # Function to check if the# number is a perfect squaredef isSquare(num) : root = int(num ** (1 / 2)) return (root * root) == num # Function to check if the# number is a perfect cubedef isCube(num) : root = int(num ** (1 / 3)) return (root * root * root ) == num # Function to count the number# of perfect squares and cubesdef countSC(N) : count = 0 for i in range(1, N + 1) : # If a number is perfect square, if isSquare(i) : count += 1 # Else if the number is cube elif isCube(i) : count += 1 return count # Driver codeif __name__ == \"__main__\" : N = 20 print(\"Number of squares and cubes is \", countSC(N)) # This code is contributed by ANKITRAI1", "e": 3337, "s": 2493, "text": null }, { "code": "// C# implementation of// above approachusing System; class GFG{ // Function to check if the// number is a perfect squarestatic bool isSquare(int num){ int root = (int)Math.Sqrt(num); return (root * root) == num;} // Function to check if the// number is a perfect cubestatic bool isCube(int num){ int root = (int)Math.Pow(num, (1.0 / 3.0)); return (root * root * root) == num;} // Function to count the number// of perfect squares and cubesstatic int countSC(int N){ int count = 0; for (int i = 1; i <= N; i++) { // If a number is perfect // square, if (isSquare(i)) count++; // Else if the number is // cube or not else if (isCube(i)) count++; } return count;} // Driver codepublic static void Main(){ int N = 20; Console.Write(\"Number of squares and \" + \"cubes is \" + countSC(N));}} // This code is contributed// by ChitraNayal", "e": 4304, "s": 3337, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to check if the// number is a perfect squarefunction isSquare($num){ $root = (int)sqrt($num); return ($root * $root) == $num;} // Function to check if the// number is a perfect cubefunction isCube($num){ $root = (int)pow($num, 1 / 3); return ($root * $root * $root) == $num;} // Function to count the number// of perfect squares and cubesfunction countSC($N){ $count = 0; for ($i = 1; $i <= $N; $i++) { // If a number is // perfect square, if (isSquare($i)) $count++; // Else if the number // is cube or not else if (isCube($i)) $count++; } return $count;} // Driver code$N = 20; echo \"Number of squares and \" . \"cubes is \" . countSC($N); // This code is contributed// by ChitraNayal?>", "e": 5156, "s": 4304, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to check if the // number is a perfect square function isSquare(num) { let root = parseInt(Math.sqrt(num), 10); return (root * root) == num; } // Function to check if the // number is a perfect cube function isCube(num) { let root = parseInt(Math.cbrt(num), 10); return (root * root * root) == num; } // Function to count the number // of perfect squares and cubes function countSC(N) { let count = 0; for (let i = 1; i <= N; i++) { // If a number is perfect square, if (isSquare(i)) count++; // Else if the number is cube or not else if (isCube(i)) count++; } return count; } let N = 20; document.write(\"Number of squares and cubes is \" + countSC(N)); </script>", "e": 6090, "s": 5156, "text": null }, { "code": null, "e": 6123, "s": 6090, "text": "Number of squares and cubes is 5" }, { "code": null, "e": 6147, "s": 6125, "text": "Efficient Approach: " }, { "code": null, "e": 6358, "s": 6147, "text": "Number of squares from 1 to N is floor(sqrt(N)).Number of cubes from 1 to N is floor(cbrt(N)).Eliminate the numbers which are both square and cube ( like 1, 64.... ) by subtracting floor(sqrt(cbrt(N))) from it." }, { "code": null, "e": 6407, "s": 6358, "text": "Number of squares from 1 to N is floor(sqrt(N))." }, { "code": null, "e": 6454, "s": 6407, "text": "Number of cubes from 1 to N is floor(cbrt(N))." }, { "code": null, "e": 6571, "s": 6454, "text": "Eliminate the numbers which are both square and cube ( like 1, 64.... ) by subtracting floor(sqrt(cbrt(N))) from it." }, { "code": null, "e": 6624, "s": 6571, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 6628, "s": 6624, "text": "C++" }, { "code": null, "e": 6633, "s": 6628, "text": "Java" }, { "code": null, "e": 6641, "s": 6633, "text": "Python3" }, { "code": null, "e": 6644, "s": 6641, "text": "C#" }, { "code": null, "e": 6648, "s": 6644, "text": "PHP" }, { "code": null, "e": 6659, "s": 6648, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <iostream>#include <math.h> // For sqrt() and cbrt()using namespace std; // Function to count the number// of perfect squares and cubesint countSC(int N){ int res = (int)sqrt(N) + (int)cbrt(N) - (int)(sqrt(cbrt(N))); return res;} // Driver codeint main(){ int N = 20; cout << \"Number of squares and cubes is \" << countSC(N); return 0;}", "e": 7073, "s": 6659, "text": null }, { "code": "// Java implementation of// above approachclass GFG{ // Function to count the number// of perfect squares and cubesstatic int countSC(int N){ int res = (int)Math.sqrt(N) + (int)Math.cbrt(N) - (int)(Math.sqrt(Math.cbrt(N))); return res;} // Driver codepublic static void main(String[] args){ int N = 20; System.out.println(\"Number of squares \" + \"and cubes is \" + countSC(N));}} // This code is contributed// by ChitraNayal", "e": 7595, "s": 7073, "text": null }, { "code": "# Python implementation of# above approachimport math # for sqrt() # Function to count the number# of perfect squares and cubesdef countSC(N): res = (int(math.sqrt(N)) + int(N ** (1 / 3)) - int(math.sqrt(N ** (1 / 3)))) return res # Driver codeN = 20print(\"Number of squares and cubes is\", countSC(N)) # This code is contributed# by vaibhav29498", "e": 7995, "s": 7595, "text": null }, { "code": "//C# implementation of// above approachusing System;public class GFG { // Function to count the number // of perfect squares and cubes static int countSC(int N) { int res = (int)(Math.Sqrt(N) + Math.Ceiling(Math.Pow(N, (double)1 / 3)) - (Math.Sqrt(Math.Ceiling(Math.Pow(N, (double)1 / 3))))); return res; } // Driver code public static void Main() { int N = 20; Console.Write(\"Number of squares \" + \"and cubes is \" + countSC(N)); }} /*This code is contributed by 29AjayKumar*/", "e": 8569, "s": 7995, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to count the number// of perfect squares and cubesfunction countSC($N){ $res = sqrt($N) + pow($N, 1 / 3) - (sqrt(pow($N, 1 / 3))); return floor($res);} // Driver code$N = 20; echo \"Number of squares and cubes is \" , countSC($N); // This code is contributed// by Shashank?>", "e": 8948, "s": 8569, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to count the number // of perfect squares and cubes function countSC(N) { let res = parseInt(Math.sqrt(N), 10) + parseInt(Math.cbrt(N), 10) - parseInt(Math.sqrt(parseInt(Math.cbrt(N), 10)), 10); return res; } let N = 20; document.write(\"Number of squares and cubes is \" + countSC(N)); </script>", "e": 9363, "s": 8948, "text": null }, { "code": null, "e": 9396, "s": 9363, "text": "Number of squares and cubes is 5" }, { "code": null, "e": 9406, "s": 9398, "text": "ankthon" }, { "code": null, "e": 9419, "s": 9406, "text": "vaibhav29498" }, { "code": null, "e": 9425, "s": 9419, "text": "ukasp" }, { "code": null, "e": 9436, "s": 9425, "text": "Shashank12" }, { "code": null, "e": 9448, "s": 9436, "text": "29AjayKumar" }, { "code": null, "e": 9461, "s": 9448, "text": "Akanksha_Rai" }, { "code": null, "e": 9479, "s": 9461, "text": "divyeshrabadiya07" }, { "code": null, "e": 9493, "s": 9479, "text": "divyesh072019" }, { "code": null, "e": 9507, "s": 9493, "text": "CPP-Functions" }, { "code": null, "e": 9516, "s": 9507, "text": "cpp-math" }, { "code": null, "e": 9527, "s": 9516, "text": "maths-cube" }, { "code": null, "e": 9548, "s": 9527, "text": "maths-perfect-square" }, { "code": null, "e": 9561, "s": 9548, "text": "Mathematical" }, { "code": null, "e": 9580, "s": 9561, "text": "School Programming" }, { "code": null, "e": 9593, "s": 9580, "text": "Mathematical" } ]
Check if a point lies inside a rectangle | Set-2
23 May, 2022 Given coordinates of bottom-left and top-right corners of a rectangle. Check if a point (x, y) lies inside this rectangle or not. Examples: Input: bottom-left: (0, 0), top-right: (10, 8), point: (1, 5) Output: Yes Input: bottom-left: (-1, 4), top-right:(2, 3), point:(0, 4) Output: No This problem is already discussed in a previous post. In this post we have discussed a new approach. Approach: The above problem can be solved by observation. A point lies inside or not the rectangle if and only if it’s x-coordinate lies between the x-coordinate of the given bottom-right and top-left coordinates of the rectangle and y-coordinate lies between the y-coordinate of the given bottom-right and top-left coordinates. Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // CPP program to Check if a// point lies on or inside a rectangle | Set-2#include <bits/stdc++.h>using namespace std; // function to find if given point// lies inside a given rectangle or not.bool FindPoint(int x1, int y1, int x2, int y2, int x, int y){ if (x > x1 and x < x2 and y > y1 and y < y2) return true; return false;} // Driver codeint main(){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) cout << "Yes"; else cout << "No"; return 0;} // C program to Check if a// point lies on or inside a rectangle | Set-2#include <stdio.h>#include <stdbool.h> // function to find if given point// lies inside a given rectangle or not.bool FindPoint(int x1, int y1, int x2, int y2, int x, int y){ if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver codeint main(){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) printf("Yes"); else printf("No"); return 0;} // This code is contributed by kothavvsaakash. // Java program to Check if// a point lies on or inside// a rectangle | Set-2class GFG{ // function to find if given point// lies inside a given rectangle or not.static boolean FindPoint(int x1, int y1, int x2, int y2, int x, int y){if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver codepublic static void main(String[] args){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed// by ChitraNayal # Python3 program to Check# if a point lies on or# inside a rectangle | Set-2 # function to find if# given point lies inside# a given rectangle or not.def FindPoint(x1, y1, x2, y2, x, y) : if (x > x1 and x < x2 and y > y1 and y < y2) : return True else : return False # Driver codeif __name__ == "__main__" : # bottom-left and top-right # corners of rectangle. # use multiple assignment x1 , y1 , x2 , y2 = 0, 0, 10, 8 # given point x, y = 1, 5 # function call if FindPoint(x1, y1, x2, y2, x, y) : print("Yes") else : print("No") # This code is contributed# by Ankit Rai // C# program to Check if a// point lies on or inside// a rectangle | Set-2using System; class GFG{ // function to find if given// point lies inside a given// rectangle or not.static bool FindPoint(int x1, int y1, int x2, int y2, int x, int y){if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver codepublic static void Main(){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed// by ChitraNayal <?php// PHP program to Check if// a point lies on or inside// a rectangle | Set-2 // function to find if given// point lies inside a given// rectangle or not.function FindPoint($x1, $y1, $x2, $y2, $x, $y){ if ($x > $x1 and $x < $x2 and $y > $y1 and $y < $y2) return true; return false;} // Driver code // bottom-left and top-right// corners of rectangle$x1 = 0; $y1 = 0;$x2 = 10; $y2 = 8; // given point$x = 1; $y = 5; // function callif (FindPoint($x1, $y1, $x2, $y2, $x, $y)) echo "Yes";else echo "No"; // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to Check if a// point lies on or inside a rectangle | Set-2 // function to find if given point// lies inside a given rectangle or not.function FindPoint(x1, y1, x2, y2, x, y){ if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver code // bottom-left and top-right // corners of rectangle let x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point let x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) document.write("Yes"); else document.write("No"); // This code is contributed by Mayank Tyagi </script> Yes Time Complexity: O(1) Auxiliary Space: O(1) ankthon Akanksha_Rai ukasp mayanktyagi1709 sumankumar20 sweetyty rohitkumarsinghcna kothavvsaakash Constructive Algorithms square-rectangle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Optimum location of point to minimize total distance Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Program for Point of Intersection of Two Lines Window to Viewport Transformation in Computer Graphics with Implementation Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2022" }, { "code": null, "e": 158, "s": 28, "text": "Given coordinates of bottom-left and top-right corners of a rectangle. Check if a point (x, y) lies inside this rectangle or not." }, { "code": null, "e": 169, "s": 158, "text": "Examples: " }, { "code": null, "e": 243, "s": 169, "text": "Input: bottom-left: (0, 0), top-right: (10, 8), point: (1, 5) Output: Yes" }, { "code": null, "e": 314, "s": 243, "text": "Input: bottom-left: (-1, 4), top-right:(2, 3), point:(0, 4) Output: No" }, { "code": null, "e": 415, "s": 314, "text": "This problem is already discussed in a previous post. In this post we have discussed a new approach." }, { "code": null, "e": 744, "s": 415, "text": "Approach: The above problem can be solved by observation. A point lies inside or not the rectangle if and only if it’s x-coordinate lies between the x-coordinate of the given bottom-right and top-left coordinates of the rectangle and y-coordinate lies between the y-coordinate of the given bottom-right and top-left coordinates." }, { "code": null, "e": 797, "s": 744, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 801, "s": 797, "text": "C++" }, { "code": null, "e": 803, "s": 801, "text": "C" }, { "code": null, "e": 808, "s": 803, "text": "Java" }, { "code": null, "e": 816, "s": 808, "text": "Python3" }, { "code": null, "e": 819, "s": 816, "text": "C#" }, { "code": null, "e": 823, "s": 819, "text": "PHP" }, { "code": null, "e": 834, "s": 823, "text": "Javascript" }, { "code": "// CPP program to Check if a// point lies on or inside a rectangle | Set-2#include <bits/stdc++.h>using namespace std; // function to find if given point// lies inside a given rectangle or not.bool FindPoint(int x1, int y1, int x2, int y2, int x, int y){ if (x > x1 and x < x2 and y > y1 and y < y2) return true; return false;} // Driver codeint main(){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 1482, "s": 834, "text": null }, { "code": "// C program to Check if a// point lies on or inside a rectangle | Set-2#include <stdio.h>#include <stdbool.h> // function to find if given point// lies inside a given rectangle or not.bool FindPoint(int x1, int y1, int x2, int y2, int x, int y){ if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver codeint main(){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) printf(\"Yes\"); else printf(\"No\"); return 0;} // This code is contributed by kothavvsaakash.", "e": 2152, "s": 1482, "text": null }, { "code": "// Java program to Check if// a point lies on or inside// a rectangle | Set-2class GFG{ // function to find if given point// lies inside a given rectangle or not.static boolean FindPoint(int x1, int y1, int x2, int y2, int x, int y){if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver codepublic static void main(String[] args){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed// by ChitraNayal", "e": 2873, "s": 2152, "text": null }, { "code": "# Python3 program to Check# if a point lies on or# inside a rectangle | Set-2 # function to find if# given point lies inside# a given rectangle or not.def FindPoint(x1, y1, x2, y2, x, y) : if (x > x1 and x < x2 and y > y1 and y < y2) : return True else : return False # Driver codeif __name__ == \"__main__\" : # bottom-left and top-right # corners of rectangle. # use multiple assignment x1 , y1 , x2 , y2 = 0, 0, 10, 8 # given point x, y = 1, 5 # function call if FindPoint(x1, y1, x2, y2, x, y) : print(\"Yes\") else : print(\"No\") # This code is contributed# by Ankit Rai", "e": 3544, "s": 2873, "text": null }, { "code": "// C# program to Check if a// point lies on or inside// a rectangle | Set-2using System; class GFG{ // function to find if given// point lies inside a given// rectangle or not.static bool FindPoint(int x1, int y1, int x2, int y2, int x, int y){if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver codepublic static void Main(){ // bottom-left and top-right // corners of rectangle int x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point int x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed// by ChitraNayal", "e": 4250, "s": 3544, "text": null }, { "code": "<?php// PHP program to Check if// a point lies on or inside// a rectangle | Set-2 // function to find if given// point lies inside a given// rectangle or not.function FindPoint($x1, $y1, $x2, $y2, $x, $y){ if ($x > $x1 and $x < $x2 and $y > $y1 and $y < $y2) return true; return false;} // Driver code // bottom-left and top-right// corners of rectangle$x1 = 0; $y1 = 0;$x2 = 10; $y2 = 8; // given point$x = 1; $y = 5; // function callif (FindPoint($x1, $y1, $x2, $y2, $x, $y)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 4872, "s": 4250, "text": null }, { "code": "<script> // Javascript program to Check if a// point lies on or inside a rectangle | Set-2 // function to find if given point// lies inside a given rectangle or not.function FindPoint(x1, y1, x2, y2, x, y){ if (x > x1 && x < x2 && y > y1 && y < y2) return true; return false;} // Driver code // bottom-left and top-right // corners of rectangle let x1 = 0, y1 = 0, x2 = 10, y2 = 8; // given point let x = 1, y = 5; // function call if (FindPoint(x1, y1, x2, y2, x, y)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by Mayank Tyagi </script>", "e": 5512, "s": 4872, "text": null }, { "code": null, "e": 5516, "s": 5512, "text": "Yes" }, { "code": null, "e": 5538, "s": 5516, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5560, "s": 5538, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5568, "s": 5560, "text": "ankthon" }, { "code": null, "e": 5581, "s": 5568, "text": "Akanksha_Rai" }, { "code": null, "e": 5587, "s": 5581, "text": "ukasp" }, { "code": null, "e": 5603, "s": 5587, "text": "mayanktyagi1709" }, { "code": null, "e": 5616, "s": 5603, "text": "sumankumar20" }, { "code": null, "e": 5625, "s": 5616, "text": "sweetyty" }, { "code": null, "e": 5644, "s": 5625, "text": "rohitkumarsinghcna" }, { "code": null, "e": 5659, "s": 5644, "text": "kothavvsaakash" }, { "code": null, "e": 5683, "s": 5659, "text": "Constructive Algorithms" }, { "code": null, "e": 5700, "s": 5683, "text": "square-rectangle" }, { "code": null, "e": 5710, "s": 5700, "text": "Geometric" }, { "code": null, "e": 5729, "s": 5710, "text": "School Programming" }, { "code": null, "e": 5739, "s": 5729, "text": "Geometric" }, { "code": null, "e": 5837, "s": 5739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5886, "s": 5837, "text": "Program for distance between two points on earth" }, { "code": null, "e": 5939, "s": 5886, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 5990, "s": 5939, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 6037, "s": 5990, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 6112, "s": 6037, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 6130, "s": 6112, "text": "Python Dictionary" }, { "code": null, "e": 6155, "s": 6130, "text": "Reverse a string in Java" }, { "code": null, "e": 6171, "s": 6155, "text": "Arrays in C/C++" }, { "code": null, "e": 6194, "s": 6171, "text": "Introduction To PYTHON" } ]
Derivatives of Implicit Functions – Continuity and Differentiability | Class 12 Maths
01 Dec, 2020 Implicit functions are functions where a specific variable cannot be expressed as a function of the other variable. A function that depends on more than one variable. Implicit Differentiation helps us compute the derivative of y with respect to x without solving the given equation for y, this can be achieved by using the chain rule which helps us express y as a function of x. Implicit Differentiation can also be used to calculate the slope of a curve, as we cannot follow the direct procedure of differentiating the function y = f(x) and putting the value of the x-coordinate of the point in dy/dx to get the slope. Instead, we will have to follow the process of implicit differentiation and solve for dy/dx. The method of implicit differentiation used here is a general technique to find the derivatives of unknown quantities. Example x2y2 + xy2+ exy = abc = constant The function above is an implicit function, we cannot express x in terms of y or y in terms of x. Since the functions can not be expressed in terms of one specific variable, we have to follow a different method to find the derivative of the implicit function : While computing the derivative of the Implicit function, our aim is to solve for dy/dx or any higher-order derivatives depending on the function. To solve dy/dx in terms of x and y, we have to follow certain steps: Given an implicit function with the dependent variable y and the independent variable x (or the other way around). Differentiate the entire equation with respect to the independent variable (it could be x or y). After differentiating, we need to apply the chain rule of differentiation. Solve the resultant equation for dy/dx (or dx/dy likewise) or differentiate again if the higher-order derivatives are needed. “Some function of y and x equals to something else”. Knowing x does not help us compute y directly. For instance, x2 + y2 = r2 (Implicit function) Differentiate with respect to x:d(x2) /dx + d(y2)/ dx = d(r2) / dx Solve each term: Using Power Rule: d(x2) / dx = 2x Using Chain Rule : d(y2)/ dx = 2y dydx r2 is a constant, so its derivative is 0: d(r2)/ dx = 0 Which gives us: 2x + 2y dy/dx = 0 Collect all the dy/dx on one side y dy/dx = −x Solve for dy/dx: dy/dx = −xy Example 1. Find the expression for the first derivative of the function y(x) given implicitly by the equation: x2y3 – 4y + 3x3 = 2. Solution: Step 1: Differentiate the given equation or function with respect to x. x2y3 – 4y + 3x3 = 2. d(x2y3 – 4y + 3x3) / dx = d(2) / dx Step 2: The right-hand side’s derivative will simply be 0 since it is a constant. The left-hand side after differentiation : 2xy3 +3x2y2 * dy/dx – 4 * dy/dx + 9x2 = 0. Step 3: Collect the terms involving dy/dx on one side and take the remaining terms on the other side to get: dy/dx * (3x2y2 – 4) = -9x2 – 2xy3 dy/dx = – ( 9x2 + 2xy3) / (3x2y2 – 4 ) This is the expression for the first derivative at any point on the curve. This expression also helps us compute the slope of a tangent drawn at point (x, y) to the curve. Example 2. Find the first derivative of y, given implicitly as: y – tan-1y = x. Solution: d(y – tan-1y) /dx = d(x)/ dx. dy/dx – (1/(1 + y2) * dy/dx = 1 dy/dx =1/(1 / (1–1/ (1 + y2))) dy/dx = 1/y2 + 1 Example 3. Find dy/dx if x2y3 − xy = 10. Solution: 2xy3 + x2. 3y2 . dy/dx – y – x . dy/dx = 0 (3x2y2 – x ) . dy/dx = y – 2xy3 dy/dx = (y – 2xy3) / (3x2y2 – x) Example 4. Find dy/dx if y = sinx + cosy Solution: y – cosy = sinx dy/dx + siny. dy/dx = cosx dy/dx = cosx / (1 + siny) Example 5. Find the slope of the tangent line to the curve x2+ y2= 25 at the point (3,−4). Solution: Note that the slope of the tangent line to a curve is the derivative, differentiate implicitly with respect to x, which yields, 2x + 2y. dy/dx = 0 dy/dx = -x/y Hence, at (3,−4), y′ = −3/−4 = 3/4, and the tangent line has slope 3/4 at the point (3,−4). Maths Class 12 Mathematical School Learning School Mathematics Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Dec, 2020" }, { "code": null, "e": 410, "s": 28, "text": "Implicit functions are functions where a specific variable cannot be expressed as a function of the other variable. A function that depends on more than one variable. Implicit Differentiation helps us compute the derivative of y with respect to x without solving the given equation for y, this can be achieved by using the chain rule which helps us express y as a function of x. " }, { "code": null, "e": 745, "s": 410, "text": " Implicit Differentiation can also be used to calculate the slope of a curve, as we cannot follow the direct procedure of differentiating the function y = f(x) and putting the value of the x-coordinate of the point in dy/dx to get the slope. Instead, we will have to follow the process of implicit differentiation and solve for dy/dx." }, { "code": null, "e": 864, "s": 745, "text": "The method of implicit differentiation used here is a general technique to find the derivatives of unknown quantities." }, { "code": null, "e": 872, "s": 864, "text": "Example" }, { "code": null, "e": 905, "s": 872, "text": "x2y2 + xy2+ exy = abc = constant" }, { "code": null, "e": 1003, "s": 905, "text": "The function above is an implicit function, we cannot express x in terms of y or y in terms of x." }, { "code": null, "e": 1166, "s": 1003, "text": "Since the functions can not be expressed in terms of one specific variable, we have to follow a different method to find the derivative of the implicit function :" }, { "code": null, "e": 1381, "s": 1166, "text": "While computing the derivative of the Implicit function, our aim is to solve for dy/dx or any higher-order derivatives depending on the function. To solve dy/dx in terms of x and y, we have to follow certain steps:" }, { "code": null, "e": 1496, "s": 1381, "text": "Given an implicit function with the dependent variable y and the independent variable x (or the other way around)." }, { "code": null, "e": 1593, "s": 1496, "text": "Differentiate the entire equation with respect to the independent variable (it could be x or y)." }, { "code": null, "e": 1668, "s": 1593, "text": "After differentiating, we need to apply the chain rule of differentiation." }, { "code": null, "e": 1794, "s": 1668, "text": "Solve the resultant equation for dy/dx (or dx/dy likewise) or differentiate again if the higher-order derivatives are needed." }, { "code": null, "e": 1910, "s": 1794, "text": " “Some function of y and x equals to something else”. Knowing x does not help us compute y directly. For instance, " }, { "code": null, "e": 1944, "s": 1910, "text": "x2 + y2 = r2 (Implicit function) " }, { "code": null, "e": 2012, "s": 1944, "text": "Differentiate with respect to x:d(x2) /dx + d(y2)/ dx = d(r2) / dx " }, { "code": null, "e": 2029, "s": 2012, "text": "Solve each term:" }, { "code": null, "e": 2064, "s": 2029, "text": "Using Power Rule: d(x2) / dx = 2x" }, { "code": null, "e": 2104, "s": 2064, "text": "Using Chain Rule : d(y2)/ dx = 2y dydx" }, { "code": null, "e": 2162, "s": 2104, "text": "r2 is a constant, so its derivative is 0: d(r2)/ dx = 0" }, { "code": null, "e": 2178, "s": 2162, "text": "Which gives us:" }, { "code": null, "e": 2196, "s": 2178, "text": "2x + 2y dy/dx = 0" }, { "code": null, "e": 2231, "s": 2196, "text": "Collect all the dy/dx on one side" }, { "code": null, "e": 2244, "s": 2231, "text": "y dy/dx = −x" }, { "code": null, "e": 2261, "s": 2244, "text": "Solve for dy/dx:" }, { "code": null, "e": 2278, "s": 2261, "text": "dy/dx = −xy " }, { "code": null, "e": 2410, "s": 2278, "text": "Example 1. Find the expression for the first derivative of the function y(x) given implicitly by the equation: x2y3 – 4y + 3x3 = 2." }, { "code": null, "e": 2420, "s": 2410, "text": "Solution:" }, { "code": null, "e": 2492, "s": 2420, "text": "Step 1: Differentiate the given equation or function with respect to x." }, { "code": null, "e": 2569, "s": 2492, "text": " x2y3 – 4y + 3x3 = 2. d(x2y3 – 4y + 3x3) / dx = d(2) / dx " }, { "code": null, "e": 2651, "s": 2569, "text": "Step 2: The right-hand side’s derivative will simply be 0 since it is a constant." }, { "code": null, "e": 2694, "s": 2651, "text": "The left-hand side after differentiation :" }, { "code": null, "e": 2737, "s": 2694, "text": "2xy3 +3x2y2 * dy/dx – 4 * dy/dx + 9x2 = 0." }, { "code": null, "e": 2846, "s": 2737, "text": "Step 3: Collect the terms involving dy/dx on one side and take the remaining terms on the other side to get:" }, { "code": null, "e": 2880, "s": 2846, "text": "dy/dx * (3x2y2 – 4) = -9x2 – 2xy3" }, { "code": null, "e": 2920, "s": 2880, "text": "dy/dx = – ( 9x2 + 2xy3) / (3x2y2 – 4 )" }, { "code": null, "e": 3092, "s": 2920, "text": "This is the expression for the first derivative at any point on the curve. This expression also helps us compute the slope of a tangent drawn at point (x, y) to the curve." }, { "code": null, "e": 3172, "s": 3092, "text": "Example 2. Find the first derivative of y, given implicitly as: y – tan-1y = x." }, { "code": null, "e": 3182, "s": 3172, "text": "Solution:" }, { "code": null, "e": 3212, "s": 3182, "text": "d(y – tan-1y) /dx = d(x)/ dx." }, { "code": null, "e": 3244, "s": 3212, "text": "dy/dx – (1/(1 + y2) * dy/dx = 1" }, { "code": null, "e": 3275, "s": 3244, "text": "dy/dx =1/(1 / (1–1/ (1 + y2)))" }, { "code": null, "e": 3292, "s": 3275, "text": "dy/dx = 1/y2 + 1" }, { "code": null, "e": 3333, "s": 3292, "text": "Example 3. Find dy/dx if x2y3 − xy = 10." }, { "code": null, "e": 3343, "s": 3333, "text": "Solution:" }, { "code": null, "e": 3386, "s": 3343, "text": "2xy3 + x2. 3y2 . dy/dx – y – x . dy/dx = 0" }, { "code": null, "e": 3418, "s": 3386, "text": "(3x2y2 – x ) . dy/dx = y – 2xy3" }, { "code": null, "e": 3452, "s": 3418, "text": "dy/dx = (y – 2xy3) / (3x2y2 – x) " }, { "code": null, "e": 3494, "s": 3452, "text": "Example 4. Find dy/dx if y = sinx + cosy " }, { "code": null, "e": 3504, "s": 3494, "text": "Solution:" }, { "code": null, "e": 3520, "s": 3504, "text": "y – cosy = sinx" }, { "code": null, "e": 3547, "s": 3520, "text": "dy/dx + siny. dy/dx = cosx" }, { "code": null, "e": 3573, "s": 3547, "text": "dy/dx = cosx / (1 + siny)" }, { "code": null, "e": 3664, "s": 3573, "text": "Example 5. Find the slope of the tangent line to the curve x2+ y2= 25 at the point (3,−4)." }, { "code": null, "e": 3674, "s": 3664, "text": "Solution:" }, { "code": null, "e": 3802, "s": 3674, "text": "Note that the slope of the tangent line to a curve is the derivative, differentiate implicitly with respect to x, which yields," }, { "code": null, "e": 3821, "s": 3802, "text": "2x + 2y. dy/dx = 0" }, { "code": null, "e": 3834, "s": 3821, "text": "dy/dx = -x/y" }, { "code": null, "e": 3926, "s": 3834, "text": "Hence, at (3,−4), y′ = −3/−4 = 3/4, and the tangent line has slope 3/4 at the point (3,−4)." }, { "code": null, "e": 3932, "s": 3926, "text": "Maths" }, { "code": null, "e": 3941, "s": 3932, "text": "Class 12" }, { "code": null, "e": 3954, "s": 3941, "text": "Mathematical" }, { "code": null, "e": 3970, "s": 3954, "text": "School Learning" }, { "code": null, "e": 3989, "s": 3970, "text": "School Mathematics" }, { "code": null, "e": 4002, "s": 3989, "text": "Mathematical" } ]
ZS Associates Interview Experience for DAA
17 Nov, 2020 I applied through a referral I got from a friend who had been working at ZS for more than two years. Using his referral, I got a quick reply from ZS Associates with a test link and was a given a period of time to solve it. Round 1: This was mostly based on aptitude questions, hosted on Talview. Though I am generally very good at aptitude questions, the timings of the rounds made it extra tricky and I believe that I missed some questions. While submitting, I had an issue with my internet, so Talview had a call centre I could call. My assessment was submitted successfully. So in the case, it happens to you, keeps their number handy. Round 2: There was a short telephonic round that was conducted two months later. I was notified about one week before regarding the same by my recruiter. My interview was conducted by her and lasted about 15 minutes. She asked a question to talk about myself. Then she followed up with two guesstimate-based questions: determine the number of people living in Delhi wearing a red item at that time (ie a shirt, dress, jewellery, pants). This question confused me for a while. She gave me a minute to think as I gave an answer that was not so well-thought-out. For anyone new to guesstimates, it is crucial to think before you speak. I thought for about two minutes before I gave my answer. My logic was simple, I considered the fact it was a Tuesday (the day the interview was conducted). I split the population of Delhi into key demographics based on age: children, adults, and senior citizens taking a 30-50-20 split. I assumed since it was a working day and adults would most likely be wearing muted colours to attend video meetings (it was during the pandemic after all). I also assumed senior citizens would not be wearing such a colour. That left the children. I assumed children would wear bright colours as they do not have to worry about appearing in meetings. I assumed a set of popular colours: red, blue, green, yellow, white. I assumed the proportion of people wearing each of these colours would be same, 20% each. I also chose to ignore jewellery as this was during the pandemic and these are often worn during social events only which was pretty much nonexistent at the time. I calculated the answer and the interviewer responded with an okay. The next question was the number of red lights (bulbs, tube lights, LED) in Delhi. After some careful thinking, I ignored LED by explaining that during the pandemic, no real festivities were happening. For the question of the tube light, since I knew the area of Delhi to be roughly 1500 square kilometres, I assumed the dimensions of Delhi as 30km x 50km with each road as roughly 500 meters long. I told the interviewer that the red bulbs would be used in traffic lights, so by calculating the number of roads, I could assume there was one per road. I gave her my answer. She followed up with a question regarding whether how many the bulbs would be functional. This part confused me again. I took some time and responded that a majority would be working, so I assumed 80% of the traffic lights were functioning fine and revised my answer accordingly. The interviewer accepted my answer. Round 3: This was the case study round. I was given a large dataset of a pharma company to study. It was of a company that a leading market share of a product in 2015 which was reduced to a much smaller one due to the entrance of a new company with a similarly reliable product at a much more affordable price. There were no strategy-based questions as per the Case Interview Prep book. It was all based on calculations. I was given two graphs: one was a graph of market share in 2015 and one was of the revenue share of the products in 2019. I had to estimate some key values using that information. Then I had to determine the three best ways to promote a product. I was given a list of methods with the fixed investment for each. Then there was another list containing the base revenue generated by each method. Then another list matrix is given which paired each method with another method as a follow-up. Each cell contained an offsetting revenue. Using this, I had to determine the best possible method to promote the product. Profit = Base Revenue * 1.1 + Offset Revenue – (Cost of Method Chosen for Base Revenue + Cost of Method Chosen for Offset Revenue) I had to choose the best three methods. There was another question after this to find the best salesmen based on sales data. This one required you to find the best salesman, the worst one based on correlating multiple graphs together. This also took a lot of calculations, so I suggest anyone appearing for this to be very thorough on your graph based questions. Even though I believe I answered these correctly, I was left with no time to revise my answers. A follow-up round was held almost immediately, where I got to defend my solutions to an interviewer. The interviewer tried to prod me on details related to my answer. There were questions I was confident on, and she asked me repeatedly if I was sure which I was. The point of this round was to test your confidence basically. Round 4: The final round was held by a manager. It began with the usual formalities, followed by one guesstimate: to find the number of cars plying through Gurgaon highway. I assumed the length as 20km of which half was five-lane and the other half was three lanes. I ignored bikes for my analysis as I was told to do so. I took the length of each of the cars as 2 m. I divided the period of high traffic: 7 am-11 am and 4 pm to 7 pm. For these, I assumed the traffic was bumper to bumper and it took a car for 1 hour. (10000metres/2 )*(5lanes+3 lanes) * 2 (for two lanes) I assumed during other periods traffic was half of this and added the two values together. The interviewer accepted my answer and wished me luck. I was rejected for the role. Marketing ZS Associates Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Nov, 2020" }, { "code": null, "e": 253, "s": 28, "text": "I applied through a referral I got from a friend who had been working at ZS for more than two years. Using his referral, I got a quick reply from ZS Associates with a test link and was a given a period of time to solve it. " }, { "code": null, "e": 669, "s": 253, "text": "Round 1: This was mostly based on aptitude questions, hosted on Talview. Though I am generally very good at aptitude questions, the timings of the rounds made it extra tricky and I believe that I missed some questions. While submitting, I had an issue with my internet, so Talview had a call centre I could call. My assessment was submitted successfully. So in the case, it happens to you, keeps their number handy." }, { "code": null, "e": 2329, "s": 669, "text": "Round 2: There was a short telephonic round that was conducted two months later. I was notified about one week before regarding the same by my recruiter. My interview was conducted by her and lasted about 15 minutes. She asked a question to talk about myself. Then she followed up with two guesstimate-based questions: determine the number of people living in Delhi wearing a red item at that time (ie a shirt, dress, jewellery, pants). This question confused me for a while. She gave me a minute to think as I gave an answer that was not so well-thought-out. For anyone new to guesstimates, it is crucial to think before you speak. I thought for about two minutes before I gave my answer. My logic was simple, I considered the fact it was a Tuesday (the day the interview was conducted). I split the population of Delhi into key demographics based on age: children, adults, and senior citizens taking a 30-50-20 split. I assumed since it was a working day and adults would most likely be wearing muted colours to attend video meetings (it was during the pandemic after all). I also assumed senior citizens would not be wearing such a colour. That left the children. I assumed children would wear bright colours as they do not have to worry about appearing in meetings. I assumed a set of popular colours: red, blue, green, yellow, white. I assumed the proportion of people wearing each of these colours would be same, 20% each. I also chose to ignore jewellery as this was during the pandemic and these are often worn during social events only which was pretty much nonexistent at the time. I calculated the answer and the interviewer responded with an okay." }, { "code": null, "e": 3220, "s": 2329, "text": "The next question was the number of red lights (bulbs, tube lights, LED) in Delhi. After some careful thinking, I ignored LED by explaining that during the pandemic, no real festivities were happening. For the question of the tube light, since I knew the area of Delhi to be roughly 1500 square kilometres, I assumed the dimensions of Delhi as 30km x 50km with each road as roughly 500 meters long. I told the interviewer that the red bulbs would be used in traffic lights, so by calculating the number of roads, I could assume there was one per road. I gave her my answer. She followed up with a question regarding whether how many the bulbs would be functional. This part confused me again. I took some time and responded that a majority would be working, so I assumed 80% of the traffic lights were functioning fine and revised my answer accordingly. The interviewer accepted my answer." }, { "code": null, "e": 3607, "s": 3220, "text": "Round 3: This was the case study round. I was given a large dataset of a pharma company to study. It was of a company that a leading market share of a product in 2015 which was reduced to a much smaller one due to the entrance of a new company with a similarly reliable product at a much more affordable price. There were no strategy-based questions as per the Case Interview Prep book." }, { "code": null, "e": 4253, "s": 3607, "text": "It was all based on calculations. I was given two graphs: one was a graph of market share in 2015 and one was of the revenue share of the products in 2019. I had to estimate some key values using that information. Then I had to determine the three best ways to promote a product. I was given a list of methods with the fixed investment for each. Then there was another list containing the base revenue generated by each method. Then another list matrix is given which paired each method with another method as a follow-up. Each cell contained an offsetting revenue. Using this, I had to determine the best possible method to promote the product." }, { "code": null, "e": 4386, "s": 4253, "text": "Profit = Base Revenue * 1.1 + Offset Revenue – (Cost of Method Chosen for Base Revenue + Cost of Method Chosen for Offset Revenue) " }, { "code": null, "e": 4426, "s": 4386, "text": "I had to choose the best three methods." }, { "code": null, "e": 4621, "s": 4426, "text": "There was another question after this to find the best salesmen based on sales data. This one required you to find the best salesman, the worst one based on correlating multiple graphs together." }, { "code": null, "e": 4846, "s": 4621, "text": "This also took a lot of calculations, so I suggest anyone appearing for this to be very thorough on your graph based questions. Even though I believe I answered these correctly, I was left with no time to revise my answers." }, { "code": null, "e": 5172, "s": 4846, "text": "A follow-up round was held almost immediately, where I got to defend my solutions to an interviewer. The interviewer tried to prod me on details related to my answer. There were questions I was confident on, and she asked me repeatedly if I was sure which I was. The point of this round was to test your confidence basically." }, { "code": null, "e": 5691, "s": 5172, "text": "Round 4: The final round was held by a manager. It began with the usual formalities, followed by one guesstimate: to find the number of cars plying through Gurgaon highway. I assumed the length as 20km of which half was five-lane and the other half was three lanes. I ignored bikes for my analysis as I was told to do so. I took the length of each of the cars as 2 m. I divided the period of high traffic: 7 am-11 am and 4 pm to 7 pm. For these, I assumed the traffic was bumper to bumper and it took a car for 1 hour." }, { "code": null, "e": 5745, "s": 5691, "text": "(10000metres/2 )*(5lanes+3 lanes) * 2 (for two lanes)" }, { "code": null, "e": 5836, "s": 5745, "text": "I assumed during other periods traffic was half of this and added the two values together." }, { "code": null, "e": 5891, "s": 5836, "text": "The interviewer accepted my answer and wished me luck." }, { "code": null, "e": 5920, "s": 5891, "text": "I was rejected for the role." }, { "code": null, "e": 5930, "s": 5920, "text": "Marketing" }, { "code": null, "e": 5944, "s": 5930, "text": "ZS Associates" }, { "code": null, "e": 5966, "s": 5944, "text": "Interview Experiences" } ]
How to Install Face Recognition in Python on Linux?
16 Oct, 2021 In this article, we will learn how to install Face Recognition in Python on Linux. This package is used to recognize and manipulate faces from Python or from the command line with the world’s simplest face recognition library. Follow the below steps to install the Face Recognition package on Linux using pip: Step 1: Install the latest Python3 in Linux Step 2: Check if pip3 and python3 are correctly installed. python3 --version pip3 --version Step 3: Upgrade your pip to avoid errors during installation. pip3 install --upgrade pip Step 4: Enter the following command to install Face Recognition using pip3. pip3 install face-recognition Follow the below steps to install the Face Recognition package on Linux using the setup.py file: Step 1: Download the latest source package of Face Recognition for python3 from here. curl https://files.pythonhosted.org/packages/92/aa/fd00864e0bab93d084879bf149cb25d87850887199f0f1bebd16f926f3dc/face_recognition-0.1.11.tar.gz > face_recognition.tar.gz Step 2: Extract the downloaded package using the following command. tar -xvzf face_recognition.tar.gz Step 3: Go inside the folder and Enter the following command to install the package. cd face_recognition-0.1.11 python3 setup.py install Make the following import in your python terminal to verify if the installation has been done properly: import face_recognition If there is any error while importing the module then is not installed properly. how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install and Use NVM on Windows? How to Install Jupyter Notebook on MacOS? How to Install Python Packages for AWS Lambda Layers? How to Add External JAR File to an IntelliJ IDEA Project? Installation of Node.js on Linux Installation of Node.js on Windows How to Install and Use NVM on Windows? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2021" }, { "code": null, "e": 255, "s": 28, "text": "In this article, we will learn how to install Face Recognition in Python on Linux. This package is used to recognize and manipulate faces from Python or from the command line with the world’s simplest face recognition library." }, { "code": null, "e": 338, "s": 255, "text": "Follow the below steps to install the Face Recognition package on Linux using pip:" }, { "code": null, "e": 382, "s": 338, "text": "Step 1: Install the latest Python3 in Linux" }, { "code": null, "e": 441, "s": 382, "text": "Step 2: Check if pip3 and python3 are correctly installed." }, { "code": null, "e": 474, "s": 441, "text": "python3 --version\npip3 --version" }, { "code": null, "e": 536, "s": 474, "text": "Step 3: Upgrade your pip to avoid errors during installation." }, { "code": null, "e": 563, "s": 536, "text": "pip3 install --upgrade pip" }, { "code": null, "e": 639, "s": 563, "text": "Step 4: Enter the following command to install Face Recognition using pip3." }, { "code": null, "e": 669, "s": 639, "text": "pip3 install face-recognition" }, { "code": null, "e": 766, "s": 669, "text": "Follow the below steps to install the Face Recognition package on Linux using the setup.py file:" }, { "code": null, "e": 852, "s": 766, "text": "Step 1: Download the latest source package of Face Recognition for python3 from here." }, { "code": null, "e": 1021, "s": 852, "text": "curl https://files.pythonhosted.org/packages/92/aa/fd00864e0bab93d084879bf149cb25d87850887199f0f1bebd16f926f3dc/face_recognition-0.1.11.tar.gz > face_recognition.tar.gz" }, { "code": null, "e": 1089, "s": 1021, "text": "Step 2: Extract the downloaded package using the following command." }, { "code": null, "e": 1123, "s": 1089, "text": "tar -xvzf face_recognition.tar.gz" }, { "code": null, "e": 1208, "s": 1123, "text": "Step 3: Go inside the folder and Enter the following command to install the package." }, { "code": null, "e": 1260, "s": 1208, "text": "cd face_recognition-0.1.11\npython3 setup.py install" }, { "code": null, "e": 1364, "s": 1260, "text": "Make the following import in your python terminal to verify if the installation has been done properly:" }, { "code": null, "e": 1388, "s": 1364, "text": "import face_recognition" }, { "code": null, "e": 1469, "s": 1388, "text": "If there is any error while importing the module then is not installed properly." }, { "code": null, "e": 1484, "s": 1469, "text": "how-to-install" }, { "code": null, "e": 1491, "s": 1484, "text": "Picked" }, { "code": null, "e": 1498, "s": 1491, "text": "How To" }, { "code": null, "e": 1517, "s": 1498, "text": "Installation Guide" }, { "code": null, "e": 1615, "s": 1517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1664, "s": 1615, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 1703, "s": 1664, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 1745, "s": 1703, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 1799, "s": 1745, "text": "How to Install Python Packages for AWS Lambda Layers?" }, { "code": null, "e": 1857, "s": 1799, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 1890, "s": 1857, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1925, "s": 1890, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1964, "s": 1925, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 2006, "s": 1964, "text": "How to Install Jupyter Notebook on MacOS?" } ]
How to save HTML Tables data to CSV in Python
One of the most challenging taks for a data sceintist is to collect the data. While the fact is, there is plenty of data available in the web it is just extracting the data through automation. I wanted to extract the basic operations data which is embedded in HTML tables from https://www.tutorialspoint.com/python/python_basic_operators.htm. Hmmm, The data is scattered in many HTML tables, if there is only one HTML table obviously I can use Copy & Paste to .csv file. However, if there are more than 5 tables in a single page then obviously it is pain. Isn't it ? 1. I will quickly show you how to create an csv file easily if you want to create a csv file. import csv # Open File in Write mode , if not found it will create one File = open('test.csv', 'w+') Data = csv.writer(File) # My Header Data.writerow(('Column1', 'Column2', 'Column3')) # Write data for i in range(20): Data.writerow((i, i+1, i+2)) # close my file File.close() The above code when executed produces a test.csv file with in the same directory as this code. 2. Let us now retrieve an HTML table from https://www.tutorialspoint.com/python/python_dictionary.htm and write it as a CSV file. First step is to do imports. import csv from urllib.request import urlopen from bs4 import BeautifulSoup url = 'https://www.tutorialspoint.com/python/python_dictionary.htm' Open the HTML file and store it in html object using urlopen. Open the HTML file and store it in html object using urlopen. html = urlopen(url) soup = BeautifulSoup(html, 'html.parser') Find the tables inside the html table and Let us bring the tables data. For demonstration purpose I will be extracting only the first table [0] Find the tables inside the html table and Let us bring the tables data. For demonstration purpose I will be extracting only the first table [0] table = soup.find_all('table')[0] rows = table.find_all('tr') print(rows) [<tr> <th style='text-align:center;width:5%'>Sr.No.</th> <th style='text-align:center;width:95%'>Function with Description</th> </tr>, <tr> <td class='ts'>1</td> <td><a href='/python/dictionary_cmp.htm'>cmp(dict1, dict2)</a> <p>Compares elements of both dict.</p></td> </tr>, <tr> <td class='ts'>2</td> <td><a href='/python/dictionary_len.htm'>len(dict)</a> <p>Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.</p></td> </tr>, <tr> <td class='ts'>3</td> <td><a href='/python/dictionary_str.htm'>str(dict)</a> <p>Produces a printable string representation of a dictionary</p></td> </tr>, <tr> <td class='ts'>4</td> <td><a href='/python/dictionary_type.htm'>type(variable)</a> <p>Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.</p></td> </tr>] 5. Now we will write the data to csv file. File = open('my_html_data_to_csv.csv', 'wt+') Data = csv.writer(File) try: for row in rows: FilteredRow = [] for cell in row.find_all(['td', 'th']): FilteredRow.append(cell.get_text()) Data.writerow(FilteredRow) finally: File.close() 6. The results are now saved into my_html_data_to_csv.csv file. We will put everything explained above together. import csv from urllib.request import urlopen from bs4 import BeautifulSoup # set the url.. url = 'https://www.tutorialspoint.com/python/python_basic_syntax.htm' # Open the url and parse the html html = urlopen(url) soup = BeautifulSoup(html, 'html.parser') # extract the first table table = soup.find_all('table')[0] rows = table.find_all('tr') # write the content to the file File = open('my_html_data_to_csv.csv', 'wt+') Data = csv.writer(File) try: for row in rows: FilteredRow = [] for cell in row.find_all(['td', 'th']): FilteredRow.append(cell.get_text()) Data.writerow(FilteredRow) finally: File.close()
[ { "code": null, "e": 1380, "s": 1187, "text": "One of the most challenging taks for a data sceintist is to collect the data. While the fact is, there is plenty of data available in the web it is just extracting the data through automation." }, { "code": null, "e": 1530, "s": 1380, "text": "I wanted to extract the basic operations data which is embedded in HTML tables from https://www.tutorialspoint.com/python/python_basic_operators.htm." }, { "code": null, "e": 1658, "s": 1530, "text": "Hmmm, The data is scattered in many HTML tables, if there is only one HTML table obviously I can use Copy & Paste to .csv file." }, { "code": null, "e": 1754, "s": 1658, "text": "However, if there are more than 5 tables in a single page then obviously it is pain. Isn't it ?" }, { "code": null, "e": 1848, "s": 1754, "text": "1.\nI will quickly show you how to create an csv file easily if you want to create a csv file." }, { "code": null, "e": 2128, "s": 1848, "text": "import csv\n# Open File in Write mode , if not found it will create one\nFile = open('test.csv', 'w+')\nData = csv.writer(File)\n\n# My Header\nData.writerow(('Column1', 'Column2', 'Column3'))\n\n# Write data\nfor i in range(20):\nData.writerow((i, i+1, i+2))\n\n# close my file\nFile.close()" }, { "code": null, "e": 2223, "s": 2128, "text": "The above code when executed produces a test.csv file with in the same directory as this code." }, { "code": null, "e": 2353, "s": 2223, "text": "2. Let us now retrieve an HTML table from https://www.tutorialspoint.com/python/python_dictionary.htm and write it as a CSV file." }, { "code": null, "e": 2382, "s": 2353, "text": "First step is to do imports." }, { "code": null, "e": 2526, "s": 2382, "text": "import csv\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nurl = 'https://www.tutorialspoint.com/python/python_dictionary.htm'" }, { "code": null, "e": 2588, "s": 2526, "text": "Open the HTML file and store it in html object using urlopen." }, { "code": null, "e": 2650, "s": 2588, "text": "Open the HTML file and store it in html object using urlopen." }, { "code": null, "e": 2712, "s": 2650, "text": "html = urlopen(url)\nsoup = BeautifulSoup(html, 'html.parser')" }, { "code": null, "e": 2856, "s": 2712, "text": "Find the tables inside the html table and Let us bring the tables data. For demonstration purpose I will be extracting only the first table [0]" }, { "code": null, "e": 3000, "s": 2856, "text": "Find the tables inside the html table and Let us bring the tables data. For demonstration purpose I will be extracting only the first table [0]" }, { "code": null, "e": 3062, "s": 3000, "text": "table = soup.find_all('table')[0]\nrows = table.find_all('tr')" }, { "code": null, "e": 3074, "s": 3062, "text": "print(rows)" }, { "code": null, "e": 3940, "s": 3074, "text": "[<tr>\n<th style='text-align:center;width:5%'>Sr.No.</th>\n<th style='text-align:center;width:95%'>Function with Description</th>\n</tr>, \n<tr>\n<td class='ts'>1</td>\n<td><a href='/python/dictionary_cmp.htm'>cmp(dict1, dict2)</a>\n<p>Compares elements of both dict.</p></td>\n</tr>, <tr>\n<td class='ts'>2</td>\n<td><a href='/python/dictionary_len.htm'>len(dict)</a>\n<p>Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.</p></td>\n</tr>, \n<tr>\n<td class='ts'>3</td>\n<td><a href='/python/dictionary_str.htm'>str(dict)</a>\n<p>Produces a printable string representation of a dictionary</p></td>\n</tr>, \n<tr>\n<td class='ts'>4</td>\n<td><a href='/python/dictionary_type.htm'>type(variable)</a>\n<p>Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.</p></td>\n</tr>]" }, { "code": null, "e": 3983, "s": 3940, "text": "5.\nNow we will write the data to csv file." }, { "code": null, "e": 4217, "s": 3983, "text": "File = open('my_html_data_to_csv.csv', 'wt+')\nData = csv.writer(File)\ntry:\nfor row in rows:\nFilteredRow = []\nfor cell in row.find_all(['td', 'th']):\nFilteredRow.append(cell.get_text())\nData.writerow(FilteredRow)\nfinally:\nFile.close()" }, { "code": null, "e": 4281, "s": 4217, "text": "6.\nThe results are now saved into my_html_data_to_csv.csv file." }, { "code": null, "e": 4330, "s": 4281, "text": "We will put everything explained above together." }, { "code": null, "e": 4946, "s": 4330, "text": "import csv\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n# set the url..\nurl = 'https://www.tutorialspoint.com/python/python_basic_syntax.htm'\n\n# Open the url and parse the html\nhtml = urlopen(url)\nsoup = BeautifulSoup(html, 'html.parser')\n\n# extract the first table\ntable = soup.find_all('table')[0]\nrows = table.find_all('tr')\n\n# write the content to the file\nFile = open('my_html_data_to_csv.csv', 'wt+')\nData = csv.writer(File)\ntry:\nfor row in rows:\nFilteredRow = []\nfor cell in row.find_all(['td', 'th']):\nFilteredRow.append(cell.get_text())\nData.writerow(FilteredRow)\nfinally:\nFile.close()" } ]
Image compression using K-means clustering
13 May, 2019 Prerequisite: K-means clustering The internet is filled with huge amounts of data in the form of images. People upload millions of pictures every day on social media sites such as Instagram, Facebook and cloud storage platforms such as google drive, etc. With such large amounts of data, image compression techniques become important to compress the images and reduce storage space. In this article, we will look at image compression using K-means clustering algorithm which is an unsupervised learning algorithm. An image is made up of several intensity values known as Pixels. In a colored image, each pixel is of 3 bytes containing RGB (Red-Blue-Green) values having Red intensity value, then Blue and then Green intensity value for each pixel. Approach:K-means clustering will group similar colors together into ‘k’ clusters (say k=64) of different colors (RGB values). Therefore, each cluster centroid is the representative of the color vector in RGB color space of its respective cluster. Now, these ‘k’ cluster centroids will replace all the color vectors in their respective clusters. Thus, we need to only store the label for each pixel which tells the cluster to which this pixel belongs. Additionally, we keep the record of color vectors of each cluster center. Libraries needed – -> Numpy library: sudo pip3 install numpy.-> Matplotlib library: sudo pip3 install matplotlib.-> scipy library: sudo pip3 install scipy Below is the Python implementation : import numpy as npimport matplotlib.pyplot as pltimport matplotlib.image as img# from scipy.io import loadmatfrom scipy import misc def read_image(): # loading the png image as a 3d matrix img = misc.imread('bird_small.png') # uncomment the below code to view the loaded image # plt.imshow(A) # plotting the image # plt.show() # scaling it so that the values are small img = img / 255 return img def initialize_means(img, clusters): # reshaping it or flattening it into a 2d matrix points = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2])) m, n = points.shape # clusters is the number of clusters # or the number of colors that we choose. # means is the array of assumed means or centroids. means = np.zeros((clusters, n)) # random initialization of means. for i in range(clusters): rand1 = int(np.random.random(1)*10) rand2 = int(np.random.random(1)*8) means[i, 0] = points[rand1, 0] means[i, 1] = points[rand2, 1] return points, means # Function to measure the euclidean# distance (distance formula)def distance(x1, y1, x2, y2): dist = np.square(x1 - x2) + np.square(y1 - y2) dist = np.sqrt(dist) return dist def k_means(points, means, clusters): iterations = 10 # the number of iterations m, n = points.shape # these are the index values that # correspond to the cluster to # which each pixel belongs to. index = np.zeros(m) # k-means algorithm. while(iterations > 0): for j in range(len(points)): # initialize minimum value to a large value minv = 1000 temp = None for k in range(clusters): x1 = points[j, 0] y1 = points[j, 1] x2 = means[k, 0] y2 = means[k, 1] if(distance(x1, y1, x2, y2) < minv): minv = distance(x1, y1, x2, y2) temp = k index[j] = k for k in range(clusters): sumx = 0 sumy = 0 count = 0 for j in range(len(points)): if(index[j] == k): sumx += points[j, 0] sumy += points[j, 1] count += 1 if(count == 0): count = 1 means[k, 0] = float(sumx / count) means[k, 1] = float(sumy / count) iterations -= 1 return means, index def compress_image(means, index, img): # recovering the compressed image by # assigning each pixel to its corresponding centroid. centroid = np.array(means) recovered = centroid[index.astype(int), :] # getting back the 3d matrix (row, col, rgb(3)) recovered = np.reshape(recovered, (img.shape[0], img.shape[1], img.shape[2])) # plotting the compressed image. plt.imshow(recovered) plt.show() # saving the compressed image. misc.imsave('compressed_' + str(clusters) + '_colors.png', recovered) # Driver Codeif __name__ == '__main__': img = read_image() clusters = 16 clusters = int(input('Enter the number of colors in the compressed image. default = 16\n')) points, means = initialize_means(img, clusters) means, index = k_means(points, means, clusters) compress_image(means, index, img) Input Image: Output : Image-Processing Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Support Vector Machine Algorithm Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI Python | Linear Regression using sklearn
[ { "code": null, "e": 28, "s": 0, "text": "\n13 May, 2019" }, { "code": null, "e": 61, "s": 28, "text": "Prerequisite: K-means clustering" }, { "code": null, "e": 411, "s": 61, "text": "The internet is filled with huge amounts of data in the form of images. People upload millions of pictures every day on social media sites such as Instagram, Facebook and cloud storage platforms such as google drive, etc. With such large amounts of data, image compression techniques become important to compress the images and reduce storage space." }, { "code": null, "e": 542, "s": 411, "text": "In this article, we will look at image compression using K-means clustering algorithm which is an unsupervised learning algorithm." }, { "code": null, "e": 776, "s": 542, "text": "An image is made up of several intensity values known as Pixels. In a colored image, each pixel is of 3 bytes containing RGB (Red-Blue-Green) values having Red intensity value, then Blue and then Green intensity value for each pixel." }, { "code": null, "e": 1301, "s": 776, "text": "Approach:K-means clustering will group similar colors together into ‘k’ clusters (say k=64) of different colors (RGB values). Therefore, each cluster centroid is the representative of the color vector in RGB color space of its respective cluster. Now, these ‘k’ cluster centroids will replace all the color vectors in their respective clusters. Thus, we need to only store the label for each pixel which tells the cluster to which this pixel belongs. Additionally, we keep the record of color vectors of each cluster center." }, { "code": null, "e": 1320, "s": 1301, "text": "Libraries needed –" }, { "code": null, "e": 1456, "s": 1320, "text": "-> Numpy library: sudo pip3 install numpy.-> Matplotlib library: sudo pip3 install matplotlib.-> scipy library: sudo pip3 install scipy" }, { "code": null, "e": 1493, "s": 1456, "text": "Below is the Python implementation :" }, { "code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.image as img# from scipy.io import loadmatfrom scipy import misc def read_image(): # loading the png image as a 3d matrix img = misc.imread('bird_small.png') # uncomment the below code to view the loaded image # plt.imshow(A) # plotting the image # plt.show() # scaling it so that the values are small img = img / 255 return img def initialize_means(img, clusters): # reshaping it or flattening it into a 2d matrix points = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2])) m, n = points.shape # clusters is the number of clusters # or the number of colors that we choose. # means is the array of assumed means or centroids. means = np.zeros((clusters, n)) # random initialization of means. for i in range(clusters): rand1 = int(np.random.random(1)*10) rand2 = int(np.random.random(1)*8) means[i, 0] = points[rand1, 0] means[i, 1] = points[rand2, 1] return points, means # Function to measure the euclidean# distance (distance formula)def distance(x1, y1, x2, y2): dist = np.square(x1 - x2) + np.square(y1 - y2) dist = np.sqrt(dist) return dist def k_means(points, means, clusters): iterations = 10 # the number of iterations m, n = points.shape # these are the index values that # correspond to the cluster to # which each pixel belongs to. index = np.zeros(m) # k-means algorithm. while(iterations > 0): for j in range(len(points)): # initialize minimum value to a large value minv = 1000 temp = None for k in range(clusters): x1 = points[j, 0] y1 = points[j, 1] x2 = means[k, 0] y2 = means[k, 1] if(distance(x1, y1, x2, y2) < minv): minv = distance(x1, y1, x2, y2) temp = k index[j] = k for k in range(clusters): sumx = 0 sumy = 0 count = 0 for j in range(len(points)): if(index[j] == k): sumx += points[j, 0] sumy += points[j, 1] count += 1 if(count == 0): count = 1 means[k, 0] = float(sumx / count) means[k, 1] = float(sumy / count) iterations -= 1 return means, index def compress_image(means, index, img): # recovering the compressed image by # assigning each pixel to its corresponding centroid. centroid = np.array(means) recovered = centroid[index.astype(int), :] # getting back the 3d matrix (row, col, rgb(3)) recovered = np.reshape(recovered, (img.shape[0], img.shape[1], img.shape[2])) # plotting the compressed image. plt.imshow(recovered) plt.show() # saving the compressed image. misc.imsave('compressed_' + str(clusters) + '_colors.png', recovered) # Driver Codeif __name__ == '__main__': img = read_image() clusters = 16 clusters = int(input('Enter the number of colors in the compressed image. default = 16\\n')) points, means = initialize_means(img, clusters) means, index = k_means(points, means, clusters) compress_image(means, index, img)", "e": 5163, "s": 1493, "text": null }, { "code": null, "e": 5176, "s": 5163, "text": "Input Image:" }, { "code": null, "e": 5185, "s": 5176, "text": "Output :" }, { "code": null, "e": 5202, "s": 5185, "text": "Image-Processing" }, { "code": null, "e": 5219, "s": 5202, "text": "Machine Learning" }, { "code": null, "e": 5236, "s": 5219, "text": "Machine Learning" }, { "code": null, "e": 5334, "s": 5236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5375, "s": 5334, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 5411, "s": 5375, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 5444, "s": 5411, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 5468, "s": 5444, "text": "Markov Decision Process" }, { "code": null, "e": 5519, "s": 5468, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 5552, "s": 5519, "text": "Normalization vs Standardization" }, { "code": null, "e": 5592, "s": 5552, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 5633, "s": 5592, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 5661, "s": 5633, "text": "Types of Environments in AI" } ]
Keras Hyperparameter Tuning in Google Colab using Hyperas | by Nils Schlüter | Towards Data Science
Hyperparameter Tuning is one of the most computationally expensive tasks when creating deep learning networks. Luckily, you can use Google Colab to speed up the process significantly. In this post, I will show you how you can tune the hyperparameters of your existing keras models using Hyperas and run everything in a Google Colab Notebook. First, you need to create a new notebook. Open your Colab Console and select New Python 3 Notebook. In your notebook, choose Runtime from the menu and then Change runtime type. Select Hardware accelerator: GPU and hit save. This will significantly speed up every calculation you do in this notebook. You can install new packages using pip. In this case, we need hyperas and hyperopt. Copy and paste the following into the first cell of your notebook: !pip install hyperas!pip install hyperopt When you run the cell you will see that pip is downloading and installing the dependencies. For this post I’m going to use the example from the hyperas github page. You can find the finished Colab Notebook here. You’ll need a data function to load your data. It needs to return your X_train, Y_train, X_test and Y_test values. Here is an example for a data function: Note: Your data function needs to return the values in exactly this order: X_train, Y_train, X_test, Y_test. Be careful if you’re using scikit learns train_test_split, as this returns the values in a different order The Model Function is where you define your model. You can use your all available keras functions and layers. To add Hyperparameters for tuning, you can use the {{uniform()}} and {{choice()}} keywords. Let’s say you want to try out different values for your batch_size. You can simply write batch_size={{choice([32, 64, 128])}} and during each trial, one of the values will be chosen and tried out . A more in-depth explanation on how to define the parameters to tune can be found on the Hyperas Github Page or you can look at the example: Note: Your model function has to return a python dictionary with a loss key and a status key If you try to run this example now, the trial will fail because Hyperas won’t be able to find your notebook. You need to copy your notebook and upload it again to your google drive folder. Luckily, you can do this from inside your notebook as described in this stackoverflow answer. Note: In lines 16 and 18, you’ll need to change HyperasMediumExample to the name of your own notebook After running this cell, you will be prompted to open a website in your browser and copy & paste a code back into the notebook: Follow the link, log in with your google account and copy & paste the code back into the notebook. If you open the Files Tab in the left sidebar, you should now see a File called <YourNotebook>.ipynb Now you can start the trial. Be careful, you have to set the parameter notebook_name to the name of your Notebook. Otherwise the Trial will fail: After running this cell, the Scan starts you can see the result in the output of the cell. If you have any problems while doing this, I recommend to do the following: In the left sidebar, open Files. There will be a file called <YourNotebook>.ipynb. Delete that fileIn the menu, select Runtime and then Restart Runtime.Reload the page In the left sidebar, open Files. There will be a file called <YourNotebook>.ipynb. Delete that file In the menu, select Runtime and then Restart Runtime. Reload the page After your runtime is connected again, you can start again by running every cell from top to bottom With just a few tweaks you can use Google colab to tune the hyperparameters of your keras network. Again, the full example can be found here.
[ { "code": null, "e": 388, "s": 46, "text": "Hyperparameter Tuning is one of the most computationally expensive tasks when creating deep learning networks. Luckily, you can use Google Colab to speed up the process significantly. In this post, I will show you how you can tune the hyperparameters of your existing keras models using Hyperas and run everything in a Google Colab Notebook." }, { "code": null, "e": 688, "s": 388, "text": "First, you need to create a new notebook. Open your Colab Console and select New Python 3 Notebook. In your notebook, choose Runtime from the menu and then Change runtime type. Select Hardware accelerator: GPU and hit save. This will significantly speed up every calculation you do in this notebook." }, { "code": null, "e": 839, "s": 688, "text": "You can install new packages using pip. In this case, we need hyperas and hyperopt. Copy and paste the following into the first cell of your notebook:" }, { "code": null, "e": 881, "s": 839, "text": "!pip install hyperas!pip install hyperopt" }, { "code": null, "e": 973, "s": 881, "text": "When you run the cell you will see that pip is downloading and installing the dependencies." }, { "code": null, "e": 1093, "s": 973, "text": "For this post I’m going to use the example from the hyperas github page. You can find the finished Colab Notebook here." }, { "code": null, "e": 1248, "s": 1093, "text": "You’ll need a data function to load your data. It needs to return your X_train, Y_train, X_test and Y_test values. Here is an example for a data function:" }, { "code": null, "e": 1464, "s": 1248, "text": "Note: Your data function needs to return the values in exactly this order: X_train, Y_train, X_test, Y_test. Be careful if you’re using scikit learns train_test_split, as this returns the values in a different order" }, { "code": null, "e": 1666, "s": 1464, "text": "The Model Function is where you define your model. You can use your all available keras functions and layers. To add Hyperparameters for tuning, you can use the {{uniform()}} and {{choice()}} keywords." }, { "code": null, "e": 2004, "s": 1666, "text": "Let’s say you want to try out different values for your batch_size. You can simply write batch_size={{choice([32, 64, 128])}} and during each trial, one of the values will be chosen and tried out . A more in-depth explanation on how to define the parameters to tune can be found on the Hyperas Github Page or you can look at the example:" }, { "code": null, "e": 2097, "s": 2004, "text": "Note: Your model function has to return a python dictionary with a loss key and a status key" }, { "code": null, "e": 2380, "s": 2097, "text": "If you try to run this example now, the trial will fail because Hyperas won’t be able to find your notebook. You need to copy your notebook and upload it again to your google drive folder. Luckily, you can do this from inside your notebook as described in this stackoverflow answer." }, { "code": null, "e": 2482, "s": 2380, "text": "Note: In lines 16 and 18, you’ll need to change HyperasMediumExample to the name of your own notebook" }, { "code": null, "e": 2610, "s": 2482, "text": "After running this cell, you will be prompted to open a website in your browser and copy & paste a code back into the notebook:" }, { "code": null, "e": 2810, "s": 2610, "text": "Follow the link, log in with your google account and copy & paste the code back into the notebook. If you open the Files Tab in the left sidebar, you should now see a File called <YourNotebook>.ipynb" }, { "code": null, "e": 2956, "s": 2810, "text": "Now you can start the trial. Be careful, you have to set the parameter notebook_name to the name of your Notebook. Otherwise the Trial will fail:" }, { "code": null, "e": 3047, "s": 2956, "text": "After running this cell, the Scan starts you can see the result in the output of the cell." }, { "code": null, "e": 3123, "s": 3047, "text": "If you have any problems while doing this, I recommend to do the following:" }, { "code": null, "e": 3291, "s": 3123, "text": "In the left sidebar, open Files. There will be a file called <YourNotebook>.ipynb. Delete that fileIn the menu, select Runtime and then Restart Runtime.Reload the page" }, { "code": null, "e": 3391, "s": 3291, "text": "In the left sidebar, open Files. There will be a file called <YourNotebook>.ipynb. Delete that file" }, { "code": null, "e": 3445, "s": 3391, "text": "In the menu, select Runtime and then Restart Runtime." }, { "code": null, "e": 3461, "s": 3445, "text": "Reload the page" }, { "code": null, "e": 3561, "s": 3461, "text": "After your runtime is connected again, you can start again by running every cell from top to bottom" } ]
Summarize Long Text Documents using Machine Learning | by Satyam Kumar | Towards Data Science
Text summarization is the process of creating a short, accurate, and fluent summary of a long text document. It is the process of distilling the most important information for a text document. The intention of text summarization is to create a summary of a large corpus having important points describing the entire corpus. A vast quantity of text data is generated on the internet, be it social media articles, news articles, etc. Manual creation of summaries is time-consuming, and therefore a need for automatic text summaries has arisen. Not only are the automatic summarization tools much faster, but they are also less biased than humans. Text summarization is useful in many ways to summarize the textual data. Some of the uses of text summarization are: To reduce the reading time of long documents While researching documents, summaries make the selection process easier. The text summarizes are useful for question-answer systems. Using a text summarization system enables commercial abstract services to increase the number of text documents to process. Several news portals such as Google News, Inshorts, etc provide short summaries of the long news article for their readers. Sumy is an open-sourced Python library to extract summaries from HTML pages and text files. The package also contains an evaluation framework for text summaries. Sumy offers several algorithms and methods for text summarization, some of them are: Luhn: heuristic method Latent Semantic Analysis (LSA) Edmundson heuristic method LexRank TextRank and many more. Visit the Sumy documentation page to know more about the text summarization algorithm Sumy offers. In this article, we will discuss and implement some of the popular text summarization algorithms Luhn, LexRank, LSA. Sumy is an open-sourced Python library and can be installed using PyPl: pip install sumy To read text documents from string variable or file, we can use a PlainTextParser from the Sumy package. To read text document from a text string variable ‘document’: parser = PlaintextParser.from_string(document, Tokenizer("english")) To read text document from a text file with location as ‘file’: parser = PlaintextParser.from_file(file, Tokenizer("english")) After reading the text document in Sumy Text Parser, we can use several algorithms or methods to summarize the given text document. LexRank Algorithm is an unsupervised approach to summarization and is inspired by the PageRank algorithm. LexRank uses an IDF-modified cosine similarity score to improve the Pagerank score for document summarization. It summarizes the text based on graph-based centrality scoring of sentences. If one sentence is very similar to other sentences in the text corpus, then that sentence is considered of great importance. Such sentences can be recommended to the users. LexRank summarizer can be implemented using an object called from Sumy package. After creating an object of LexRankSummarizer, pass the text document and number of lines to return in the summary. Latent Semantic Analysis (LSA) is based on term frequency techniques with singular value decomposition to summarize texts. LSA is an unsupervised NLP technique, and the aim of LSA is to create a representation of text data in terms of topics or latent features. LSA consists of two steps: To generate a document term matrix (or numerical vector). To perform Singular Value Decomposition on document term matrix. SVD reduces the dimensionality of the original dataset by encoding it with latent features. With LSA these latent features represent topics in the original data. Text summarizers are used to create short summaries of long text documents. The input long text documents are taken from the Wikipedia page of Machine Learning. The output of Text Summarization using LexRank Algorithm: The output of Text Summarization using LSA Algorithm: In this article, we have discussed how to summarize long text documents using an open-sourced python package Sumy. Sumy offers various algorithms such as LexRank, Luhn, LSA, TextRank, SumBasic, etc to summarize the text documents. Sumy can summarize texts from string variables and files on disk. You can also read about Text-Summarize, that is another open-source python library to summarize text document. [1] Sumy Documentation (May 19, 2019): https://pypi.org/project/sumy/ Thank You for Reading
[ { "code": null, "e": 495, "s": 171, "text": "Text summarization is the process of creating a short, accurate, and fluent summary of a long text document. It is the process of distilling the most important information for a text document. The intention of text summarization is to create a summary of a large corpus having important points describing the entire corpus." }, { "code": null, "e": 816, "s": 495, "text": "A vast quantity of text data is generated on the internet, be it social media articles, news articles, etc. Manual creation of summaries is time-consuming, and therefore a need for automatic text summaries has arisen. Not only are the automatic summarization tools much faster, but they are also less biased than humans." }, { "code": null, "e": 933, "s": 816, "text": "Text summarization is useful in many ways to summarize the textual data. Some of the uses of text summarization are:" }, { "code": null, "e": 978, "s": 933, "text": "To reduce the reading time of long documents" }, { "code": null, "e": 1052, "s": 978, "text": "While researching documents, summaries make the selection process easier." }, { "code": null, "e": 1112, "s": 1052, "text": "The text summarizes are useful for question-answer systems." }, { "code": null, "e": 1360, "s": 1112, "text": "Using a text summarization system enables commercial abstract services to increase the number of text documents to process. Several news portals such as Google News, Inshorts, etc provide short summaries of the long news article for their readers." }, { "code": null, "e": 1607, "s": 1360, "text": "Sumy is an open-sourced Python library to extract summaries from HTML pages and text files. The package also contains an evaluation framework for text summaries. Sumy offers several algorithms and methods for text summarization, some of them are:" }, { "code": null, "e": 1630, "s": 1607, "text": "Luhn: heuristic method" }, { "code": null, "e": 1661, "s": 1630, "text": "Latent Semantic Analysis (LSA)" }, { "code": null, "e": 1688, "s": 1661, "text": "Edmundson heuristic method" }, { "code": null, "e": 1696, "s": 1688, "text": "LexRank" }, { "code": null, "e": 1705, "s": 1696, "text": "TextRank" }, { "code": null, "e": 1819, "s": 1705, "text": "and many more. Visit the Sumy documentation page to know more about the text summarization algorithm Sumy offers." }, { "code": null, "e": 1936, "s": 1819, "text": "In this article, we will discuss and implement some of the popular text summarization algorithms Luhn, LexRank, LSA." }, { "code": null, "e": 2008, "s": 1936, "text": "Sumy is an open-sourced Python library and can be installed using PyPl:" }, { "code": null, "e": 2025, "s": 2008, "text": "pip install sumy" }, { "code": null, "e": 2130, "s": 2025, "text": "To read text documents from string variable or file, we can use a PlainTextParser from the Sumy package." }, { "code": null, "e": 2192, "s": 2130, "text": "To read text document from a text string variable ‘document’:" }, { "code": null, "e": 2261, "s": 2192, "text": "parser = PlaintextParser.from_string(document, Tokenizer(\"english\"))" }, { "code": null, "e": 2325, "s": 2261, "text": "To read text document from a text file with location as ‘file’:" }, { "code": null, "e": 2388, "s": 2325, "text": "parser = PlaintextParser.from_file(file, Tokenizer(\"english\"))" }, { "code": null, "e": 2520, "s": 2388, "text": "After reading the text document in Sumy Text Parser, we can use several algorithms or methods to summarize the given text document." }, { "code": null, "e": 2814, "s": 2520, "text": "LexRank Algorithm is an unsupervised approach to summarization and is inspired by the PageRank algorithm. LexRank uses an IDF-modified cosine similarity score to improve the Pagerank score for document summarization. It summarizes the text based on graph-based centrality scoring of sentences." }, { "code": null, "e": 2987, "s": 2814, "text": "If one sentence is very similar to other sentences in the text corpus, then that sentence is considered of great importance. Such sentences can be recommended to the users." }, { "code": null, "e": 3183, "s": 2987, "text": "LexRank summarizer can be implemented using an object called from Sumy package. After creating an object of LexRankSummarizer, pass the text document and number of lines to return in the summary." }, { "code": null, "e": 3445, "s": 3183, "text": "Latent Semantic Analysis (LSA) is based on term frequency techniques with singular value decomposition to summarize texts. LSA is an unsupervised NLP technique, and the aim of LSA is to create a representation of text data in terms of topics or latent features." }, { "code": null, "e": 3472, "s": 3445, "text": "LSA consists of two steps:" }, { "code": null, "e": 3530, "s": 3472, "text": "To generate a document term matrix (or numerical vector)." }, { "code": null, "e": 3687, "s": 3530, "text": "To perform Singular Value Decomposition on document term matrix. SVD reduces the dimensionality of the original dataset by encoding it with latent features." }, { "code": null, "e": 3757, "s": 3687, "text": "With LSA these latent features represent topics in the original data." }, { "code": null, "e": 3918, "s": 3757, "text": "Text summarizers are used to create short summaries of long text documents. The input long text documents are taken from the Wikipedia page of Machine Learning." }, { "code": null, "e": 3976, "s": 3918, "text": "The output of Text Summarization using LexRank Algorithm:" }, { "code": null, "e": 4030, "s": 3976, "text": "The output of Text Summarization using LSA Algorithm:" }, { "code": null, "e": 4327, "s": 4030, "text": "In this article, we have discussed how to summarize long text documents using an open-sourced python package Sumy. Sumy offers various algorithms such as LexRank, Luhn, LSA, TextRank, SumBasic, etc to summarize the text documents. Sumy can summarize texts from string variables and files on disk." }, { "code": null, "e": 4438, "s": 4327, "text": "You can also read about Text-Summarize, that is another open-source python library to summarize text document." }, { "code": null, "e": 4508, "s": 4438, "text": "[1] Sumy Documentation (May 19, 2019): https://pypi.org/project/sumy/" } ]
PhoneGap - Quick Guide
Mobile, handhelds and easy-to-carry devices have started a new revolution in software engineering. These small but efficient devices are capable to run applications created with high-end programming languages. People who own these devices tend to use them at their maximum as these devices such as mobile phones, are very convenient to use anytime, anywhere. The architecture of a mobile device is similar to that of a computer system. It has custom built hardware, firmware, and operating systems. These three items are mostly proprietary and are engineered, developed, and assembled under one flagship organization. Apps (Application Software) are developed both by flagship organization and developers from outside the organization. A number of well-recognized mobile operating systems are available in the market in both proprietary and open-source categories. Most widely used mobile operating systems are − Android IOS BlackBerry Windows Every mobile operating system provides their own set of tools and environments to develop apps that will run on them. Application made for one operating system cannot run on any other platform as they are entirely different. Developers tend to cover all major mobile operating systems in order to increase reachability among their users. Thus it becomes a tedious task to develop an application program that may run on all major OS platforms, keeping its look, feel, and functionality identical on all platforms. For this work, a developer needs to understand all platforms and should have a good understanding of major development tools for different operating systems. PhoneGap may be seen as a solution to all problems mentioned above. PhoneGap is a framework that makes the developers develop their apps using standard web APIs for all major mobile operating systems. It is open-source and free. Developers only need to know web development using HTML, CSS and JavaScript. PhoneGap takes care of rest of the work, such as look and feel of the app and portability among various mobile operating systems. Using PhoneGap, one can create apps for all major mobile operating systems like Apple iOS, Android, BlackBerry, Windows etc. This does not require the developer to have an expertise over any of the above mentioned platforms, neither the developer is required to know programming to code the app from scratch. PhoneGap allows its users to upload the data contents on website and it automatically converts it to various App files. In this tutorial, we shall see how to create an app for Apple, android, and windows platform online without using any offline tool. In this chapter, we will learn how to set up basic environment in order to make apps effortlessly. Though PhoneGap supports offline creation of apps using Cordova command line interface and Github repository mechanism, we shall concentrate on minimum effort procedure. We assume that you are well versed with web technologies and have your web application ready to be shipped as an app. Because PhoneGap supports only HTML, CSS and JavaScript, it is mandatory that the application should be created using these technologies only. From a developer’s perspective, an app should have the following items included in its package − Configuration files Icons for app Information or content (built using web technologies) Our web app will need only one configuration file that should be adequate to configure all its necessary settings. Its name is config.xml. This file contains all the necessary information required to compile the app. Let us see config.xml for our example − <?xml version = "1.0" encoding = "UTF-8"?> <widget xmlns = "http://www.w3.org/ns/widgets" xmlns:gap = "http://phonegap.com/ns/1.0" id = "com.tutorialspoint.onlineviewer" version = "1.0"> <name>Tutorials Point</name> <description> Tutorials Point Online Viewer </description> <author href = "http://tutorialspoint.com" email = "contact@tutorialspoint.com"> Tutorials Point </author> <preference name = "permissions" value = "none"/> <icon src = "res/icon/android/drawable-ldpi/tp_icon.png" gap:platform = "android" gap:qualifier = "ldpi" /> <icon src = "res/icon/android/drawable-mdpi/tp_icon.png" gap:platform = "android" gap:qualifier = "mdpi" /> <icon src = "res/icon/android/drawable-hdpi/tp_icon.png" gap:platform = "android" gap:qualifier = "hdpi" /> <icon src = "res/icon/android/drawable-xhdpi/tp_icon.png" gap:platform = "android" gap:qualifier = "xhdpi" /> <icon src = "res/icon/android/drawable-xxhdpi/tp_icon.png" gap:platform = "android" gap:qualifier = "xxhdpi" /> <icon src = "res/icon/ios/Icon-72.png" gap:platform = "ios" gap:qualifier = ""/> <icon src = "res/icon/ios/icon-57.png" gap:platform = "ios" width = "57" height = "57" /> <icon src = "res/icon/ios/icon-72.png" gap:platform = "ios" width = "72" height = "72" /> <icon src = "res/icon/ios/icon-57-2x.png" gap:platform = "ios" width = "114" height = "114" /> <icon src = "res/icon/ios/icon-72-2x.png" gap:platform = "ios" width = "144" height = "144" /> </widget> All configuration contents are wrapped in <widget> tag. Brief description of these is as follows − <widget id = ”app_id”> id is your reserved app-id on various app stores. It is in reverse-domain name style i.e. com.tutorialspoint.onlineviewer etc. <widget version = "x.y.z"> This is version number of app in x.y.z format where (x,y,z) are positive integers i.e. 1.0.0, it represents major.minor.patch version system. <name> App Name</name> This is the name of the app, which will be displayed below the app icon on the mobile screen. Your app can be searched using this name. <description> My First Web App </description> This is a brief description of what the app is about, and what it is. <author> Author_Name </author> This field contains name of the creator or programmer, generally set to the name of organization which is launching this app. <preferences name = "permissions" value = "none"> The preferences tag is used to set various options like FullScreen, BackgroundColor and Orientation for app. These options are in name and value pair. For example: name = "FullScreen" value = "true" etc. Because we do not require any of these advance settings, we just put permissions to none. <icon> Allows us to add icons to our apps. It can be coded in various ways, but since we are learning short-cut of everything, so here it is. The .src determines the path of icon image. The gap:platform determines for which OS platform this icon is to be used. The gap:qualifier is density that is used by android devices. The iOS devices use width & height parameters. There are devices of various sizes having same mobile operating system, so to target an audience of one platform you need to furnish icons of all the mobiles types too. It is important that we prepare icons of exact shapes and sizes as required by particular mobile operating system. Here we are using the folders res/icon/ios and res/icon/android/drawable-xxxx.. To get this work done fast, you can create a logo of size 1024x1024 and log on to makeappicon.com. This website will help you instantly create logos of all sizes for both android and iOS platform. After providing icon image of size 1024x1024, makeappicon.com should provide the following − Icons for iOS Icons for Android This website provides you with an option to email all the logos in zip format to your doorstep (a.k.a. email, of course!) Offline websites are copied to local hard drive and accessed whenever the user needs to without any internet connection. Likewise, this offline web app will let you create a web application that is downloaded to its entirety to the mobile devices of a user who can access that offline. An application for this type of app may include app having collection of stories, short tutorials or any other offline content of users' interest, which he/she can read offline even when internet is not available. The following image represents the folder structure for offline app. At root directory it requires only two files, config.xml and index.xml. The config.xml contains app configuration settings which we learnt in previous section. The index.html file contains homepage of web contents. One important thing to learn here is that all links inside all html files should contain relative path only. That is, no absolute path or base href tag should be there. The following image shows folder structure for our app to be in online mode. In online mode, entire web content is loaded from internet website. You may notice that data folder is missing in online mode app, because all the files reside on the actual server and are accessible via internet. The index.html file contains actual links as it contains at the web server and all its links are either absolute or used with base href tag. After you have decided the mode of your app and organized its files in the file structure mentioned above, you need to zip your file with any standard zip tool and save it. We shall use this file in the next section. It is essential for any app to be signed by its developers or developing organization to keep things in order. For this reason, you need to sign your app. You may need keytool which is a part of standard java distribution. Execute the following command in %JAVA_HOME% in your Windows command prompt or Linux Shell − keytool -genkey -v -keystore my_keystore.keystore -alias TutorialsPoint -keyalg RSA -keysize 2048 -validity 10000 This should generate my_keystore.keystore file, which we shall need in the next section. Now we are ready to compile our first web API-based quick mode app. In this final segment, we shall learn about the process of transforming our web contents to an app format, which can be uploaded on online app stores. PhoneGap accepts user login created on GitHub or using AdobeID. GitHub is a repository service where users can upload their contents and use them by providing their URL references. For example, the content we just created can be uploaded to GitHub and then call it directly to PhoneGap. The following steps detail how to create an Adobe ID. Go to www.build.phonegap.com and click on Register A new window will open as displayed below − Fill in your details and click on sign up. You can now login with the same user id to PhoneGap. By default, this page should lead to PhoneGap console as displayed below − Click ‘Upload a .zip file’ and upload the .zip file we created, which has the entire web content and configurations. You should see the following window after successful upload − You may instantly see that iOS app has failed its processing as we have not provided any signed key. We are only concentrating on Android and you can see that it has been created by PhoneGap. This app cannot be uploaded to google store as it is not signed by key. Click on the Android icon and the following screen should appear − Click on drop-down option menu next to Android icon that reads No key selected, click on add a key and the following screen should appear − Provide title and alias of your choice and click on Keystore file. Provide the keystore file created in the last section. Then click on 'Rebuild' button next to it. The app built by this process can be directly uploaded to Google Play. Click on .apk file and you can download your first web-based free app. Before uploading, app should be tested on either virtual or real devices. Print Add Notes Bookmark this page
[ { "code": null, "e": 2046, "s": 1687, "text": "Mobile, handhelds and easy-to-carry devices have started a new revolution in software engineering. These small but efficient devices are capable to run applications created with high-end programming languages. People who own these devices tend to use them at their maximum as these devices such as mobile phones, are very convenient to use anytime, anywhere." }, { "code": null, "e": 2186, "s": 2046, "text": "The architecture of a mobile device is similar to that of a computer system. It has custom built hardware, firmware, and operating systems." }, { "code": null, "e": 2423, "s": 2186, "text": "These three items are mostly proprietary and are engineered, developed, and assembled under one flagship organization. Apps (Application Software) are developed both by flagship organization and developers from outside the organization." }, { "code": null, "e": 2600, "s": 2423, "text": "A number of well-recognized mobile operating systems are available in the market in both proprietary and open-source categories. Most widely used mobile operating systems are −" }, { "code": null, "e": 2608, "s": 2600, "text": "Android" }, { "code": null, "e": 2612, "s": 2608, "text": "IOS" }, { "code": null, "e": 2623, "s": 2612, "text": "BlackBerry" }, { "code": null, "e": 2631, "s": 2623, "text": "Windows" }, { "code": null, "e": 2969, "s": 2631, "text": "Every mobile operating system provides their own set of tools and environments to develop apps that will run on them. Application made for one operating system cannot run on any other platform as they are entirely different. Developers tend to cover all major mobile operating systems in order to increase reachability among their users." }, { "code": null, "e": 3302, "s": 2969, "text": "Thus it becomes a tedious task to develop an application program that may run on all major OS platforms, keeping its look, feel, and functionality identical on all platforms. For this work, a developer needs to understand all platforms and should have a good understanding of major development tools for different operating systems." }, { "code": null, "e": 3531, "s": 3302, "text": "PhoneGap may be seen as a solution to all problems mentioned above. PhoneGap is a framework that makes the developers develop their apps using standard web APIs for all major mobile operating systems. It is open-source and free." }, { "code": null, "e": 3738, "s": 3531, "text": "Developers only need to know web development using HTML, CSS and JavaScript. PhoneGap takes care of rest of the work, such as look and feel of the app and portability among various mobile operating systems." }, { "code": null, "e": 4047, "s": 3738, "text": "Using PhoneGap, one can create apps for all major mobile operating systems like Apple iOS, Android, BlackBerry, Windows etc. This does not require the developer to have an expertise over any of the above mentioned platforms, neither the developer is required to know programming to code the app from scratch." }, { "code": null, "e": 4167, "s": 4047, "text": "PhoneGap allows its users to upload the data contents on website and it automatically converts it to various App files." }, { "code": null, "e": 4299, "s": 4167, "text": "In this tutorial, we shall see how to create an app for Apple, android, and windows platform online without using any offline tool." }, { "code": null, "e": 4568, "s": 4299, "text": "In this chapter, we will learn how to set up basic environment in order to make apps effortlessly. Though PhoneGap supports offline creation of apps using Cordova command line interface and Github repository mechanism, we shall concentrate on minimum effort procedure." }, { "code": null, "e": 4829, "s": 4568, "text": "We assume that you are well versed with web technologies and have your web application ready to be shipped as an app. Because PhoneGap supports only HTML, CSS and JavaScript, it is mandatory that the application should be created using these technologies only." }, { "code": null, "e": 4926, "s": 4829, "text": "From a developer’s perspective, an app should have the following items included in its package −" }, { "code": null, "e": 4946, "s": 4926, "text": "Configuration files" }, { "code": null, "e": 4960, "s": 4946, "text": "Icons for app" }, { "code": null, "e": 5014, "s": 4960, "text": "Information or content (built using web technologies)" }, { "code": null, "e": 5231, "s": 5014, "text": "Our web app will need only one configuration file that should be adequate to configure all its necessary settings. Its name is config.xml. This file contains all the necessary information required to compile the app." }, { "code": null, "e": 5271, "s": 5231, "text": "Let us see config.xml for our example −" }, { "code": null, "e": 6850, "s": 5271, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<widget xmlns = \"http://www.w3.org/ns/widgets\" \n xmlns:gap = \"http://phonegap.com/ns/1.0\" id = \"com.tutorialspoint.onlineviewer\" version = \"1.0\">\n \n <name>Tutorials Point</name>\n \n <description>\n Tutorials Point Online Viewer\n </description>\n \n <author href = \"http://tutorialspoint.com\" email = \"contact@tutorialspoint.com\">\n Tutorials Point\n </author>\n \n <preference name = \"permissions\" value = \"none\"/>\n \n <icon src = \"res/icon/android/drawable-ldpi/tp_icon.png\" \n gap:platform = \"android\" gap:qualifier = \"ldpi\" />\n\t\t\n <icon src = \"res/icon/android/drawable-mdpi/tp_icon.png\" \n gap:platform = \"android\" gap:qualifier = \"mdpi\" />\n\t\t\n <icon src = \"res/icon/android/drawable-hdpi/tp_icon.png\" \n gap:platform = \"android\" gap:qualifier = \"hdpi\" />\n\t\t\n <icon src = \"res/icon/android/drawable-xhdpi/tp_icon.png\" \n gap:platform = \"android\" gap:qualifier = \"xhdpi\" />\n\t\t\n <icon src = \"res/icon/android/drawable-xxhdpi/tp_icon.png\" \n gap:platform = \"android\" gap:qualifier = \"xxhdpi\" />\n \n <icon src = \"res/icon/ios/Icon-72.png\" gap:platform = \"ios\" gap:qualifier = \"\"/>\n <icon src = \"res/icon/ios/icon-57.png\" gap:platform = \"ios\" width = \"57\" height = \"57\" />\n <icon src = \"res/icon/ios/icon-72.png\" gap:platform = \"ios\" width = \"72\" height = \"72\" />\n <icon src = \"res/icon/ios/icon-57-2x.png\" gap:platform = \"ios\" width = \"114\" height = \"114\" />\n <icon src = \"res/icon/ios/icon-72-2x.png\" gap:platform = \"ios\" width = \"144\" height = \"144\" />\n \n</widget>" }, { "code": null, "e": 6949, "s": 6850, "text": "All configuration contents are wrapped in <widget> tag. Brief description of these is as follows −" }, { "code": null, "e": 6972, "s": 6949, "text": "<widget id = ”app_id”>" }, { "code": null, "e": 7099, "s": 6972, "text": "id is your reserved app-id on various app stores. It is in reverse-domain name style i.e. com.tutorialspoint.onlineviewer etc." }, { "code": null, "e": 7126, "s": 7099, "text": "<widget version = \"x.y.z\">" }, { "code": null, "e": 7268, "s": 7126, "text": "This is version number of app in x.y.z format where (x,y,z) are positive integers i.e. 1.0.0, it represents major.minor.patch version system." }, { "code": null, "e": 7291, "s": 7268, "text": "<name> App Name</name>" }, { "code": null, "e": 7427, "s": 7291, "text": "This is the name of the app, which will be displayed below the app icon on the mobile screen. Your app can be searched using this name." }, { "code": null, "e": 7473, "s": 7427, "text": "<description> My First Web App </description>" }, { "code": null, "e": 7543, "s": 7473, "text": "This is a brief description of what the app is about, and what it is." }, { "code": null, "e": 7574, "s": 7543, "text": "<author> Author_Name </author>" }, { "code": null, "e": 7700, "s": 7574, "text": "This field contains name of the creator or programmer, generally set to the name of organization which is launching this app." }, { "code": null, "e": 7750, "s": 7700, "text": "<preferences name = \"permissions\" value = \"none\">" }, { "code": null, "e": 8044, "s": 7750, "text": "The preferences tag is used to set various options like FullScreen, BackgroundColor and Orientation for app. These options are in name and value pair. For example: name = \"FullScreen\" value = \"true\" etc. Because we do not require any of these advance settings, we just put permissions to none." }, { "code": null, "e": 8051, "s": 8044, "text": "<icon>" }, { "code": null, "e": 8414, "s": 8051, "text": "Allows us to add icons to our apps. It can be coded in various ways, but since we are\nlearning short-cut of everything, so here it is. The .src determines the path of icon image. The gap:platform determines for which OS platform this icon is to be used. The gap:qualifier is density that is used by android devices. The iOS devices use width & height parameters." }, { "code": null, "e": 8698, "s": 8414, "text": "There are devices of various sizes having same mobile operating system, so to target an audience of one platform you need to furnish icons of all the mobiles types too. It is important that we prepare icons of exact shapes and sizes as required by particular mobile operating system." }, { "code": null, "e": 8778, "s": 8698, "text": "Here we are using the folders res/icon/ios and res/icon/android/drawable-xxxx.." }, { "code": null, "e": 8975, "s": 8778, "text": "To get this work done fast, you can create a logo of size 1024x1024 and log on to makeappicon.com. This website will help you instantly create logos of all sizes for both android and iOS platform." }, { "code": null, "e": 9068, "s": 8975, "text": "After providing icon image of size 1024x1024, makeappicon.com should provide the following −" }, { "code": null, "e": 9082, "s": 9068, "text": "Icons for iOS" }, { "code": null, "e": 9100, "s": 9082, "text": "Icons for Android" }, { "code": null, "e": 9222, "s": 9100, "text": "This website provides you with an option to email all the logos in zip format to your doorstep (a.k.a. email, of course!)" }, { "code": null, "e": 9508, "s": 9222, "text": "Offline websites are copied to local hard drive and accessed whenever the user needs to without any internet connection. Likewise, this offline web app will let you create a web application that is downloaded to its entirety to the mobile devices of a user who can access that offline." }, { "code": null, "e": 9722, "s": 9508, "text": "An application for this type of app may include app having collection of stories, short tutorials or any other offline content of users' interest, which he/she can read offline even when internet is not available." }, { "code": null, "e": 9863, "s": 9722, "text": "The following image represents the folder structure for offline app. At root directory it requires only two files, config.xml and index.xml." }, { "code": null, "e": 10006, "s": 9863, "text": "The config.xml contains app configuration settings which we learnt in previous section. The index.html file contains homepage of web contents." }, { "code": null, "e": 10175, "s": 10006, "text": "One important thing to learn here is that all links inside all html files should contain relative path only. That is, no absolute path or base href tag should be there." }, { "code": null, "e": 10320, "s": 10175, "text": "The following image shows folder structure for our app to be in online mode. In online mode, entire web content is loaded from internet website." }, { "code": null, "e": 10607, "s": 10320, "text": "You may notice that data folder is missing in online mode app, because all the files reside on the actual server and are accessible via internet. The index.html file contains actual links as it contains at the web server and all its links are either absolute or used with base href tag." }, { "code": null, "e": 10824, "s": 10607, "text": "After you have decided the mode of your app and organized its files in the file structure mentioned above, you need to zip your file with any standard zip tool and save it. We shall use this file in the next section." }, { "code": null, "e": 11047, "s": 10824, "text": "It is essential for any app to be signed by its developers or developing organization to keep things in order. For this reason, you need to sign your app. You may need keytool which is a part of standard java distribution." }, { "code": null, "e": 11140, "s": 11047, "text": "Execute the following command in %JAVA_HOME% in your Windows command prompt or Linux Shell −" }, { "code": null, "e": 11259, "s": 11140, "text": "keytool -genkey -v -keystore my_keystore.keystore \n -alias TutorialsPoint -keyalg RSA -keysize 2048 -validity 10000\n" }, { "code": null, "e": 11348, "s": 11259, "text": "This should generate my_keystore.keystore file, which we shall need in the next section." }, { "code": null, "e": 11567, "s": 11348, "text": "Now we are ready to compile our first web API-based quick mode app. In this final segment, we shall learn about the process of transforming our web contents to an app format, which can be uploaded on online app stores." }, { "code": null, "e": 11854, "s": 11567, "text": "PhoneGap accepts user login created on GitHub or using AdobeID. GitHub is a repository service where users can upload their contents and use them by providing their URL references. For example, the content we just created can be uploaded to GitHub and then call it directly to PhoneGap." }, { "code": null, "e": 11908, "s": 11854, "text": "The following steps detail how to create an Adobe ID." }, { "code": null, "e": 11959, "s": 11908, "text": "Go to www.build.phonegap.com and click on Register" }, { "code": null, "e": 12003, "s": 11959, "text": "A new window will open as displayed below −" }, { "code": null, "e": 12174, "s": 12003, "text": "Fill in your details and click on sign up. You can now login with the same user id to PhoneGap. By default, this page should lead to PhoneGap console as displayed below −" }, { "code": null, "e": 12353, "s": 12174, "text": "Click ‘Upload a .zip file’ and upload the .zip file we created, which has the entire web content and configurations. You should see the following window after successful upload −" }, { "code": null, "e": 12617, "s": 12353, "text": "You may instantly see that iOS app has failed its processing as we have not provided any signed key. We are only concentrating on Android and you can see that it has been created by PhoneGap. This app cannot be uploaded to google store as it is not signed by key." }, { "code": null, "e": 12684, "s": 12617, "text": "Click on the Android icon and the following screen should appear −" }, { "code": null, "e": 12824, "s": 12684, "text": "Click on drop-down option menu next to Android icon that reads No key selected, click on add a key and the following screen should appear −" }, { "code": null, "e": 12989, "s": 12824, "text": "Provide title and alias of your choice and click on Keystore file. Provide the keystore file created in the last section. Then click on 'Rebuild' button next to it." }, { "code": null, "e": 13131, "s": 12989, "text": "The app built by this process can be directly uploaded to Google Play. Click on .apk file and you can download your first web-based free app." }, { "code": null, "e": 13205, "s": 13131, "text": "Before uploading, app should be tested on either virtual or real devices." }, { "code": null, "e": 13212, "s": 13205, "text": " Print" }, { "code": null, "e": 13223, "s": 13212, "text": " Add Notes" } ]
Using The Predictive Power Score in R | by Luca Zavarella | Towards Data Science
In recent months Florian Wetschoreck published a story on Toward Data Science’s Medium channel that attracted the attention of many data scientists on LinkedIn thanks to its very provocative title: “RIP correlation. Introducing the Predictive Power Score”. Let’s see what it is and how to use it in R. The Predictive Power Score (PPS) is a normalized index (it ranges from 0 to 1) that tells us how much the variable x (be it numerical or categorical) could be used to predict the variable y (numerical or categorical). The higher the PPS index, the more the variable x is decisive in predicting the variable y. The conceptual similarity of PPS with the correlation coefficient is evident, although the following differences exist: PPS also detects non-linear relationships between x and y. PPS is not a symmetrical index. This means that PPS(x, y) ≠ PPS(y, x). In other words, it is not said that if x predicts y, then y also predicts x. PPS allows both numerical and categorical variables. Basically, PPS is an asymmetric nonlinear index that is applicable to all types of variables for predictive purposes. Behind the scene it implements Decision Trees as learning algorithms due to their robustness to outliers and poor data pre-processing. The score is calculated on the test sets of a default of 4-fold cross-validation given by the scikit-learn cross_val_score function and it is given by different metrics according to the type of problem (regression or classification) defined by the target variable: Regression: Mean Absolute Error (MAE) normalized to the [0, 1] interval given a baseline of “naïve” values of y calculated as the median of the target variable. Classification: Weighted F1 normalized to the [0, 1] interval given a baseline of “naïve” values of y calculated as the most common value of the target variable or a random value (sometimes, a random value has a higher F1 than the most common value). You can get into the details of the Python code thanks to the fact that the Predictive Power Score project was released as open source on Github. The two indexes come from different domains and fundamental distinctions must be made: Pearson correlation is given by the normalized covariance between two numerical variables. Covariance depends on the deviations of the two variables from their respective means, so it’s a statistical measure. Given two numerical variables, Pearson correlation is a descriptive index well defined mathematically that gives the goodness-of-fit for the best possible linear function describing the relation between the variables. PPS tries to solve the issues of only linear correlations and only numeric variables being measured in a correlation analysis by applying decision tree estimation. It is derived from performance metrics of that estimation. At the time this post was written (version 1.1.0), it gets by default a random sample (stratified if needed) of 5000 rows from the input dataset in order to speed up the calculations (the size of the sample can be modified using a proper parameter). No tuning is done to get the optimal model parameters for the decision tree. There is therefore the possibility of overfitting or underfitting. Moreover, PPS results could be different at each run over the same dataset due to the randomness inherent to the algorithm (random seed could be used to guarantee the reproducibility of results). So, PPS could be inaccurate. But its aim is not to give an exact score, rather the general notion of dependency and a fast result. Both the indexes should be used during the Exploration Data Analysis phase. As the same author says: The PPS clearly has some advantages over correlation for finding predictive patterns in the data. However, once the patterns are found, the correlation is still a great way of communicating found linear relationships. The author lists several use cases in his article where PPS may add value: Finds every relationship that the correlation finds and more Feature selection Detect information leakage Find entity structures in the data via interpreting the PPS matrix as a directed graph. UPDATE: An R-specific package has been developed in late December 2020: https://github.com/paulvanderlaken/ppsr As mentioned before, the project ppscore is open sourced and it’s developed in Python. There is currently no porting project of ppscore in R. So how to use the ppscore functions in an R script? It’s possible to use the prowess of R along with the programming capabilities of Python and vice-versa thanks to some libraries created for interoperability between Python and R. Among the others, two of them are the most widely used: rpy2: an interface to R running embedded in a Python process reticulate: a comprehensive set of tools for interoperability between Python and R thanks to embedded session of Python within R sessions In our scenario, reticulate will allow ppscore functions to be called from an R script. First of all, if you didn’t install Python on your machine, I suggest to install Miniconda (a small, bootstrap version of Anaconda that includes only conda, Python, and few other useful packages), letting the installer add the Python installation path to your PATH environment variable in case of a Windows machine. Python developers usually use virtual environments. A virtual environment is a tool that helps to keep dependencies required by different projects separated by creating self-contained directory trees that contain Python installations for particular versions of Python, plus a number of additional packages. Conda is a tool that helps to manage environments and packages. In this case a new Python environment will be created in order to install the ppscore required packages on it. You can use the following R script to prepare a new Python environment for the ppscore library: # Install reticulateif( !require(reticulate) ) { install.packages("reticulate")}# Load reticulatelibrary(reticulate)# List current python environmentsconda_list()# Create a new environemnt called 'test_ppscore'conda_create(envname = "test_ppscore")# Install the ppscore package and its dependencies using pip into the test_ppscore environment.# Requirements are listed here: https://github.com/8080labs/ppscore/blob/master/requirements.txtconda_install(envname = "test_ppscore", packages = "pandas", pip = TRUE)conda_install(envname = "test_ppscore", packages = "scikit-learn", pip = TRUE)conda_install(envname = "test_ppscore", packages = "ppscore", pip = TRUE)# Check if the new environment is now listedconda_list()# Make sure to use the new environmentuse_condaenv("test_ppscore")# Import the ppscore Python module in your R sessionpps <- import(module = "ppscore") Functions and other data within Python modules and classes can be accessed via the $ operator (as well as interacting with an R list). Imported Python modules support code completion and inline help. For example, the matrix function in the pps module can be accessed as follows: If you want to learn more about reticulate, you can go through its home page. Starting from the example the author included in the repository, it’s possible to replicate the Titanic PPScore Heatmap using the matrix function: The Variable Importance given the target “Survived” is obtainable filtering properly the output (complete interaction between predictors) given by the matrix function. But it is also possible to use directly the predictor function to directly have the same result, being careful to use the same random_seed parameter within both functions, in order to avoid to obtain different results. The Variable Importance plot given the target variable “Survived” is the following: The R code used to get the above plots is the following: library(reticulate)library(readr)library(dplyr)library(ggplot2)heatmap <- function(df, x, y, value, main_title = "Heatmap", legend_title = "Value", x_title = "feature", y_title = "target") { x_quo <- enquo(x) y_quo <- enquo(y) value_quo <- enquo(value) res <- ggplot( df, aes(x = !!x_quo, y = !!y_quo, fill = !!value_quo) ) + geom_tile(color = "white") + scale_fill_gradient2(low = "white", high = "steelblue", limit = c(0,1), space = "Lab", name="PPScore") + theme_minimal()+ # minimal theme # theme(axis.text.x = element_text(angle = 45, vjust = 1, # size = 12, hjust = 1)) + coord_fixed() + geom_text(aes(x, y, label = round(!!value_quo, 2)), color = "black", size = 4) + theme( axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1), axis.text.y = element_text(size = 12), panel.grid.major = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.ticks = element_blank() ) + xlab(x_title) + ylab(y_title) + labs(fill = legend_title) + guides(fill = guide_colorbar(barwidth = 1, barheight = 10, title.position = "top", title.hjust = 1)) + ggtitle(main_title) return(res) }lollipop <- function(df, x, y, main_title = "Variable Importance", x_title = "PPScore", y_title = "Predictors", caption_title = "Data from Titanic dataset") { x_quo <- enquo(x) y_quo <- enquo(y) res <- ggplot(df, aes(x=!!x_quo, y=forcats::fct_reorder(!!y_quo, !!x_quo, .desc=FALSE))) + geom_segment( aes(x = 0, y=forcats::fct_reorder(!!y_quo, !!x_quo, .desc=FALSE), xend = !!x_quo, yend = forcats::fct_reorder(!!y_quo, !!x_quo, .desc=FALSE)), color = "gray50") + geom_point( color = "darkorange" ) + labs(x = x_title, y = y_title, title = main_title, #subtitle = "subtitle", caption = caption_title) + theme_minimal() + geom_text(aes(label=round(!!x_quo, 2)), hjust=-.5, size = 3.5 ) + theme(panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(), axis.text.x = element_blank()) return(res) }df <- read_csv("https://raw.githubusercontent.com/8080labs/ppscore/master/examples/titanic.csv")df <- df %>% mutate( Survived = as.factor(Survived) ) %>% mutate( across(where(is.character), as.factor) ) %>% select( Survived, Class = Pclass, Sex, Age, TicketID = Ticket, TicketPrice = Fare, Port = Embarked )use_condaenv("test_ppscore")pps <- import(module = "ppscore")# PPScore heatmapscore <- pps$matrix(df = df, random_seed = 1234L)score %>% heatmap(x = x, y = y, value = ppscore, main_title = "PPScore for Titanic's predictors", legend_title = "PPScore")# Variable importancevi <- pps$predictors( df = df, y = "Survived", random_seed = 1234L)vi %>% mutate( x = as.factor(x) ) %>% lollipop( ppscore, x, main_title = "Variable Importance for target = 'Survived'", x_title = "PPScore", y_title = "Predictors", caption_title = "Data from Titanic dataset") Denis Boigelot published a quite famous picture about Pearson correlation examples on Wikimedia Commons, sharing also the R code used to get this picture: Starting from that code, it’s possible to calculate the PPScore for the same distributions. Here the results for X→Y: Here the results for Y→X: It’s clear that at the time this post was written PPScore struggles to identify linear relationships in presence of even minimal dispersion of the points from the line of origin (as highlighted in yellow and red in previous pictures). These cases show how important it is also to use a correlation index to check linearity in order not to run into wrong conclusions. I shared these results with the author and he confirmed they are studying a solution to solve linear relationships issues. He also shared the reasons why PPScore 1.1.0 doesn’t work well with linear relationships at this link. Conversely, PPScore provides good results on some distributions for which Pearson correlation was not sufficient (as highlighted in green in previous pictures). The R code used to get the above Boigelot distributions is the following: # Install packagespkgs <- c("dplyr","ggplot2","ggpubr","mvtnorm")for (pkg in pkgs) { if (! (pkg %in% rownames(installed.packages()))) { install.packages(pkg) }}# Load packageslibrary(mvtnorm)library(dplyr)library(ggplot2)library(ggpubr)library(reticulate)# FunctionsMyPlot <- function(xy, xlim = c(-4, 4), ylim = c(-4, 4), eps = 1e-15, metric = c("cor", "ppsxy", "ppsyx")) { metric <- metric[1] df <- as.data.frame(xy) names(df) <- c("x", "y") if (metric == "cor") { value <- round(cor(xy[,1], xy[,2]), 1) if (sd(xy[,2]) < eps) { #title <- bquote("corr = " * "undef") # corr. coeff. is undefined title <- paste0("corr = NA") # corr. coeff. is undefined } else { #title <- bquote("corr = " * .(value)) title <- paste0("corr = ", value) } subtitle <- NULL } else if (metric == "ppsxy") { pps_df <- pps$matrix(df = df, random_seed = 1111L) value <- pps_df %>% filter( x == "x" & y == "y" ) %>% mutate( ppscore = round(ppscore, 1) ) %>% pull(ppscore) title <- bquote("pps"[X%->%Y] * " = " * .(value)) subtitle <- NULL } else if (metric == "ppsyx") { pps_df <- pps$matrix(df = df, random_seed = 1111L) value <- pps_df %>% filter( x == "y" & y == "x" ) %>% mutate( ppscore = round(ppscore, 1) ) %>% pull(ppscore) title <- bquote("pps"[Y%->%X] * " = " * .(value)) subtitle <- NULL } ggplot(df, aes(x, y)) + geom_point( color = "darkblue", size = 0.2 ) + xlim(xlim) + ylim(ylim) + labs(title = title, subtitle = subtitle) + theme_void() + theme( plot.title = element_text(size = 10, hjust = .5) ) }MvNormal <- function(n = 1000, cor = 0.8, metric = c("cor", "ppsxy", "ppsyx")) { metric <- metric[1] res <- list() j <- 0 for (i in cor) { sd <- matrix(c(1, i, i, 1), ncol = 2) x <- rmvnorm(n, c(0, 0), sd) j <- j + 1 name <- paste0("p", j) res[[name]] <- MyPlot(x, metric = metric) } return(res)}rotation <- function(t, X) return(X %*% matrix(c(cos(t), sin(t), -sin(t), cos(t)), ncol = 2))RotNormal <- function(n = 1000, t = pi/2, metric = c("cor", "ppsxy", "ppsyx")) { metric <- metric[1] sd <- matrix(c(1, 1, 1, 1), ncol = 2) x <- rmvnorm(n, c(0, 0), sd) res <- list() j <- 0 for (i in t) { j <- j + 1 name <- paste0("p", j) res[[name]] <- MyPlot(rotation(i, x), metric = metric) } return(res)}Others <- function(n = 1000, metric = c("cor", "ppsxy", "ppsyx")) { metric <- metric[1] res <- list() x <- runif(n, -1, 1) y <- 4 * (x^2 - 1/2)^2 + runif(n, -1, 1)/3 res[["p1"]] <- MyPlot(cbind(x,y), xlim = c(-1, 1), ylim = c(-1/3, 1+1/3), metric = metric) y <- runif(n, -1, 1) xy <- rotation(-pi/8, cbind(x,y)) lim <- sqrt(2+sqrt(2)) / sqrt(2) res[["p2"]] <- MyPlot(xy, xlim = c(-lim, lim), ylim = c(-lim, lim), metric = metric) xy <- rotation(-pi/8, xy) res[["p3"]] <- MyPlot(xy, xlim = c(-sqrt(2), sqrt(2)), ylim = c(-sqrt(2), sqrt(2)), metric = metric) y <- 2*x^2 + runif(n, -1, 1) res[["p4"]] <- MyPlot(cbind(x,y), xlim = c(-1, 1), ylim = c(-1, 3), metric = metric) y <- (x^2 + runif(n, 0, 1/2)) * sample(seq(-1, 1, 2), n, replace = TRUE) res[["p5"]] <- MyPlot(cbind(x,y), xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5), metric = metric) y <- cos(x*pi) + rnorm(n, 0, 1/8) x <- sin(x*pi) + rnorm(n, 0, 1/8) res[["p6"]] <- MyPlot(cbind(x,y), xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5), metric = metric) xy1 <- rmvnorm(n/4, c( 3, 3)) xy2 <- rmvnorm(n/4, c(-3, 3)) xy3 <- rmvnorm(n/4, c(-3, -3)) xy4 <- rmvnorm(n/4, c( 3, -3)) res[["p7"]] <- MyPlot(rbind(xy1, xy2, xy3, xy4), xlim = c(-3-4, 3+4), ylim = c(-3-4, 3+4), metric = metric) return(res)}output <- function( metric = c("cor", "ppsxy", "ppsyx") ) { metric <- metric[1] plots1 <- MvNormal( n = 800, cor = c(1.0, 0.8, 0.4, 0.0, -0.4, -0.8, -1.0), metric = metric ); plots2 <- RotNormal(200, c(0, pi/12, pi/6, pi/4, pi/2-pi/6, pi/2-pi/12, pi/2), metric = metric); plots3 <- Others(800, metric = metric) ggarrange( plots1$p1, plots1$p2, plots1$p3, plots1$p4, plots1$p5, plots1$p6, plots1$p7, plots2$p1, plots2$p2, plots2$p3, plots2$p4, plots2$p5, plots2$p6, plots2$p7, plots3$p1, plots3$p2, plots3$p3, plots3$p4, plots3$p5, plots3$p6, plots3$p7, ncol = 7, nrow = 3 ) }#-- Main -------------------------------------use_condaenv("test_ppscore")pps <- import(module = "ppscore")output( metric = "cor" )output( metric = "ppsxy" )output( metric = "ppsyx" ) The Predictive Power Score (PPS) index proposed by Florian Wetschoreck tries to help data scientists in giving a hint to find any kind of relationship between two variables during the EDA phase of a project, being them numerical or categorical. PPS could be inaccurate, but its aim is not to give an exact score, rather the general notion of dependency between two variables and a fast result. Using the Boigelot distributions, it was shown that PPS (the current version is 1.1.0) is able to identify non-linear relationships not identified by the correlation index. Conversely, PPS seems to struggle to identify linear relationships in presence of even minimal dispersion of the points from the line of origin. Although PPScore was developed in Python, its functions can also be used in an R script thanks to reticulate. All the code can be found on this Github repository.
[ { "code": null, "e": 474, "s": 172, "text": "In recent months Florian Wetschoreck published a story on Toward Data Science’s Medium channel that attracted the attention of many data scientists on LinkedIn thanks to its very provocative title: “RIP correlation. Introducing the Predictive Power Score”. Let’s see what it is and how to use it in R." }, { "code": null, "e": 784, "s": 474, "text": "The Predictive Power Score (PPS) is a normalized index (it ranges from 0 to 1) that tells us how much the variable x (be it numerical or categorical) could be used to predict the variable y (numerical or categorical). The higher the PPS index, the more the variable x is decisive in predicting the variable y." }, { "code": null, "e": 904, "s": 784, "text": "The conceptual similarity of PPS with the correlation coefficient is evident, although the following differences exist:" }, { "code": null, "e": 963, "s": 904, "text": "PPS also detects non-linear relationships between x and y." }, { "code": null, "e": 1112, "s": 963, "text": "PPS is not a symmetrical index. This means that PPS(x, y) ≠ PPS(y, x). In other words, it is not said that if x predicts y, then y also predicts x." }, { "code": null, "e": 1165, "s": 1112, "text": "PPS allows both numerical and categorical variables." }, { "code": null, "e": 1283, "s": 1165, "text": "Basically, PPS is an asymmetric nonlinear index that is applicable to all types of variables for predictive purposes." }, { "code": null, "e": 1418, "s": 1283, "text": "Behind the scene it implements Decision Trees as learning algorithms due to their robustness to outliers and poor data pre-processing." }, { "code": null, "e": 1683, "s": 1418, "text": "The score is calculated on the test sets of a default of 4-fold cross-validation given by the scikit-learn cross_val_score function and it is given by different metrics according to the type of problem (regression or classification) defined by the target variable:" }, { "code": null, "e": 1845, "s": 1683, "text": "Regression: Mean Absolute Error (MAE) normalized to the [0, 1] interval given a baseline of “naïve” values of y calculated as the median of the target variable." }, { "code": null, "e": 2097, "s": 1845, "text": "Classification: Weighted F1 normalized to the [0, 1] interval given a baseline of “naïve” values of y calculated as the most common value of the target variable or a random value (sometimes, a random value has a higher F1 than the most common value)." }, { "code": null, "e": 2243, "s": 2097, "text": "You can get into the details of the Python code thanks to the fact that the Predictive Power Score project was released as open source on Github." }, { "code": null, "e": 2330, "s": 2243, "text": "The two indexes come from different domains and fundamental distinctions must be made:" }, { "code": null, "e": 2757, "s": 2330, "text": "Pearson correlation is given by the normalized covariance between two numerical variables. Covariance depends on the deviations of the two variables from their respective means, so it’s a statistical measure. Given two numerical variables, Pearson correlation is a descriptive index well defined mathematically that gives the goodness-of-fit for the best possible linear function describing the relation between the variables." }, { "code": null, "e": 3701, "s": 2757, "text": "PPS tries to solve the issues of only linear correlations and only numeric variables being measured in a correlation analysis by applying decision tree estimation. It is derived from performance metrics of that estimation. At the time this post was written (version 1.1.0), it gets by default a random sample (stratified if needed) of 5000 rows from the input dataset in order to speed up the calculations (the size of the sample can be modified using a proper parameter). No tuning is done to get the optimal model parameters for the decision tree. There is therefore the possibility of overfitting or underfitting. Moreover, PPS results could be different at each run over the same dataset due to the randomness inherent to the algorithm (random seed could be used to guarantee the reproducibility of results). So, PPS could be inaccurate. But its aim is not to give an exact score, rather the general notion of dependency and a fast result." }, { "code": null, "e": 3802, "s": 3701, "text": "Both the indexes should be used during the Exploration Data Analysis phase. As the same author says:" }, { "code": null, "e": 4020, "s": 3802, "text": "The PPS clearly has some advantages over correlation for finding predictive patterns in the data. However, once the patterns are found, the correlation is still a great way of communicating found linear relationships." }, { "code": null, "e": 4095, "s": 4020, "text": "The author lists several use cases in his article where PPS may add value:" }, { "code": null, "e": 4156, "s": 4095, "text": "Finds every relationship that the correlation finds and more" }, { "code": null, "e": 4174, "s": 4156, "text": "Feature selection" }, { "code": null, "e": 4201, "s": 4174, "text": "Detect information leakage" }, { "code": null, "e": 4289, "s": 4201, "text": "Find entity structures in the data via interpreting the PPS matrix as a directed graph." }, { "code": null, "e": 4401, "s": 4289, "text": "UPDATE: An R-specific package has been developed in late December 2020: https://github.com/paulvanderlaken/ppsr" }, { "code": null, "e": 4830, "s": 4401, "text": "As mentioned before, the project ppscore is open sourced and it’s developed in Python. There is currently no porting project of ppscore in R. So how to use the ppscore functions in an R script? It’s possible to use the prowess of R along with the programming capabilities of Python and vice-versa thanks to some libraries created for interoperability between Python and R. Among the others, two of them are the most widely used:" }, { "code": null, "e": 4891, "s": 4830, "text": "rpy2: an interface to R running embedded in a Python process" }, { "code": null, "e": 5029, "s": 4891, "text": "reticulate: a comprehensive set of tools for interoperability between Python and R thanks to embedded session of Python within R sessions" }, { "code": null, "e": 5117, "s": 5029, "text": "In our scenario, reticulate will allow ppscore functions to be called from an R script." }, { "code": null, "e": 5433, "s": 5117, "text": "First of all, if you didn’t install Python on your machine, I suggest to install Miniconda (a small, bootstrap version of Anaconda that includes only conda, Python, and few other useful packages), letting the installer add the Python installation path to your PATH environment variable in case of a Windows machine." }, { "code": null, "e": 5804, "s": 5433, "text": "Python developers usually use virtual environments. A virtual environment is a tool that helps to keep dependencies required by different projects separated by creating self-contained directory trees that contain Python installations for particular versions of Python, plus a number of additional packages. Conda is a tool that helps to manage environments and packages." }, { "code": null, "e": 6011, "s": 5804, "text": "In this case a new Python environment will be created in order to install the ppscore required packages on it. You can use the following R script to prepare a new Python environment for the ppscore library:" }, { "code": null, "e": 6882, "s": 6011, "text": "# Install reticulateif( !require(reticulate) ) { install.packages(\"reticulate\")}# Load reticulatelibrary(reticulate)# List current python environmentsconda_list()# Create a new environemnt called 'test_ppscore'conda_create(envname = \"test_ppscore\")# Install the ppscore package and its dependencies using pip into the test_ppscore environment.# Requirements are listed here: https://github.com/8080labs/ppscore/blob/master/requirements.txtconda_install(envname = \"test_ppscore\", packages = \"pandas\", pip = TRUE)conda_install(envname = \"test_ppscore\", packages = \"scikit-learn\", pip = TRUE)conda_install(envname = \"test_ppscore\", packages = \"ppscore\", pip = TRUE)# Check if the new environment is now listedconda_list()# Make sure to use the new environmentuse_condaenv(\"test_ppscore\")# Import the ppscore Python module in your R sessionpps <- import(module = \"ppscore\")" }, { "code": null, "e": 7161, "s": 6882, "text": "Functions and other data within Python modules and classes can be accessed via the $ operator (as well as interacting with an R list). Imported Python modules support code completion and inline help. For example, the matrix function in the pps module can be accessed as follows:" }, { "code": null, "e": 7239, "s": 7161, "text": "If you want to learn more about reticulate, you can go through its home page." }, { "code": null, "e": 7386, "s": 7239, "text": "Starting from the example the author included in the repository, it’s possible to replicate the Titanic PPScore Heatmap using the matrix function:" }, { "code": null, "e": 7773, "s": 7386, "text": "The Variable Importance given the target “Survived” is obtainable filtering properly the output (complete interaction between predictors) given by the matrix function. But it is also possible to use directly the predictor function to directly have the same result, being careful to use the same random_seed parameter within both functions, in order to avoid to obtain different results." }, { "code": null, "e": 7857, "s": 7773, "text": "The Variable Importance plot given the target variable “Survived” is the following:" }, { "code": null, "e": 7914, "s": 7857, "text": "The R code used to get the above plots is the following:" }, { "code": null, "e": 11351, "s": 7914, "text": "library(reticulate)library(readr)library(dplyr)library(ggplot2)heatmap <- function(df, x, y, value, main_title = \"Heatmap\", legend_title = \"Value\", x_title = \"feature\", y_title = \"target\") { x_quo <- enquo(x) y_quo <- enquo(y) value_quo <- enquo(value) res <- ggplot( df, aes(x = !!x_quo, y = !!y_quo, fill = !!value_quo) ) + geom_tile(color = \"white\") + scale_fill_gradient2(low = \"white\", high = \"steelblue\", limit = c(0,1), space = \"Lab\", name=\"PPScore\") + theme_minimal()+ # minimal theme # theme(axis.text.x = element_text(angle = 45, vjust = 1, # size = 12, hjust = 1)) + coord_fixed() + geom_text(aes(x, y, label = round(!!value_quo, 2)), color = \"black\", size = 4) + theme( axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1), axis.text.y = element_text(size = 12), panel.grid.major = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.ticks = element_blank() ) + xlab(x_title) + ylab(y_title) + labs(fill = legend_title) + guides(fill = guide_colorbar(barwidth = 1, barheight = 10, title.position = \"top\", title.hjust = 1)) + ggtitle(main_title) return(res) }lollipop <- function(df, x, y, main_title = \"Variable Importance\", x_title = \"PPScore\", y_title = \"Predictors\", caption_title = \"Data from Titanic dataset\") { x_quo <- enquo(x) y_quo <- enquo(y) res <- ggplot(df, aes(x=!!x_quo, y=forcats::fct_reorder(!!y_quo, !!x_quo, .desc=FALSE))) + geom_segment( aes(x = 0, y=forcats::fct_reorder(!!y_quo, !!x_quo, .desc=FALSE), xend = !!x_quo, yend = forcats::fct_reorder(!!y_quo, !!x_quo, .desc=FALSE)), color = \"gray50\") + geom_point( color = \"darkorange\" ) + labs(x = x_title, y = y_title, title = main_title, #subtitle = \"subtitle\", caption = caption_title) + theme_minimal() + geom_text(aes(label=round(!!x_quo, 2)), hjust=-.5, size = 3.5 ) + theme(panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(), axis.text.x = element_blank()) return(res) }df <- read_csv(\"https://raw.githubusercontent.com/8080labs/ppscore/master/examples/titanic.csv\")df <- df %>% mutate( Survived = as.factor(Survived) ) %>% mutate( across(where(is.character), as.factor) ) %>% select( Survived, Class = Pclass, Sex, Age, TicketID = Ticket, TicketPrice = Fare, Port = Embarked )use_condaenv(\"test_ppscore\")pps <- import(module = \"ppscore\")# PPScore heatmapscore <- pps$matrix(df = df, random_seed = 1234L)score %>% heatmap(x = x, y = y, value = ppscore, main_title = \"PPScore for Titanic's predictors\", legend_title = \"PPScore\")# Variable importancevi <- pps$predictors( df = df, y = \"Survived\", random_seed = 1234L)vi %>% mutate( x = as.factor(x) ) %>% lollipop( ppscore, x, main_title = \"Variable Importance for target = 'Survived'\", x_title = \"PPScore\", y_title = \"Predictors\", caption_title = \"Data from Titanic dataset\")" }, { "code": null, "e": 11506, "s": 11351, "text": "Denis Boigelot published a quite famous picture about Pearson correlation examples on Wikimedia Commons, sharing also the R code used to get this picture:" }, { "code": null, "e": 11624, "s": 11506, "text": "Starting from that code, it’s possible to calculate the PPScore for the same distributions. Here the results for X→Y:" }, { "code": null, "e": 11650, "s": 11624, "text": "Here the results for Y→X:" }, { "code": null, "e": 11700, "s": 11650, "text": "It’s clear that at the time this post was written" }, { "code": null, "e": 11885, "s": 11700, "text": "PPScore struggles to identify linear relationships in presence of even minimal dispersion of the points from the line of origin (as highlighted in yellow and red in previous pictures)." }, { "code": null, "e": 11902, "s": 11885, "text": "These cases show" }, { "code": null, "e": 12017, "s": 11902, "text": "how important it is also to use a correlation index to check linearity in order not to run into wrong conclusions." }, { "code": null, "e": 12243, "s": 12017, "text": "I shared these results with the author and he confirmed they are studying a solution to solve linear relationships issues. He also shared the reasons why PPScore 1.1.0 doesn’t work well with linear relationships at this link." }, { "code": null, "e": 12404, "s": 12243, "text": "Conversely, PPScore provides good results on some distributions for which Pearson correlation was not sufficient (as highlighted in green in previous pictures)." }, { "code": null, "e": 12478, "s": 12404, "text": "The R code used to get the above Boigelot distributions is the following:" }, { "code": null, "e": 17022, "s": 12478, "text": "# Install packagespkgs <- c(\"dplyr\",\"ggplot2\",\"ggpubr\",\"mvtnorm\")for (pkg in pkgs) { if (! (pkg %in% rownames(installed.packages()))) { install.packages(pkg) }}# Load packageslibrary(mvtnorm)library(dplyr)library(ggplot2)library(ggpubr)library(reticulate)# FunctionsMyPlot <- function(xy, xlim = c(-4, 4), ylim = c(-4, 4), eps = 1e-15, metric = c(\"cor\", \"ppsxy\", \"ppsyx\")) { metric <- metric[1] df <- as.data.frame(xy) names(df) <- c(\"x\", \"y\") if (metric == \"cor\") { value <- round(cor(xy[,1], xy[,2]), 1) if (sd(xy[,2]) < eps) { #title <- bquote(\"corr = \" * \"undef\") # corr. coeff. is undefined title <- paste0(\"corr = NA\") # corr. coeff. is undefined } else { #title <- bquote(\"corr = \" * .(value)) title <- paste0(\"corr = \", value) } subtitle <- NULL } else if (metric == \"ppsxy\") { pps_df <- pps$matrix(df = df, random_seed = 1111L) value <- pps_df %>% filter( x == \"x\" & y == \"y\" ) %>% mutate( ppscore = round(ppscore, 1) ) %>% pull(ppscore) title <- bquote(\"pps\"[X%->%Y] * \" = \" * .(value)) subtitle <- NULL } else if (metric == \"ppsyx\") { pps_df <- pps$matrix(df = df, random_seed = 1111L) value <- pps_df %>% filter( x == \"y\" & y == \"x\" ) %>% mutate( ppscore = round(ppscore, 1) ) %>% pull(ppscore) title <- bquote(\"pps\"[Y%->%X] * \" = \" * .(value)) subtitle <- NULL } ggplot(df, aes(x, y)) + geom_point( color = \"darkblue\", size = 0.2 ) + xlim(xlim) + ylim(ylim) + labs(title = title, subtitle = subtitle) + theme_void() + theme( plot.title = element_text(size = 10, hjust = .5) ) }MvNormal <- function(n = 1000, cor = 0.8, metric = c(\"cor\", \"ppsxy\", \"ppsyx\")) { metric <- metric[1] res <- list() j <- 0 for (i in cor) { sd <- matrix(c(1, i, i, 1), ncol = 2) x <- rmvnorm(n, c(0, 0), sd) j <- j + 1 name <- paste0(\"p\", j) res[[name]] <- MyPlot(x, metric = metric) } return(res)}rotation <- function(t, X) return(X %*% matrix(c(cos(t), sin(t), -sin(t), cos(t)), ncol = 2))RotNormal <- function(n = 1000, t = pi/2, metric = c(\"cor\", \"ppsxy\", \"ppsyx\")) { metric <- metric[1] sd <- matrix(c(1, 1, 1, 1), ncol = 2) x <- rmvnorm(n, c(0, 0), sd) res <- list() j <- 0 for (i in t) { j <- j + 1 name <- paste0(\"p\", j) res[[name]] <- MyPlot(rotation(i, x), metric = metric) } return(res)}Others <- function(n = 1000, metric = c(\"cor\", \"ppsxy\", \"ppsyx\")) { metric <- metric[1] res <- list() x <- runif(n, -1, 1) y <- 4 * (x^2 - 1/2)^2 + runif(n, -1, 1)/3 res[[\"p1\"]] <- MyPlot(cbind(x,y), xlim = c(-1, 1), ylim = c(-1/3, 1+1/3), metric = metric) y <- runif(n, -1, 1) xy <- rotation(-pi/8, cbind(x,y)) lim <- sqrt(2+sqrt(2)) / sqrt(2) res[[\"p2\"]] <- MyPlot(xy, xlim = c(-lim, lim), ylim = c(-lim, lim), metric = metric) xy <- rotation(-pi/8, xy) res[[\"p3\"]] <- MyPlot(xy, xlim = c(-sqrt(2), sqrt(2)), ylim = c(-sqrt(2), sqrt(2)), metric = metric) y <- 2*x^2 + runif(n, -1, 1) res[[\"p4\"]] <- MyPlot(cbind(x,y), xlim = c(-1, 1), ylim = c(-1, 3), metric = metric) y <- (x^2 + runif(n, 0, 1/2)) * sample(seq(-1, 1, 2), n, replace = TRUE) res[[\"p5\"]] <- MyPlot(cbind(x,y), xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5), metric = metric) y <- cos(x*pi) + rnorm(n, 0, 1/8) x <- sin(x*pi) + rnorm(n, 0, 1/8) res[[\"p6\"]] <- MyPlot(cbind(x,y), xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5), metric = metric) xy1 <- rmvnorm(n/4, c( 3, 3)) xy2 <- rmvnorm(n/4, c(-3, 3)) xy3 <- rmvnorm(n/4, c(-3, -3)) xy4 <- rmvnorm(n/4, c( 3, -3)) res[[\"p7\"]] <- MyPlot(rbind(xy1, xy2, xy3, xy4), xlim = c(-3-4, 3+4), ylim = c(-3-4, 3+4), metric = metric) return(res)}output <- function( metric = c(\"cor\", \"ppsxy\", \"ppsyx\") ) { metric <- metric[1] plots1 <- MvNormal( n = 800, cor = c(1.0, 0.8, 0.4, 0.0, -0.4, -0.8, -1.0), metric = metric ); plots2 <- RotNormal(200, c(0, pi/12, pi/6, pi/4, pi/2-pi/6, pi/2-pi/12, pi/2), metric = metric); plots3 <- Others(800, metric = metric) ggarrange( plots1$p1, plots1$p2, plots1$p3, plots1$p4, plots1$p5, plots1$p6, plots1$p7, plots2$p1, plots2$p2, plots2$p3, plots2$p4, plots2$p5, plots2$p6, plots2$p7, plots3$p1, plots3$p2, plots3$p3, plots3$p4, plots3$p5, plots3$p6, plots3$p7, ncol = 7, nrow = 3 ) }#-- Main -------------------------------------use_condaenv(\"test_ppscore\")pps <- import(module = \"ppscore\")output( metric = \"cor\" )output( metric = \"ppsxy\" )output( metric = \"ppsyx\" )" }, { "code": null, "e": 17416, "s": 17022, "text": "The Predictive Power Score (PPS) index proposed by Florian Wetschoreck tries to help data scientists in giving a hint to find any kind of relationship between two variables during the EDA phase of a project, being them numerical or categorical. PPS could be inaccurate, but its aim is not to give an exact score, rather the general notion of dependency between two variables and a fast result." }, { "code": null, "e": 17734, "s": 17416, "text": "Using the Boigelot distributions, it was shown that PPS (the current version is 1.1.0) is able to identify non-linear relationships not identified by the correlation index. Conversely, PPS seems to struggle to identify linear relationships in presence of even minimal dispersion of the points from the line of origin." }, { "code": null, "e": 17844, "s": 17734, "text": "Although PPScore was developed in Python, its functions can also be used in an R script thanks to reticulate." } ]
Tryit Editor v3.7
Tryit: Unordered HTML list
[]
Fabric.js | Circle fill Property - GeeksforGeeks
12 May, 2020 In this article, we are going to see how to change the fill color of a canvas circle using FabricJS. The canvas means the circle is movable and can be stretched according to requirement. Further, the circle can be customized when it comes to initial stroke color, fill color, stroke width, or radius. Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our circle. After this, we will initialize instances of Canvas and Circle provided by FabricJS and change the fill color of the circle using fill property and render the Circle on the Canvas as given in the example below. Syntax: fabric.Circle({ radius: number, fill: string }); Parameters: This function accepts two parameters as mentioned above and described below: radius: It specifies the radius of circle. fill: It specifies the color to be filled into the circle. Example: This example uses FabricJS to change the fill color of a canvas circle. <!DOCTYPE html><html> <head> <title> Fabric.js | Circle fill Property </title> <!-- FabricJS CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas("canvas"); // Initiate a Circle instance var circle = new fabric.Circle({ radius: 50, fill: 'green' }); // Render the circle in canvas canvas.add(circle); </script></body> </html> Output: Fabric.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23990, "s": 23962, "text": "\n12 May, 2020" }, { "code": null, "e": 24291, "s": 23990, "text": "In this article, we are going to see how to change the fill color of a canvas circle using FabricJS. The canvas means the circle is movable and can be stretched according to requirement. Further, the circle can be customized when it comes to initial stroke color, fill color, stroke width, or radius." }, { "code": null, "e": 24705, "s": 24291, "text": "Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our circle. After this, we will initialize instances of Canvas and Circle provided by FabricJS and change the fill color of the circle using fill property and render the Circle on the Canvas as given in the example below." }, { "code": null, "e": 24713, "s": 24705, "text": "Syntax:" }, { "code": null, "e": 24771, "s": 24713, "text": "fabric.Circle({\n radius: number,\n fill: string\n}); " }, { "code": null, "e": 24860, "s": 24771, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 24903, "s": 24860, "text": "radius: It specifies the radius of circle." }, { "code": null, "e": 24962, "s": 24903, "text": "fill: It specifies the color to be filled into the circle." }, { "code": null, "e": 25043, "s": 24962, "text": "Example: This example uses FabricJS to change the fill color of a canvas circle." }, { "code": "<!DOCTYPE html><html> <head> <title> Fabric.js | Circle fill Property </title> <!-- FabricJS CDN --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000\"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas(\"canvas\"); // Initiate a Circle instance var circle = new fabric.Circle({ radius: 50, fill: 'green' }); // Render the circle in canvas canvas.add(circle); </script></body> </html>", "e": 25716, "s": 25043, "text": null }, { "code": null, "e": 25724, "s": 25716, "text": "Output:" }, { "code": null, "e": 25734, "s": 25724, "text": "Fabric.js" }, { "code": null, "e": 25745, "s": 25734, "text": "JavaScript" }, { "code": null, "e": 25762, "s": 25745, "text": "Web Technologies" }, { "code": null, "e": 25860, "s": 25762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25869, "s": 25860, "text": "Comments" }, { "code": null, "e": 25882, "s": 25869, "text": "Old Comments" }, { "code": null, "e": 25927, "s": 25882, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 25988, "s": 25927, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26060, "s": 25988, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26112, "s": 26060, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 26158, "s": 26112, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 26200, "s": 26158, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26233, "s": 26200, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26276, "s": 26233, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26338, "s": 26276, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
GitLab CI - Install Runner
GitLab runner is a build instance which is used to run the jobs over multiple machines and send the results to GitLab. In this chapter, we will discuss about how to install runner in the GitLab CI. Step 1 − First, login to your GitLab server using SSH (Secure Shell). Step 2 − Update the repository by using the below command − $ sudo apt-get update -y Step 3 − Next, install the required dependencies − sudo apt-get install wget curl gcc checkinstall libxml2-dev sudo apt-get install libxslt-dev libcurl4-openssl-dev sudo apt-get install libreadline6-dev libc6-dev libssl-dev sudo apt-get install libmysql++-dev make build-essential zlib1g-dev sudo apt-get install openssh-server git-core libyaml-dev sudo apt-get install redis-server postfix libpq-dev libicudev Step 4 − Now, install the Ruby by creating a directory under /tmp folder − mkdir /tmp/ruby && cd /tmp/ruby Step 5 − Install the Ruby package with the below command − curl --progress http://cache.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p353.tar.bz2 | tar xj cd ruby-2.0.0-p353 ./configure –disable-install-rdoc && make && sudo make install Step 6 − After installing the Ruby, install the package manager for Ruby − sudo gem install bundler Step 7 − Now create a new user to run the runner instead of running as root user. (For security reasons, we are creating new user) − sudo adduser –disabled-login –gecos 'GitLab CI Runner' gitlab_ci_runner Step 8 − Login with new user − sudo su gitlab_ci_runner cd ~/ Step 9 − Now clone the actual code after installing all dependencies − git clone https://gitlab.com/gitlab-org/gitlab-ci-runner.git && cd gitlab-ci-runner Step 10 − Next, install the gems for the runner − bundle install –-deployment Step 10 − Your need to start runner automatically whenever the server restarts by creating the init.d file − cd /gitlab-ci-runner sudo cp ./lib/support/init.d/gitlab_ci_runner /etc/init.d/gitlab-ci-runner sudo chmod +x /etc/init.d/gitlab-ci-runner sudo update-rc.d gitlab-ci-runner defaults 21 Step 11 − Now you can start the runner by using the below command − sudo service gitlab-ci-runner start Print Add Notes Bookmark this page
[ { "code": null, "e": 2522, "s": 2324, "text": "GitLab runner is a build instance which is used to run the jobs over multiple machines and send the results to GitLab. In this chapter, we will discuss about how to install runner in the GitLab CI." }, { "code": null, "e": 2592, "s": 2522, "text": "Step 1 − First, login to your GitLab server using SSH (Secure Shell)." }, { "code": null, "e": 2652, "s": 2592, "text": "Step 2 − Update the repository by using the below command −" }, { "code": null, "e": 2677, "s": 2652, "text": "$ sudo apt-get update -y" }, { "code": null, "e": 2728, "s": 2677, "text": "Step 3 − Next, install the required dependencies −" }, { "code": null, "e": 3088, "s": 2728, "text": "sudo apt-get install wget curl gcc checkinstall libxml2-dev\nsudo apt-get install libxslt-dev libcurl4-openssl-dev\nsudo apt-get install libreadline6-dev libc6-dev libssl-dev\nsudo apt-get install libmysql++-dev make build-essential\nzlib1g-dev\nsudo apt-get install openssh-server git-core libyaml-dev\nsudo apt-get install redis-server postfix libpq-dev libicudev" }, { "code": null, "e": 3163, "s": 3088, "text": "Step 4 − Now, install the Ruby by creating a directory under /tmp folder −" }, { "code": null, "e": 3195, "s": 3163, "text": "mkdir /tmp/ruby && cd /tmp/ruby" }, { "code": null, "e": 3254, "s": 3195, "text": "Step 5 − Install the Ruby package with the below command −" }, { "code": null, "e": 3425, "s": 3254, "text": "curl --progress http://cache.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p353.tar.bz2 | tar xj\ncd ruby-2.0.0-p353\n./configure –disable-install-rdoc && make && sudo make install" }, { "code": null, "e": 3500, "s": 3425, "text": "Step 6 − After installing the Ruby, install the package manager for Ruby −" }, { "code": null, "e": 3526, "s": 3500, "text": "sudo gem install bundler " }, { "code": null, "e": 3659, "s": 3526, "text": "Step 7 − Now create a new user to run the runner instead of running as root user. (For security reasons, we are creating new user) −" }, { "code": null, "e": 3731, "s": 3659, "text": "sudo adduser –disabled-login –gecos 'GitLab CI Runner' gitlab_ci_runner" }, { "code": null, "e": 3762, "s": 3731, "text": "Step 8 − Login with new user −" }, { "code": null, "e": 3793, "s": 3762, "text": "sudo su gitlab_ci_runner\ncd ~/" }, { "code": null, "e": 3864, "s": 3793, "text": "Step 9 − Now clone the actual code after installing all dependencies −" }, { "code": null, "e": 3948, "s": 3864, "text": "git clone https://gitlab.com/gitlab-org/gitlab-ci-runner.git && cd gitlab-ci-runner" }, { "code": null, "e": 3998, "s": 3948, "text": "Step 10 − Next, install the gems for the runner −" }, { "code": null, "e": 4026, "s": 3998, "text": "bundle install –-deployment" }, { "code": null, "e": 4135, "s": 4026, "text": "Step 10 − Your need to start runner automatically whenever the server restarts by creating the init.d file −" }, { "code": null, "e": 4320, "s": 4135, "text": "cd /gitlab-ci-runner\nsudo cp ./lib/support/init.d/gitlab_ci_runner /etc/init.d/gitlab-ci-runner\nsudo chmod +x /etc/init.d/gitlab-ci-runner\nsudo update-rc.d gitlab-ci-runner defaults 21" }, { "code": null, "e": 4388, "s": 4320, "text": "Step 11 − Now you can start the runner by using the below command −" }, { "code": null, "e": 4424, "s": 4388, "text": "sudo service gitlab-ci-runner start" }, { "code": null, "e": 4431, "s": 4424, "text": " Print" }, { "code": null, "e": 4442, "s": 4431, "text": " Add Notes" } ]
Deadlock and Starvation in Java - GeeksforGeeks
24 Mar, 2022 Deadlock: Deadlock is a situation when two threads are waiting for each other and the waiting never ends. Here both threads cant completes their tasks. JAVA // Java program to illustrate Deadlock situationclass DeadlockDemo extends Thread { static Thread mainThread; public void run() { System.out.println("Child Thread waiting for" + " main thread completion"); try { // Child thread waiting for completion // of main thread mainThread.join(); } catch (InterruptedException e) { System.out.println("Child thread execution" + " completes"); } } public static void main(String[] args) throws InterruptedException { DeadlockDemo.mainThread = Thread.currentThread(); DeadlockDemo thread = new DeadlockDemo(); thread.start(); System.out.println("Main thread waiting for " + "Child thread completion"); // main thread is waiting for the completion // of Child thread thread.join(); System.out.println("Main thread execution" + " completes"); }} Output: Main thread waiting for Child thread completion Child Thread waiting for main thread completion Starvation:In Starvation, threads are also waiting for each other. But here waiting time is not infinite after some interval of time, waiting thread always gets the resources whatever is required to execute thread run() method. JAVA // Java program to illustrate Starvation conceptclass StarvationDemo extends Thread { static int threadcount = 1; public void run() { System.out.println(threadcount + "st Child" + " Thread execution starts"); System.out.println("Child thread execution completes"); threadcount++; } public static void main(String[] args) throws InterruptedException { System.out.println("Main thread execution starts"); // Thread priorities are set in a way that thread5 // gets least priority. StarvationDemo thread1 = new StarvationDemo(); thread1.setPriority(10); StarvationDemo thread2 = new StarvationDemo(); thread2.setPriority(9); StarvationDemo thread3 = new StarvationDemo(); thread3.setPriority(8); StarvationDemo thread4 = new StarvationDemo(); thread4.setPriority(7); StarvationDemo thread5 = new StarvationDemo(); thread5.setPriority(6); thread1.start(); thread2.start(); thread3.start(); thread4.start(); // Here thread5 have to wait because of the // other thread. But after waiting for some // interval, thread5 will get the chance of // execution. It is known as Starvation thread5.start(); System.out.println("Main thread execution completes"); }} Output: Main thread execution starts 1st Child Thread execution starts Child thread execution completes 2st Child Thread execution starts Child thread execution completes 3st Child Thread execution starts Child thread execution completes 4st Child Thread execution starts Child thread execution completes Main thread execution completes 5st Child Thread execution starts Child thread execution completes adnanirshad158 jordandegea Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n24 Mar, 2022" }, { "code": null, "e": 24101, "s": 23948, "text": "Deadlock: Deadlock is a situation when two threads are waiting for each other and the waiting never ends. Here both threads cant completes their tasks. " }, { "code": null, "e": 24106, "s": 24101, "text": "JAVA" }, { "code": "// Java program to illustrate Deadlock situationclass DeadlockDemo extends Thread { static Thread mainThread; public void run() { System.out.println(\"Child Thread waiting for\" + \" main thread completion\"); try { // Child thread waiting for completion // of main thread mainThread.join(); } catch (InterruptedException e) { System.out.println(\"Child thread execution\" + \" completes\"); } } public static void main(String[] args) throws InterruptedException { DeadlockDemo.mainThread = Thread.currentThread(); DeadlockDemo thread = new DeadlockDemo(); thread.start(); System.out.println(\"Main thread waiting for \" + \"Child thread completion\"); // main thread is waiting for the completion // of Child thread thread.join(); System.out.println(\"Main thread execution\" + \" completes\"); }}", "e": 25198, "s": 24106, "text": null }, { "code": null, "e": 25208, "s": 25198, "text": "Output: " }, { "code": null, "e": 25304, "s": 25208, "text": "Main thread waiting for Child thread completion\nChild Thread waiting for main thread completion" }, { "code": null, "e": 25533, "s": 25304, "text": "Starvation:In Starvation, threads are also waiting for each other. But here waiting time is not infinite after some interval of time, waiting thread always gets the resources whatever is required to execute thread run() method. " }, { "code": null, "e": 25538, "s": 25533, "text": "JAVA" }, { "code": "// Java program to illustrate Starvation conceptclass StarvationDemo extends Thread { static int threadcount = 1; public void run() { System.out.println(threadcount + \"st Child\" + \" Thread execution starts\"); System.out.println(\"Child thread execution completes\"); threadcount++; } public static void main(String[] args) throws InterruptedException { System.out.println(\"Main thread execution starts\"); // Thread priorities are set in a way that thread5 // gets least priority. StarvationDemo thread1 = new StarvationDemo(); thread1.setPriority(10); StarvationDemo thread2 = new StarvationDemo(); thread2.setPriority(9); StarvationDemo thread3 = new StarvationDemo(); thread3.setPriority(8); StarvationDemo thread4 = new StarvationDemo(); thread4.setPriority(7); StarvationDemo thread5 = new StarvationDemo(); thread5.setPriority(6); thread1.start(); thread2.start(); thread3.start(); thread4.start(); // Here thread5 have to wait because of the // other thread. But after waiting for some // interval, thread5 will get the chance of // execution. It is known as Starvation thread5.start(); System.out.println(\"Main thread execution completes\"); }}", "e": 26935, "s": 25538, "text": null }, { "code": null, "e": 26945, "s": 26935, "text": "Output: " }, { "code": null, "e": 27341, "s": 26945, "text": "Main thread execution starts\n1st Child Thread execution starts\nChild thread execution completes\n2st Child Thread execution starts\nChild thread execution completes\n3st Child Thread execution starts\nChild thread execution completes\n4st Child Thread execution starts\nChild thread execution completes\nMain thread execution completes\n5st Child Thread execution starts\nChild thread execution completes" }, { "code": null, "e": 27358, "s": 27343, "text": "adnanirshad158" }, { "code": null, "e": 27370, "s": 27358, "text": "jordandegea" }, { "code": null, "e": 27390, "s": 27370, "text": "Java-Multithreading" }, { "code": null, "e": 27395, "s": 27390, "text": "Java" }, { "code": null, "e": 27400, "s": 27395, "text": "Java" }, { "code": null, "e": 27498, "s": 27400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27513, "s": 27498, "text": "Stream In Java" }, { "code": null, "e": 27559, "s": 27513, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27580, "s": 27559, "text": "Constructors in Java" }, { "code": null, "e": 27599, "s": 27580, "text": "Exceptions in Java" }, { "code": null, "e": 27616, "s": 27599, "text": "Generics in Java" }, { "code": null, "e": 27646, "s": 27616, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27689, "s": 27646, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27718, "s": 27689, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27739, "s": 27718, "text": "Introduction to Java" } ]
Easy, Breezy, EDA — An Update to My Latest Function | by Katie Sylvia | Towards Data Science
In my latest blog post, I had written about a function I created while working on my latest project to simplify code and save time during the EDA process. For those not familiar with the post, this was the function I had created: def initial_eda(df): # List of categorical columns cat_cols = df.select_dtypes('object').columns for col in cat_cols: # Formatting column_name = col.title().replace('_', ' ') title= 'Distribution of ' + column_name # Unique values <= 12 to avoid overcrowding if len(df[col].value_counts())<=12: plt.figure(figsize = (8, 6)) sns.countplot(x=df[col], data=df, palette="Paired", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel("Frequency",fontsize = 15) plt.show(); else: print(f'{column_name} has {len(df[col].value_counts())} unique values. Alternative EDA should be considered.') returnSome examples of the visuals created from this code: After running the Austin Animal Center dataset through this function, here were some of the visuals that were produced: While this worked well for initial EDA, like I mentioned in my last post, there was plenty of room for improvement. For example, the function above only provides visuals for columns with twelve or fewer unique values. Those with more unique values provided these print statements instead: While this does provide some information about each of these columns, there was a missed opportunity to extract insights about the data that could be valuable. Here is a new, updated version of this function: def initial_eda(df): # List of categorical columns cat_cols = df.select_dtypes(['object','category']).columns for col in cat_cols: # Formatting column_name = col.title().replace('_', ' ') title = 'Distribution of ' + column_name unique_values = len(df[col].value_counts()) # unique_values <=12 to avoid overcrowding if unique_values<=12: plt.figure(figsize = (10, 6)) sns.countplot(x=df[col], data=df, palette="Paired", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel("Frequency",fontsize = 15) plt.show(); else: print(f'{column_name} has {len(df[col].value_counts())} unique values. Here are the top 10:') print() col_count = df[col].value_counts() col_count = col_count[:10,] plt.figure(figsize = (12, 6)) sns.barplot(x = col_count.index, y = col_count.values, palette="Paired") plt.title(f'Top 10 {column_name}s', fontsize = 18, pad = 12) plt.ylabel('Frequency', fontsize=15) plt.xticks(rotation=20) plt.xlabel(column_name, fontsize=15) plt.show() return Rather than returning a print statement, the updated version of this function will now create a bar plot of the ten most common unique values if the column has more than twelve unique values. Some examples: This addition to the function provides us with even more information and raises questions we may choose to pursue further. For example, from these visuals we can see that the animal with ID A721033 has entered the shelter more than thirty times. Why is that? What animal type is it? Was this animal a stray? Has this animal been adopted before? These additional visuals can provide valuable insights and pilot the direction of the project prior to the modeling process. One final addition is made to the function to ensure the produced visuals are aesthetically pleasing. While the function as is provides us with meaningful information, a ‘one-figsize-fits-all’ approach can create bar plots that may be considered visually unappealing. For example: Maybe this is me being picky, but I look at these graphs and know they can be improved. In my opinion, columns with two unique values should not have the same figure size as a column with twelve unique values. Here is the final, updated function that configures the figure size based off the number of unique values: def initial_eda(df): # List of categorical columns cat_cols = df.select_dtypes(['object','category']).columns for col in cat_cols: # Formatting column_name = col.title().replace('_', ' ') title = 'Distribution of ' + column_name unique_values = len(df[col].value_counts()) # If statements for figsize if 2<=unique_values<3: plt.figure(figsize = (4, 6)) sns.countplot(x=df[col], data=df, palette="Paired", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel("Frequency",fontsize = 15) plt.show(); elif 3<=unique_values<8: plt.figure(figsize = (8, 6)) sns.countplot(x=df[col], data=df, palette="Paired", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel("Frequency",fontsize = 15) plt.show(); elif 8<=unique_values<=12: plt.figure(figsize = (10, 6)) sns.countplot(x=df[col], data=df, palette="Paired", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel("Frequency",fontsize = 15) plt.show(); else: print(f'{column_name} has {len(df[col].value_counts())} unique values. Here are the top 10:') print() col_count = df[col].value_counts() col_count = col_count[:10,] plt.figure(figsize = (12, 6)) sns.barplot(x = col_count.index, y = col_count.values, palette="Paired") plt.title(f'Top 10 {column_name}s', fontsize = 18, pad = 12) plt.ylabel('Frequency', fontsize=15) plt.xticks(rotation=20) plt.xlabel(column_name, fontsize=15) plt.show() return Now, this function will present these visuals instead: These are slightly more appealing to look at, in my opinion. Exploratory Data Analysis (EDA) can shape the direction of a project. It is one of my favorite phases in the data science process as it is where one’s curiosity can be fully explored. While the “magic” of data science comes to life during the modeling phase, determining and optimizing a model to its fullest potential starts with proper data exploration. My hope is that myself and others can utilize this function not just to save time, but more importantly to use the time saved to expand our curiosities. The important thing is not to stop questioning. Curiosity has its own reason for existing. One cannot help but be in awe when he contemplates the mysteries of eternity, of life, of the marvelous structure of reality. It is enough if one tries merely to comprehend a little of this mystery every day. Never lose a holy curiosity. — Albert Einstein, LIFE Magazine (2 May 1955) To read more about the Austin Animal Outcomes project, you can view it on my personal GitHub here.
[ { "code": null, "e": 402, "s": 172, "text": "In my latest blog post, I had written about a function I created while working on my latest project to simplify code and save time during the EDA process. For those not familiar with the post, this was the function I had created:" }, { "code": null, "e": 1387, "s": 402, "text": "def initial_eda(df): # List of categorical columns cat_cols = df.select_dtypes('object').columns for col in cat_cols: # Formatting column_name = col.title().replace('_', ' ') title= 'Distribution of ' + column_name # Unique values <= 12 to avoid overcrowding if len(df[col].value_counts())<=12: plt.figure(figsize = (8, 6)) sns.countplot(x=df[col], data=df, palette=\"Paired\", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel(\"Frequency\",fontsize = 15) plt.show(); else: print(f'{column_name} has {len(df[col].value_counts())} unique values. Alternative EDA should be considered.') returnSome examples of the visuals created from this code:" }, { "code": null, "e": 1507, "s": 1387, "text": "After running the Austin Animal Center dataset through this function, here were some of the visuals that were produced:" }, { "code": null, "e": 1796, "s": 1507, "text": "While this worked well for initial EDA, like I mentioned in my last post, there was plenty of room for improvement. For example, the function above only provides visuals for columns with twelve or fewer unique values. Those with more unique values provided these print statements instead:" }, { "code": null, "e": 2005, "s": 1796, "text": "While this does provide some information about each of these columns, there was a missed opportunity to extract insights about the data that could be valuable. Here is a new, updated version of this function:" }, { "code": null, "e": 3479, "s": 2005, "text": "def initial_eda(df): # List of categorical columns cat_cols = df.select_dtypes(['object','category']).columns for col in cat_cols: # Formatting column_name = col.title().replace('_', ' ') title = 'Distribution of ' + column_name unique_values = len(df[col].value_counts()) # unique_values <=12 to avoid overcrowding if unique_values<=12: plt.figure(figsize = (10, 6)) sns.countplot(x=df[col], data=df, palette=\"Paired\", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel(\"Frequency\",fontsize = 15) plt.show(); else: print(f'{column_name} has {len(df[col].value_counts())} unique values. Here are the top 10:') print() col_count = df[col].value_counts() col_count = col_count[:10,] plt.figure(figsize = (12, 6)) sns.barplot(x = col_count.index, y = col_count.values, palette=\"Paired\") plt.title(f'Top 10 {column_name}s', fontsize = 18, pad = 12) plt.ylabel('Frequency', fontsize=15) plt.xticks(rotation=20) plt.xlabel(column_name, fontsize=15) plt.show() return" }, { "code": null, "e": 3686, "s": 3479, "text": "Rather than returning a print statement, the updated version of this function will now create a bar plot of the ten most common unique values if the column has more than twelve unique values. Some examples:" }, { "code": null, "e": 4156, "s": 3686, "text": "This addition to the function provides us with even more information and raises questions we may choose to pursue further. For example, from these visuals we can see that the animal with ID A721033 has entered the shelter more than thirty times. Why is that? What animal type is it? Was this animal a stray? Has this animal been adopted before? These additional visuals can provide valuable insights and pilot the direction of the project prior to the modeling process." }, { "code": null, "e": 4437, "s": 4156, "text": "One final addition is made to the function to ensure the produced visuals are aesthetically pleasing. While the function as is provides us with meaningful information, a ‘one-figsize-fits-all’ approach can create bar plots that may be considered visually unappealing. For example:" }, { "code": null, "e": 4754, "s": 4437, "text": "Maybe this is me being picky, but I look at these graphs and know they can be improved. In my opinion, columns with two unique values should not have the same figure size as a column with twelve unique values. Here is the final, updated function that configures the figure size based off the number of unique values:" }, { "code": null, "e": 7136, "s": 4754, "text": "def initial_eda(df): # List of categorical columns cat_cols = df.select_dtypes(['object','category']).columns for col in cat_cols: # Formatting column_name = col.title().replace('_', ' ') title = 'Distribution of ' + column_name unique_values = len(df[col].value_counts()) # If statements for figsize if 2<=unique_values<3: plt.figure(figsize = (4, 6)) sns.countplot(x=df[col], data=df, palette=\"Paired\", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel(\"Frequency\",fontsize = 15) plt.show(); elif 3<=unique_values<8: plt.figure(figsize = (8, 6)) sns.countplot(x=df[col], data=df, palette=\"Paired\", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel(\"Frequency\",fontsize = 15) plt.show(); elif 8<=unique_values<=12: plt.figure(figsize = (10, 6)) sns.countplot(x=df[col], data=df, palette=\"Paired\", order = df[col].value_counts().index) plt.title(title, fontsize = 18, pad = 12) plt.xlabel(column_name, fontsize = 15) plt.xticks(rotation=20) plt.ylabel(\"Frequency\",fontsize = 15) plt.show(); else: print(f'{column_name} has {len(df[col].value_counts())} unique values. Here are the top 10:') print() col_count = df[col].value_counts() col_count = col_count[:10,] plt.figure(figsize = (12, 6)) sns.barplot(x = col_count.index, y = col_count.values, palette=\"Paired\") plt.title(f'Top 10 {column_name}s', fontsize = 18, pad = 12) plt.ylabel('Frequency', fontsize=15) plt.xticks(rotation=20) plt.xlabel(column_name, fontsize=15) plt.show() return" }, { "code": null, "e": 7191, "s": 7136, "text": "Now, this function will present these visuals instead:" }, { "code": null, "e": 7252, "s": 7191, "text": "These are slightly more appealing to look at, in my opinion." }, { "code": null, "e": 7608, "s": 7252, "text": "Exploratory Data Analysis (EDA) can shape the direction of a project. It is one of my favorite phases in the data science process as it is where one’s curiosity can be fully explored. While the “magic” of data science comes to life during the modeling phase, determining and optimizing a model to its fullest potential starts with proper data exploration." }, { "code": null, "e": 7761, "s": 7608, "text": "My hope is that myself and others can utilize this function not just to save time, but more importantly to use the time saved to expand our curiosities." }, { "code": null, "e": 8136, "s": 7761, "text": "The important thing is not to stop questioning. Curiosity has its own reason for existing. One cannot help but be in awe when he contemplates the mysteries of eternity, of life, of the marvelous structure of reality. It is enough if one tries merely to comprehend a little of this mystery every day. Never lose a holy curiosity. — Albert Einstein, LIFE Magazine (2 May 1955)" } ]
Extract 'k' bits from a given position in a number. - GeeksforGeeks
31 Jan, 2022 How to extract ‘k’ bits from a given position ‘p’ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 0101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get only 01000 i.e 8. 1) Right shift number by p-1. 2) Do bit wise AND of k set bits with the modified number. We can get k set bits by doing (1 << k) – 1. C++ C Java Python3 C# PHP Javascript // C++ program to extract k bits from a given// position.#include <bits/stdc++.h>using namespace std; // Function to extract k bits from p position// and returns the extracted value as integerint bitExtracted(int number, int k, int p){ return (((1 << k) - 1) & (number >> (p - 1)));} // Driver codeint main(){ int number = 171, k = 5, p = 2; cout << "The extracted number is " << bitExtracted(number, k, p); return 0;} // This code is contributed by importantly // C program to extract k bits from a given// position.#include <stdio.h> // Function to extract k bits from p position// and returns the extracted value as integerint bitExtracted(int number, int k, int p){ return (((1 << k) - 1) & (number >> (p - 1)));} // Driver codeint main(){ int number = 171, k = 5, p = 2; printf("The extracted number is %d", bitExtracted(number, k, p)); return 0;} // Java program to extract k bits from a given// position. class GFG { // Function to extract k bits from p position // and returns the extracted value as integer static int bitExtracted(int number, int k, int p) { return (((1 << k) - 1) & (number >> (p - 1))); } // Driver code public static void main (String[] args) { int number = 171, k = 5, p = 2; System.out.println("The extracted number is "+ bitExtracted(number, k, p)); }} # Python program to extract k bits from a given# position. # Function to extract k bits from p position# and returns the extracted value as integerdef bitExtracted(number, k, p): return ( ((1 << k) - 1) & (number >> (p-1) ) ); # number is from where 'k' bits are extracted# from p positionnumber = 171k = 5p = 2print ("The extracted number is ", bitExtracted(number, k, p)) // C# program to extract k bits from a given// position.using System; class GFG { // Function to extract k bits from p position // and returns the extracted value as integer static int bitExtracted(int number, int k, int p) { return (((1 << k) - 1) & (number >> (p - 1))); } // Driver code public static void Main() { int number = 171, k = 5, p = 2; Console.WriteLine("The extracted number is " + bitExtracted(number, k, p)); }} //This code is contributed by Anant Agarwal. <?php//PHP program to extract// k bits from a given// position. // Function to extract k// bits from p position// and returns the extracted// value as integerfunction bitExtracted($number, $k, $p){ return (((1 << $k) - 1) & ($number >> ($p - 1)));} // Driver Code $number = 171; $k = 5; $p = 2; echo "The extracted number is ", bitExtracted($number, $k, $p); // This code is contributed by Ajit?> <script>// JavaScript program to extract k bits from a given// position. // Function to extract k bits from p position// and returns the extracted value as integerfunction bitExtracted(number, k, p){ return (((1 << k) - 1) & (number >> (p - 1)));} // Driver code let number = 171, k = 5, p = 2; document.write("The extracted number is ", bitExtracted(number, k, p)); // This code is contributed by Manoj.</script> Output : The extracted number is 21 YouTubeGeeksforGeeks502K subscribersExtract ‘k’ bits from a given position in a number | 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:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_FJ6FoEc7Yk" 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 Ujjwal Aryal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t mank1083 importantly amartyaghoshgfg Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Bit Fields in C Add two numbers without using arithmetic operators Find the element that appears once Set, Clear and Toggle a given bit of a number in C Josephus problem | Set 1 (A O(n) Solution) C++ bitset and its application
[ { "code": null, "e": 25006, "s": 24978, "text": "\n31 Jan, 2022" }, { "code": null, "e": 25069, "s": 25006, "text": "How to extract ‘k’ bits from a given position ‘p’ in a number?" }, { "code": null, "e": 25080, "s": 25069, "text": "Examples: " }, { "code": null, "e": 25428, "s": 25080, "text": "Input : number = 171\n k = 5 \n p = 2\nOutput : The extracted number is 21\n171 is represented as 0101011 in binary,\nso, you should get only 10101 i.e. 21.\n\nInput : number = 72\n k = 5 \n p = 1\nOutput : The extracted number is 8\n72 is represented as 1001000 in binary,\nso, you should get only 01000 i.e 8.\n " }, { "code": null, "e": 25562, "s": 25428, "text": "1) Right shift number by p-1. 2) Do bit wise AND of k set bits with the modified number. We can get k set bits by doing (1 << k) – 1." }, { "code": null, "e": 25566, "s": 25562, "text": "C++" }, { "code": null, "e": 25568, "s": 25566, "text": "C" }, { "code": null, "e": 25573, "s": 25568, "text": "Java" }, { "code": null, "e": 25581, "s": 25573, "text": "Python3" }, { "code": null, "e": 25584, "s": 25581, "text": "C#" }, { "code": null, "e": 25588, "s": 25584, "text": "PHP" }, { "code": null, "e": 25599, "s": 25588, "text": "Javascript" }, { "code": "// C++ program to extract k bits from a given// position.#include <bits/stdc++.h>using namespace std; // Function to extract k bits from p position// and returns the extracted value as integerint bitExtracted(int number, int k, int p){ return (((1 << k) - 1) & (number >> (p - 1)));} // Driver codeint main(){ int number = 171, k = 5, p = 2; cout << \"The extracted number is \" << bitExtracted(number, k, p); return 0;} // This code is contributed by importantly", "e": 26097, "s": 25599, "text": null }, { "code": "// C program to extract k bits from a given// position.#include <stdio.h> // Function to extract k bits from p position// and returns the extracted value as integerint bitExtracted(int number, int k, int p){ return (((1 << k) - 1) & (number >> (p - 1)));} // Driver codeint main(){ int number = 171, k = 5, p = 2; printf(\"The extracted number is %d\", bitExtracted(number, k, p)); return 0;}", "e": 26514, "s": 26097, "text": null }, { "code": "// Java program to extract k bits from a given// position. class GFG { // Function to extract k bits from p position // and returns the extracted value as integer static int bitExtracted(int number, int k, int p) { return (((1 << k) - 1) & (number >> (p - 1))); } // Driver code public static void main (String[] args) { int number = 171, k = 5, p = 2; System.out.println(\"The extracted number is \"+ bitExtracted(number, k, p)); }}", "e": 27008, "s": 26514, "text": null }, { "code": "# Python program to extract k bits from a given# position. # Function to extract k bits from p position# and returns the extracted value as integerdef bitExtracted(number, k, p): return ( ((1 << k) - 1) & (number >> (p-1) ) ); # number is from where 'k' bits are extracted# from p positionnumber = 171k = 5p = 2print (\"The extracted number is \", bitExtracted(number, k, p))", "e": 27389, "s": 27008, "text": null }, { "code": "// C# program to extract k bits from a given// position.using System; class GFG { // Function to extract k bits from p position // and returns the extracted value as integer static int bitExtracted(int number, int k, int p) { return (((1 << k) - 1) & (number >> (p - 1))); } // Driver code public static void Main() { int number = 171, k = 5, p = 2; Console.WriteLine(\"The extracted number is \" + bitExtracted(number, k, p)); }} //This code is contributed by Anant Agarwal.", "e": 27946, "s": 27389, "text": null }, { "code": "<?php//PHP program to extract// k bits from a given// position. // Function to extract k// bits from p position// and returns the extracted// value as integerfunction bitExtracted($number, $k, $p){ return (((1 << $k) - 1) & ($number >> ($p - 1)));} // Driver Code $number = 171; $k = 5; $p = 2; echo \"The extracted number is \", bitExtracted($number, $k, $p); // This code is contributed by Ajit?>", "e": 28385, "s": 27946, "text": null }, { "code": "<script>// JavaScript program to extract k bits from a given// position. // Function to extract k bits from p position// and returns the extracted value as integerfunction bitExtracted(number, k, p){ return (((1 << k) - 1) & (number >> (p - 1)));} // Driver code let number = 171, k = 5, p = 2; document.write(\"The extracted number is \", bitExtracted(number, k, p)); // This code is contributed by Manoj.</script>", "e": 28821, "s": 28385, "text": null }, { "code": null, "e": 28831, "s": 28821, "text": "Output : " }, { "code": null, "e": 28858, "s": 28831, "text": "The extracted number is 21" }, { "code": null, "e": 29709, "s": 28860, "text": "YouTubeGeeksforGeeks502K subscribersExtract ‘k’ bits from a given position in a number | 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:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_FJ6FoEc7Yk\" 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": 30130, "s": 29709, "text": "This article is contributed by Ujjwal Aryal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30136, "s": 30130, "text": "jit_t" }, { "code": null, "e": 30145, "s": 30136, "text": "mank1083" }, { "code": null, "e": 30157, "s": 30145, "text": "importantly" }, { "code": null, "e": 30173, "s": 30157, "text": "amartyaghoshgfg" }, { "code": null, "e": 30183, "s": 30173, "text": "Bit Magic" }, { "code": null, "e": 30193, "s": 30183, "text": "Bit Magic" }, { "code": null, "e": 30291, "s": 30193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30337, "s": 30291, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 30367, "s": 30337, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 30420, "s": 30367, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 30460, "s": 30420, "text": "Binary representation of a given number" }, { "code": null, "e": 30476, "s": 30460, "text": "Bit Fields in C" }, { "code": null, "e": 30527, "s": 30476, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 30562, "s": 30527, "text": "Find the element that appears once" }, { "code": null, "e": 30613, "s": 30562, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 30656, "s": 30613, "text": "Josephus problem | Set 1 (A O(n) Solution)" } ]
getchar_unlocked() in C
The function getchar_unlocked() is deprecated in Windows because it is a thread unsafe version of getchar(). It is suggested not to use getchar_unlocked(). There is no stream lock check that’s why getchar_unlocked is unsafe. The function getchar_unlocked() is faster than getchar(). Here is the syntax of getchar_unlocked() in C language, int getchar_unlocked(void); A program of getchar_unlocked() in C is as follows − Live Demo #include <stdio.h> int main() { char val; val = getchar_unlocked(); printf("Enter the character : \n"); printf("Entered character : %c", val); return 0; } Here is the output Enter the character : a Entered character : a
[ { "code": null, "e": 1345, "s": 1062, "text": "The function getchar_unlocked() is deprecated in Windows because it is a thread unsafe version of getchar(). It is suggested not to use getchar_unlocked(). There is no stream lock check that’s why getchar_unlocked is unsafe. The function getchar_unlocked() is faster than getchar()." }, { "code": null, "e": 1401, "s": 1345, "text": "Here is the syntax of getchar_unlocked() in C language," }, { "code": null, "e": 1429, "s": 1401, "text": "int getchar_unlocked(void);" }, { "code": null, "e": 1482, "s": 1429, "text": "A program of getchar_unlocked() in C is as follows −" }, { "code": null, "e": 1493, "s": 1482, "text": " Live Demo" }, { "code": null, "e": 1664, "s": 1493, "text": "#include <stdio.h>\n\nint main() {\n char val;\n val = getchar_unlocked();\n printf(\"Enter the character : \\n\");\n printf(\"Entered character : %c\", val);\n return 0;\n}" }, { "code": null, "e": 1683, "s": 1664, "text": "Here is the output" }, { "code": null, "e": 1729, "s": 1683, "text": "Enter the character : a\nEntered character : a" } ]
HTML - <comment> and <!--....--> Tag
The HTML <comment> tag allows authors to comment their HTML code. This tag is supported by IE only. It is recommended to use <!--....--> to comment your tags. This tag is compatible to all browsers. Note − The <comment> tag deprecated in HTML5. Do not use this element. <!DOCTYPE html> <html> <head> <title>HTML <!--....--> Tag</title> </head> <body> <comment>This is a commented line in IE</comment> <!-- This is a commented line supported by almost every browser. It will not appear in output as its a comment. --> </body> </html> This will produce the following result − Browser Support for <comment> tag Browser Support for <!--...--> tag 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2474, "s": 2374, "text": "The HTML <comment> tag allows authors to comment their HTML code. This tag is supported by IE only." }, { "code": null, "e": 2573, "s": 2474, "text": "It is recommended to use <!--....--> to comment your tags. This tag is compatible to all browsers." }, { "code": null, "e": 2644, "s": 2573, "text": "Note − The <comment> tag deprecated in HTML5. Do not use this element." }, { "code": null, "e": 2963, "s": 2644, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML <!--....--> Tag</title>\n </head>\n\n <body>\n <comment>This is a commented line in IE</comment>\n \n <!-- This is a commented line supported by almost every browser.\n It will not appear in output as its a comment. \n -->\n </body>\n\n</html>" }, { "code": null, "e": 3004, "s": 2963, "text": "This will produce the following result −" }, { "code": null, "e": 3038, "s": 3004, "text": "Browser Support for <comment> tag" }, { "code": null, "e": 3073, "s": 3038, "text": "Browser Support for <!--...--> tag" }, { "code": null, "e": 3106, "s": 3073, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3120, "s": 3106, "text": " Anadi Sharma" }, { "code": null, "e": 3155, "s": 3120, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3169, "s": 3155, "text": " Anadi Sharma" }, { "code": null, "e": 3204, "s": 3169, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3221, "s": 3204, "text": " Frahaan Hussain" }, { "code": null, "e": 3256, "s": 3221, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3287, "s": 3256, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3320, "s": 3287, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3351, "s": 3320, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3386, "s": 3351, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3417, "s": 3386, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3424, "s": 3417, "text": " Print" }, { "code": null, "e": 3435, "s": 3424, "text": " Add Notes" } ]
Check if a large number is divisible by 3 or not - GeeksforGeeks
28 Jan, 2022 Given a number, the task is that we divide number by 3. The input number may be large and it may not be possible to store even if we use long long int.Examples: Input : n = 769452 Output : Yes Input : n = 123456758933312 Output : No Input : n = 3635883959606670431112222 Output : Yes Since input number may be very large, we cannot use n % 3 to check if a number is divisible by 3 or not, especially in languages like C/C++. The idea is based on following fact. A number is divisible by 3 if sum of its digits is divisible by 3. Illustration: For example n = 1332 Sum of digits = 1 + 3 + 3 + 2 = 9 Since sum is divisible by 3, answer is Yes. How does this work? Let us consider 1332, we can write it as 1332 = 1*1000 + 3*100 + 3*10 + 2 The proof is based on below observation: Remainder of 10i divided by 3 is 1 So powers of 10 only result in value 1. Remainder of "1*1000 + 3*100 + 3*10 + 2" divided by 3 can be written as : 1*1 + 3*1 + 3*1 + 2 = 9 The above expression is basically sum of all digits. Since 9 is divisible by 3, answer is yes. Below is the implementation of above fact : C++ Java Python3 C# PHP Javascript // C++ program to find if a number is divisible by// 3 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible by 3 or notint check(string str){ // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str[i]-'0'); // Check if sum of digits is divisible by 3. return (digitSum % 3 == 0);} // Driver codeint main(){ string str = "1332"; check(str)? cout << "Yes" : cout << "No "; return 0;} // Java program to find if a number is// divisible by 3 or notclass IsDivisible{ // Function to find that number // divisible by 3 or not static boolean check(String str) { // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str.charAt(i)-'0'); // Check if sum of digits is // divisible by 3. return (digitSum % 3 == 0); } // main function public static void main (String[] args) { String str = "1332"; if(check(str)) System.out.println("Yes"); else System.out.println("No"); }} # Python program to find if a number is# divisible by 3 or not # Function to find that number# divisible by 3 or notdef check(num) : # Compute sum of digits digitSum = 0 while num > 0 : rem = num % 10 digitSum = digitSum + rem num = num / 10 # Check if sum of digits is # divisible by 3. return (digitSum % 3 == 0) # main functionnum = 1332if(check(num)) : print ("Yes")else : print ("No") # This code is contributed by Nikita Tiwari. // C# program to find if a number is// divisible by 3 or notusing System; class GFG{ // Function to find that number // divisible by 3 or not static bool check(string str) { // Compute sum of digits int n = str.Length; int digitSum = 0; for (int i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 3. return (digitSum % 3 == 0); } // main function public static void Main () { string str = "1332"; if(check(str)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m. <?php// PHP program to find if a// number is divisible by// 3 or not // Function to find that// number divisible by 3 or notfunction check($str){ // Compute sum of digits $n = strlen($str); $digitSum = 0; for ($i = 0; $i < $n; $i++) $digitSum += ($str[$i] - '0'); // Check if sum of digits // is divisible by 3. return ($digitSum % 3 == 0);} // Driver code$str = "1332";$x = check($str) ? "Yes" : "No ";echo($x); // This code is contributed by Ajit.?> <script>// Javascript program to find if a// number is divisible by// 3 or not // Function to find that// number divisible by 3 or notfunction check(str){ // Compute sum of digits let n = str.length; let digitSum = 0; for (let i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits // is divisible by 3. return (digitSum % 3 == 0);} // Driver codelet str = "1332";let x = check(str) ? "Yes" : "No ";document.write(x); // This code is contributed by _saurabh_jaiswal.</script> Output: Yes This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t ManasChhabra2 _saurabh_jaiswal amartyaghoshgfg divisibility large-numbers number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Operators in C / C++ Program for factorial of a number The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value
[ { "code": null, "e": 26590, "s": 26562, "text": "\n28 Jan, 2022" }, { "code": null, "e": 26753, "s": 26590, "text": "Given a number, the task is that we divide number by 3. The input number may be large and it may not be possible to store even if we use long long int.Examples: " }, { "code": null, "e": 26881, "s": 26753, "text": "Input : n = 769452\nOutput : Yes\n\nInput : n = 123456758933312\nOutput : No\n\nInput : n = 3635883959606670431112222\nOutput : Yes" }, { "code": null, "e": 27062, "s": 26883, "text": "Since input number may be very large, we cannot use n % 3 to check if a number is divisible by 3 or not, especially in languages like C/C++. The idea is based on following fact. " }, { "code": null, "e": 27129, "s": 27062, "text": "A number is divisible by 3 if sum of its digits is divisible by 3." }, { "code": null, "e": 27145, "s": 27129, "text": "Illustration: " }, { "code": null, "e": 27257, "s": 27145, "text": "For example n = 1332\nSum of digits = 1 + 3 + 3 + 2\n = 9\nSince sum is divisible by 3,\nanswer is Yes." }, { "code": null, "e": 27278, "s": 27257, "text": "How does this work? " }, { "code": null, "e": 27665, "s": 27278, "text": "Let us consider 1332, we can write it as\n1332 = 1*1000 + 3*100 + 3*10 + 2\n\nThe proof is based on below observation:\nRemainder of 10i divided by 3 is 1\nSo powers of 10 only result in value 1.\n\nRemainder of \"1*1000 + 3*100 + 3*10 + 2\"\ndivided by 3 can be written as : \n1*1 + 3*1 + 3*1 + 2 = 9\nThe above expression is basically sum of\nall digits.\n\nSince 9 is divisible by 3, answer is yes." }, { "code": null, "e": 27710, "s": 27665, "text": "Below is the implementation of above fact : " }, { "code": null, "e": 27714, "s": 27710, "text": "C++" }, { "code": null, "e": 27719, "s": 27714, "text": "Java" }, { "code": null, "e": 27727, "s": 27719, "text": "Python3" }, { "code": null, "e": 27730, "s": 27727, "text": "C#" }, { "code": null, "e": 27734, "s": 27730, "text": "PHP" }, { "code": null, "e": 27745, "s": 27734, "text": "Javascript" }, { "code": "// C++ program to find if a number is divisible by// 3 or not#include<bits/stdc++.h>using namespace std; // Function to find that number divisible by 3 or notint check(string str){ // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str[i]-'0'); // Check if sum of digits is divisible by 3. return (digitSum % 3 == 0);} // Driver codeint main(){ string str = \"1332\"; check(str)? cout << \"Yes\" : cout << \"No \"; return 0;}", "e": 28252, "s": 27745, "text": null }, { "code": "// Java program to find if a number is// divisible by 3 or notclass IsDivisible{ // Function to find that number // divisible by 3 or not static boolean check(String str) { // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str.charAt(i)-'0'); // Check if sum of digits is // divisible by 3. return (digitSum % 3 == 0); } // main function public static void main (String[] args) { String str = \"1332\"; if(check(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 28918, "s": 28252, "text": null }, { "code": "# Python program to find if a number is# divisible by 3 or not # Function to find that number# divisible by 3 or notdef check(num) : # Compute sum of digits digitSum = 0 while num > 0 : rem = num % 10 digitSum = digitSum + rem num = num / 10 # Check if sum of digits is # divisible by 3. return (digitSum % 3 == 0) # main functionnum = 1332if(check(num)) : print (\"Yes\")else : print (\"No\") # This code is contributed by Nikita Tiwari.", "e": 29420, "s": 28918, "text": null }, { "code": "// C# program to find if a number is// divisible by 3 or notusing System; class GFG{ // Function to find that number // divisible by 3 or not static bool check(string str) { // Compute sum of digits int n = str.Length; int digitSum = 0; for (int i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 3. return (digitSum % 3 == 0); } // main function public static void Main () { string str = \"1332\"; if(check(str)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.", "e": 30123, "s": 29420, "text": null }, { "code": "<?php// PHP program to find if a// number is divisible by// 3 or not // Function to find that// number divisible by 3 or notfunction check($str){ // Compute sum of digits $n = strlen($str); $digitSum = 0; for ($i = 0; $i < $n; $i++) $digitSum += ($str[$i] - '0'); // Check if sum of digits // is divisible by 3. return ($digitSum % 3 == 0);} // Driver code$str = \"1332\";$x = check($str) ? \"Yes\" : \"No \";echo($x); // This code is contributed by Ajit.?>", "e": 30609, "s": 30123, "text": null }, { "code": "<script>// Javascript program to find if a// number is divisible by// 3 or not // Function to find that// number divisible by 3 or notfunction check(str){ // Compute sum of digits let n = str.length; let digitSum = 0; for (let i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits // is divisible by 3. return (digitSum % 3 == 0);} // Driver codelet str = \"1332\";let x = check(str) ? \"Yes\" : \"No \";document.write(x); // This code is contributed by _saurabh_jaiswal.</script>", "e": 31137, "s": 30609, "text": null }, { "code": null, "e": 31145, "s": 31137, "text": "Output:" }, { "code": null, "e": 31149, "s": 31145, "text": "Yes" }, { "code": null, "e": 31570, "s": 31149, "text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31576, "s": 31570, "text": "jit_t" }, { "code": null, "e": 31590, "s": 31576, "text": "ManasChhabra2" }, { "code": null, "e": 31607, "s": 31590, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31623, "s": 31607, "text": "amartyaghoshgfg" }, { "code": null, "e": 31636, "s": 31623, "text": "divisibility" }, { "code": null, "e": 31650, "s": 31636, "text": "large-numbers" }, { "code": null, "e": 31664, "s": 31650, "text": "number-digits" }, { "code": null, "e": 31677, "s": 31664, "text": "Mathematical" }, { "code": null, "e": 31690, "s": 31677, "text": "Mathematical" }, { "code": null, "e": 31788, "s": 31690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31812, "s": 31788, "text": "Merge two sorted arrays" }, { "code": null, "e": 31855, "s": 31812, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31869, "s": 31855, "text": "Prime Numbers" }, { "code": null, "e": 31911, "s": 31869, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31933, "s": 31911, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 32006, "s": 31933, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32027, "s": 32006, "text": "Operators in C / C++" }, { "code": null, "e": 32061, "s": 32027, "text": "Program for factorial of a number" }, { "code": null, "e": 32104, "s": 32061, "text": "The Knight's tour problem | Backtracking-1" } ]
How to secure your Azure Data Factory pipeline | by René Bremer | Towards Data Science
Azure Data Factory (ADFv2) is a popular tool to orchestrate data ingestion from on-premises to cloud. In every ADFv2 pipeline, security is an important topic. Common security aspects are the following: Azure Active Directory (AAD) access control to data and endpoints Managed Identity (MI) to prevent key management processes Virtual Network (VNET) isolation of data and endpoints In the remainder of this blog, it is discussed how an ADFv2 pipeline can be secured using AAD, MI, VNETs and firewall rules. For more details on security of Azure Functions, see my other blog. For a solution how to prevent data loss in your Data lake using snapshots and incremental backups, see this blog. Update 2020–07–26: It is now possible to run ADFv2 Azure hosted Integration Runtime in a Managed VNET . This is in public preview and this blog has not yet been updated yet with this feature. In this ADFv2 pipeline, data is read from SQLDB, transformed using an Azure Function and written to an ADLS gen2 account. The architecture of the project can be found below. The Azure services and its usage in this project are described as follows: SQLDB is used as source system that contains the table data that will be copied. Azure Data Factory v2 (ADFv2) is used as orchestrator to copy data from source to destination. ADFv2 uses a Self-Hosted Integration Runtime (SHIR) as compute which runs on VMs in a VNET Azure Function in Python is used to parse data. Function has no access to other Azure resources Azure Data Lake Store gen2 (ADLS gen2) is used to store the data from 10 SQLDB tables and the metadata file created by the Azure Function Azure Active Directory (AAD) is Microsoft’s identity and access management service to authenticate and authorize to Azure resources The following security aspects are part of this project. AAD access control: SQLDB, ADLS gen 2 and Azure Function only allow the MI of ADFv2 to access the data. This means that no keys need to be stored in ADFv2 or key vaults. Firewall rules: SQLDB, ADLS gen 2 and Azure Function all have firewall rules in which only the VNET of the SHIR is allowed as inbound network In the next chapter, the ADFv2 pipeline architecture is realized. In this chapter, the following steps are executed to create and deploy the ADFv2 pipeline. 3a. Install preliminaries and resources 3b. Create Self-hosted integration runtime in ADFv2 3c. Secure ADLS gen2 account 3d. Secure SQLDB database 3e. Deploy and secure Azure Function 3f. Configure and run ADFv2 pipeline In this tutorial, deployment of resources will be done using code as much as possible. The following resources need to be installed: Install Azure CLI Install Azure PowerShell Install Visual Studio Code Install Azure Function Python libraries in Visual Studio Code After the preliminaries are installed, the basic resources can be installed. Open your Visual Studio Code, create a new terminal session and execute commands below. # Login with your AzureAD credentialsaz login# set parameters$rg = "<<Resource group>>"$loc = "<<Location, e.g. westeurope>>"$adfv2 = "<<Adfv2 name>>"$sqlserv = "<<Logical sql server>>"$sqldb = "<<SQLDB name>>"$sqluser = "<<SQLDB username>>"$pass = "<<SQLDB password, use https://passwordsgenerator.net/>>"$adls = "<<adls gen 2 account, only alphanumeric>>"$funname = "<<Azure Function name>>"$funstor = "<<Azure Function storage>>"$funplan = "<<Azure Function plan>>"$vnet = "<<Azure VNET name>>"# create resource groupaz group create -n $rg -l $loc# create Azure Data Factory instanceaz resource create --resource-group $rg --name $adfv2 --resource-type "Microsoft.DataFactory/factories" -p {}# create logical SQL server and SQLDBaz sql server create -l $loc -g $rg -n $sqlserv -u sqluser -p $passaz sql db create -g $rg -s $sqlserver -n $sqldb --service-objective Basic --sample-name AdventureWorksLT# create ADLS gen 2 account and containeraz storage account create -n $adls -g $rg -l $loc --sku Standard_LRS --kind StorageV2 --hierarchical-namespace trueaz storage container create --account-name $adls -n "sqldbdata"# create Azure Functionaz storage account create -n $funstor -g $rg --sku Standard_LRSaz appservice plan create -n $funplan -g $rg --sku B1 --is-linuxaz functionapp create -g $rg --os-type Linux --plan $funplan --runtime python --name $funname --storage-account $funstor# create VNETaz network vnet create -g $rg -n $vnet -l $loc --address-prefix 10.100.0.0/16 --subnet-name shir --subnet-prefix 10.100.0.0/24 In this part, the self-hosted integration runtime in ADFv2 is configured. This will be done using VMs running in the VNET that was created earlier. Execute the Azure CLI script below. # use the same parameters in step 3a, plus additional params below:$shir_rg="<<rg name>>"$shir_name="<<shir name>>"$shir_vm="<<name of VMs on which SHIR runs>>"$shir_admin="<<name of VMs on which SHIR runs>>"$shir_pass="<<VM password, use https://passwordsgenerator.net/>>"az group deployment create -g $shir_rg --template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vms-with-selfhost-integration-runtime/azuredeploy.json --parameters existingDataFactoryName=$adfv2 existingDataFactoryResourceGroup=$rg existingDataFactoryVersion=V2 IntegrationRuntimeName=$shir_name NodeCount=2 adminUserName=$shir_admin adminPassword=$shir_pass existingVirtualNetworkName=$vnet existingVnetLocation=$loc existingVnetResourceGroupName=$rg existingSubnetInYourVnet="shir" The scripts can take 15 minutes before it is finished. After the script is run, you can verify in your ADFv2 instance whether it is succesfully deployed, see also below. In this part, the ADLS gen2 account will be secured. This is done as follows: Add RBAC rule that only MI of ADFv2 can access ADLS gen 2 Add firewall rule that only VNET of SHIR can access ADLS gen 2 container In this case, Azure PowerShell is used to configure the rules using the same variable # Get params, PowerShell is used here, can be done in VSC terminalSet-AzDataFactoryV2 -ResourceGroupName $rg -Name $adfv2 -Location $l$adfv2_id = Get-AzDataFactoryV2 -ResourceGroupName $rg -Name $adfv2$sub_id = (Get-AzContext).Subscription.id# Give ADFv2 MI RBAC role to ADLS gen 2 accountNew-AzRoleAssignment -ObjectId $adfv2_id.Identity.PrincipalId -RoleDefinitionName "Reader" -Scope "/subscriptions/$sub_id/resourceGroups/$rg/providers/Microsoft.Storage/storageAccounts/$adls/blobServices/default"New-AzRoleAssignment -ObjectId $adfv2_id.Identity.PrincipalId -RoleDefinitionName "Storage Blob Data Contributor" -Scope "/subscriptions/$sub_id/resourceGroups/$rg/providers/Microsoft.Storage/storageAccounts/$adls/blobServices/default/containers/sqldbdata"# Turn on firewallUpdate-AzStorageAccountNetworkRuleSet -ResourceGroupName $rg -Name $adls -DefaultAction Deny# Set service endpoints for storage and SQL to subnetGet-AzVirtualNetwork -ResourceGroupName $rg -Name $vnet | Set-AzVirtualNetworkSubnetConfig -Name "shir" -AddressPrefix "10.100.0.0/24" -ServiceEndpoint "Microsoft.Storage", "Microsoft.SQL" | Set-AzVirtualNetwork# Add firewall rules$subnet = Get-AzVirtualNetwork -ResourceGroupName $rg -Name $vnet | Get-AzVirtualNetworkSubnetConfig -Name "shir"Add-AzStorageAccountNetworkRule -ResourceGroupName $rg -Name $adls -VirtualNetworkResourceId $subnet.Id After the last step, access to your storage account from the Azure portal is refused (since it is not part of the VNET). To enable access from the portal, you you need to whitelist your IP address. In this part, the SQLDB will be secured. This is done as follows: Add Database rule that only MI of ADFv2 can access SQLDB Add firewall rule that only VNET of SHIR can access SQLDB Azure PowerShell is used to configure the rules. # Configure AAD access to logical SQL serverConnect-AzureAD$aaduser = "<<your aad user email address>>"Set-AzSqlServerActiveDirectoryAdministrator -ResourceGroupName $rg -ServerName $sqlserver -DisplayName $aaduser# log in SQL with AAD (e.g. via portal query editor, SSMS or VSC)# Execute following SQL statementCREATE USER [<<your Data Factory name>>] FROM EXTERNAL PROVIDER;EXEC sp_addrolemember [db_datareader], [<<your Data Factory name>>];# Add firewall rules$subnet = Get-AzVirtualNetwork -ResourceGroupName $rg -Name $vnet | Get-AzVirtualNetworkSubnetConfig -Name "shir"New-AzSqlServerVirtualNetworkRule -ResourceGroupName $rg -ServerName $sqlserver -VirtualNetworkRuleName "shirvnet" -VirtualNetworkSubnetId $subnet.Id To enable access from the computer for test purposes, you you need to white your IP address. In this part, the Azure Function will be deployed. This is done as follows: Deploy source to function Add firewall rule that only VNET of SHIR can access Azure Function Add App Registration that only MI of ADFv2 can access Azure Function First step is to create an Azure Function in python using this quickstart. Subsequently, update the requirement.txt, __init__.py and add cdmschema.py from this git repository. Then publish your function to the $funname that was created in step 3a. To enhance security, add a firewall rule using the following Azure CLI script: az webapp config access-restriction add -g $rg -n $funname --rule-name "shirvnet" --action Allow --vnet-name $vnet --subnet "shir" --priority 300 Finally, AAD access to the Azure Function can be configured by added an app registration to the Azure Function and only allow MI of ADFv2 to access Azure Function. Refer to this tutorial and this PowerShell script how to do this. In this part, the ADFv2 pipeline will be configured and run. Go to your Azure Data Factory Instance, select to set up a code repository and import the following GitHub repository rebremer and project adfv2_cdm_metadata, see below. Only the pipeline BlogADFv2sec is relevant for this blog. Customize the related linked services of this pipeline for ADLS gen2, Azure Function and SQLDB, see also below. See this link how to be enabled logging in your Azure Function using Applications Insights. An example of logging can be found below. In the final step, the pipeline can be run in ADFv2. Go to your pipeline and click debug. When everything goes well, all green checks will appear in the output, see below. In this blog, an architecture is created that deploys a secure ADFv2 pipeline in which data is read from SQLDB, transformed using an Azure Function and written to an ADLS gen2 account. In this, AAD access control, Managed Identities, VNETs and firewall rules are used to secure the pipeline, see also architecture below. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 373, "s": 171, "text": "Azure Data Factory (ADFv2) is a popular tool to orchestrate data ingestion from on-premises to cloud. In every ADFv2 pipeline, security is an important topic. Common security aspects are the following:" }, { "code": null, "e": 439, "s": 373, "text": "Azure Active Directory (AAD) access control to data and endpoints" }, { "code": null, "e": 497, "s": 439, "text": "Managed Identity (MI) to prevent key management processes" }, { "code": null, "e": 552, "s": 497, "text": "Virtual Network (VNET) isolation of data and endpoints" }, { "code": null, "e": 859, "s": 552, "text": "In the remainder of this blog, it is discussed how an ADFv2 pipeline can be secured using AAD, MI, VNETs and firewall rules. For more details on security of Azure Functions, see my other blog. For a solution how to prevent data loss in your Data lake using snapshots and incremental backups, see this blog." }, { "code": null, "e": 1051, "s": 859, "text": "Update 2020–07–26: It is now possible to run ADFv2 Azure hosted Integration Runtime in a Managed VNET . This is in public preview and this blog has not yet been updated yet with this feature." }, { "code": null, "e": 1225, "s": 1051, "text": "In this ADFv2 pipeline, data is read from SQLDB, transformed using an Azure Function and written to an ADLS gen2 account. The architecture of the project can be found below." }, { "code": null, "e": 1300, "s": 1225, "text": "The Azure services and its usage in this project are described as follows:" }, { "code": null, "e": 1381, "s": 1300, "text": "SQLDB is used as source system that contains the table data that will be copied." }, { "code": null, "e": 1567, "s": 1381, "text": "Azure Data Factory v2 (ADFv2) is used as orchestrator to copy data from source to destination. ADFv2 uses a Self-Hosted Integration Runtime (SHIR) as compute which runs on VMs in a VNET" }, { "code": null, "e": 1663, "s": 1567, "text": "Azure Function in Python is used to parse data. Function has no access to other Azure resources" }, { "code": null, "e": 1801, "s": 1663, "text": "Azure Data Lake Store gen2 (ADLS gen2) is used to store the data from 10 SQLDB tables and the metadata file created by the Azure Function" }, { "code": null, "e": 1933, "s": 1801, "text": "Azure Active Directory (AAD) is Microsoft’s identity and access management service to authenticate and authorize to Azure resources" }, { "code": null, "e": 1990, "s": 1933, "text": "The following security aspects are part of this project." }, { "code": null, "e": 2160, "s": 1990, "text": "AAD access control: SQLDB, ADLS gen 2 and Azure Function only allow the MI of ADFv2 to access the data. This means that no keys need to be stored in ADFv2 or key vaults." }, { "code": null, "e": 2302, "s": 2160, "text": "Firewall rules: SQLDB, ADLS gen 2 and Azure Function all have firewall rules in which only the VNET of the SHIR is allowed as inbound network" }, { "code": null, "e": 2368, "s": 2302, "text": "In the next chapter, the ADFv2 pipeline architecture is realized." }, { "code": null, "e": 2459, "s": 2368, "text": "In this chapter, the following steps are executed to create and deploy the ADFv2 pipeline." }, { "code": null, "e": 2499, "s": 2459, "text": "3a. Install preliminaries and resources" }, { "code": null, "e": 2551, "s": 2499, "text": "3b. Create Self-hosted integration runtime in ADFv2" }, { "code": null, "e": 2580, "s": 2551, "text": "3c. Secure ADLS gen2 account" }, { "code": null, "e": 2606, "s": 2580, "text": "3d. Secure SQLDB database" }, { "code": null, "e": 2643, "s": 2606, "text": "3e. Deploy and secure Azure Function" }, { "code": null, "e": 2680, "s": 2643, "text": "3f. Configure and run ADFv2 pipeline" }, { "code": null, "e": 2813, "s": 2680, "text": "In this tutorial, deployment of resources will be done using code as much as possible. The following resources need to be installed:" }, { "code": null, "e": 2831, "s": 2813, "text": "Install Azure CLI" }, { "code": null, "e": 2856, "s": 2831, "text": "Install Azure PowerShell" }, { "code": null, "e": 2883, "s": 2856, "text": "Install Visual Studio Code" }, { "code": null, "e": 2945, "s": 2883, "text": "Install Azure Function Python libraries in Visual Studio Code" }, { "code": null, "e": 3110, "s": 2945, "text": "After the preliminaries are installed, the basic resources can be installed. Open your Visual Studio Code, create a new terminal session and execute commands below." }, { "code": null, "e": 4642, "s": 3110, "text": "# Login with your AzureAD credentialsaz login# set parameters$rg = \"<<Resource group>>\"$loc = \"<<Location, e.g. westeurope>>\"$adfv2 = \"<<Adfv2 name>>\"$sqlserv = \"<<Logical sql server>>\"$sqldb = \"<<SQLDB name>>\"$sqluser = \"<<SQLDB username>>\"$pass = \"<<SQLDB password, use https://passwordsgenerator.net/>>\"$adls = \"<<adls gen 2 account, only alphanumeric>>\"$funname = \"<<Azure Function name>>\"$funstor = \"<<Azure Function storage>>\"$funplan = \"<<Azure Function plan>>\"$vnet = \"<<Azure VNET name>>\"# create resource groupaz group create -n $rg -l $loc# create Azure Data Factory instanceaz resource create --resource-group $rg --name $adfv2 --resource-type \"Microsoft.DataFactory/factories\" -p {}# create logical SQL server and SQLDBaz sql server create -l $loc -g $rg -n $sqlserv -u sqluser -p $passaz sql db create -g $rg -s $sqlserver -n $sqldb --service-objective Basic --sample-name AdventureWorksLT# create ADLS gen 2 account and containeraz storage account create -n $adls -g $rg -l $loc --sku Standard_LRS --kind StorageV2 --hierarchical-namespace trueaz storage container create --account-name $adls -n \"sqldbdata\"# create Azure Functionaz storage account create -n $funstor -g $rg --sku Standard_LRSaz appservice plan create -n $funplan -g $rg --sku B1 --is-linuxaz functionapp create -g $rg --os-type Linux --plan $funplan --runtime python --name $funname --storage-account $funstor# create VNETaz network vnet create -g $rg -n $vnet -l $loc --address-prefix 10.100.0.0/16 --subnet-name shir --subnet-prefix 10.100.0.0/24" }, { "code": null, "e": 4826, "s": 4642, "text": "In this part, the self-hosted integration runtime in ADFv2 is configured. This will be done using VMs running in the VNET that was created earlier. Execute the Azure CLI script below." }, { "code": null, "e": 5619, "s": 4826, "text": "# use the same parameters in step 3a, plus additional params below:$shir_rg=\"<<rg name>>\"$shir_name=\"<<shir name>>\"$shir_vm=\"<<name of VMs on which SHIR runs>>\"$shir_admin=\"<<name of VMs on which SHIR runs>>\"$shir_pass=\"<<VM password, use https://passwordsgenerator.net/>>\"az group deployment create -g $shir_rg --template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vms-with-selfhost-integration-runtime/azuredeploy.json --parameters existingDataFactoryName=$adfv2 existingDataFactoryResourceGroup=$rg existingDataFactoryVersion=V2 IntegrationRuntimeName=$shir_name NodeCount=2 adminUserName=$shir_admin adminPassword=$shir_pass existingVirtualNetworkName=$vnet existingVnetLocation=$loc existingVnetResourceGroupName=$rg existingSubnetInYourVnet=\"shir\"" }, { "code": null, "e": 5789, "s": 5619, "text": "The scripts can take 15 minutes before it is finished. After the script is run, you can verify in your ADFv2 instance whether it is succesfully deployed, see also below." }, { "code": null, "e": 5867, "s": 5789, "text": "In this part, the ADLS gen2 account will be secured. This is done as follows:" }, { "code": null, "e": 5925, "s": 5867, "text": "Add RBAC rule that only MI of ADFv2 can access ADLS gen 2" }, { "code": null, "e": 5998, "s": 5925, "text": "Add firewall rule that only VNET of SHIR can access ADLS gen 2 container" }, { "code": null, "e": 6084, "s": 5998, "text": "In this case, Azure PowerShell is used to configure the rules using the same variable" }, { "code": null, "e": 7454, "s": 6084, "text": "# Get params, PowerShell is used here, can be done in VSC terminalSet-AzDataFactoryV2 -ResourceGroupName $rg -Name $adfv2 -Location $l$adfv2_id = Get-AzDataFactoryV2 -ResourceGroupName $rg -Name $adfv2$sub_id = (Get-AzContext).Subscription.id# Give ADFv2 MI RBAC role to ADLS gen 2 accountNew-AzRoleAssignment -ObjectId $adfv2_id.Identity.PrincipalId -RoleDefinitionName \"Reader\" -Scope \"/subscriptions/$sub_id/resourceGroups/$rg/providers/Microsoft.Storage/storageAccounts/$adls/blobServices/default\"New-AzRoleAssignment -ObjectId $adfv2_id.Identity.PrincipalId -RoleDefinitionName \"Storage Blob Data Contributor\" -Scope \"/subscriptions/$sub_id/resourceGroups/$rg/providers/Microsoft.Storage/storageAccounts/$adls/blobServices/default/containers/sqldbdata\"# Turn on firewallUpdate-AzStorageAccountNetworkRuleSet -ResourceGroupName $rg -Name $adls -DefaultAction Deny# Set service endpoints for storage and SQL to subnetGet-AzVirtualNetwork -ResourceGroupName $rg -Name $vnet | Set-AzVirtualNetworkSubnetConfig -Name \"shir\" -AddressPrefix \"10.100.0.0/24\" -ServiceEndpoint \"Microsoft.Storage\", \"Microsoft.SQL\" | Set-AzVirtualNetwork# Add firewall rules$subnet = Get-AzVirtualNetwork -ResourceGroupName $rg -Name $vnet | Get-AzVirtualNetworkSubnetConfig -Name \"shir\"Add-AzStorageAccountNetworkRule -ResourceGroupName $rg -Name $adls -VirtualNetworkResourceId $subnet.Id" }, { "code": null, "e": 7652, "s": 7454, "text": "After the last step, access to your storage account from the Azure portal is refused (since it is not part of the VNET). To enable access from the portal, you you need to whitelist your IP address." }, { "code": null, "e": 7718, "s": 7652, "text": "In this part, the SQLDB will be secured. This is done as follows:" }, { "code": null, "e": 7775, "s": 7718, "text": "Add Database rule that only MI of ADFv2 can access SQLDB" }, { "code": null, "e": 7833, "s": 7775, "text": "Add firewall rule that only VNET of SHIR can access SQLDB" }, { "code": null, "e": 7882, "s": 7833, "text": "Azure PowerShell is used to configure the rules." }, { "code": null, "e": 8609, "s": 7882, "text": "# Configure AAD access to logical SQL serverConnect-AzureAD$aaduser = \"<<your aad user email address>>\"Set-AzSqlServerActiveDirectoryAdministrator -ResourceGroupName $rg -ServerName $sqlserver -DisplayName $aaduser# log in SQL with AAD (e.g. via portal query editor, SSMS or VSC)# Execute following SQL statementCREATE USER [<<your Data Factory name>>] FROM EXTERNAL PROVIDER;EXEC sp_addrolemember [db_datareader], [<<your Data Factory name>>];# Add firewall rules$subnet = Get-AzVirtualNetwork -ResourceGroupName $rg -Name $vnet | Get-AzVirtualNetworkSubnetConfig -Name \"shir\"New-AzSqlServerVirtualNetworkRule -ResourceGroupName $rg -ServerName $sqlserver -VirtualNetworkRuleName \"shirvnet\" -VirtualNetworkSubnetId $subnet.Id" }, { "code": null, "e": 8702, "s": 8609, "text": "To enable access from the computer for test purposes, you you need to white your IP address." }, { "code": null, "e": 8778, "s": 8702, "text": "In this part, the Azure Function will be deployed. This is done as follows:" }, { "code": null, "e": 8804, "s": 8778, "text": "Deploy source to function" }, { "code": null, "e": 8871, "s": 8804, "text": "Add firewall rule that only VNET of SHIR can access Azure Function" }, { "code": null, "e": 8940, "s": 8871, "text": "Add App Registration that only MI of ADFv2 can access Azure Function" }, { "code": null, "e": 9267, "s": 8940, "text": "First step is to create an Azure Function in python using this quickstart. Subsequently, update the requirement.txt, __init__.py and add cdmschema.py from this git repository. Then publish your function to the $funname that was created in step 3a. To enhance security, add a firewall rule using the following Azure CLI script:" }, { "code": null, "e": 9413, "s": 9267, "text": "az webapp config access-restriction add -g $rg -n $funname --rule-name \"shirvnet\" --action Allow --vnet-name $vnet --subnet \"shir\" --priority 300" }, { "code": null, "e": 9643, "s": 9413, "text": "Finally, AAD access to the Azure Function can be configured by added an app registration to the Azure Function and only allow MI of ADFv2 to access Azure Function. Refer to this tutorial and this PowerShell script how to do this." }, { "code": null, "e": 9874, "s": 9643, "text": "In this part, the ADFv2 pipeline will be configured and run. Go to your Azure Data Factory Instance, select to set up a code repository and import the following GitHub repository rebremer and project adfv2_cdm_metadata, see below." }, { "code": null, "e": 10044, "s": 9874, "text": "Only the pipeline BlogADFv2sec is relevant for this blog. Customize the related linked services of this pipeline for ADLS gen2, Azure Function and SQLDB, see also below." }, { "code": null, "e": 10178, "s": 10044, "text": "See this link how to be enabled logging in your Azure Function using Applications Insights. An example of logging can be found below." }, { "code": null, "e": 10350, "s": 10178, "text": "In the final step, the pipeline can be run in ADFv2. Go to your pipeline and click debug. When everything goes well, all green checks will appear in the output, see below." }, { "code": null, "e": 10671, "s": 10350, "text": "In this blog, an architecture is created that deploys a secure ADFv2 pipeline in which data is read from SQLDB, transformed using an Azure Function and written to an ADLS gen2 account. In this, AAD access control, Managed Identities, VNETs and firewall rules are used to secure the pipeline, see also architecture below." } ]
Logistic Regression for Binary Classification | by Sebastián Gerard Aguilar Kleimann | Towards Data Science
In previous articles, I talked about deep learning and the functions used to predict results. In this article, we will use logistic regression to perform binary classification. Binary classification is named this way because it classifies the data into two results. Simply put, the result will be “yes” (1) or “no” (0). To determine whether the result is “yes” or “no”, we will use a probability function: This probability function will give us a number from 0 to 1 indicating how likely this observation will belong to the classification that we have currently determined to be “yes”. With this, we know what we intend to do with our prediction. Now, we’ll see how to use logistic regression to calculate the equation in (1). To perform logistic regression, the sigmoid function, presented below with its plot, is used: As we can see this function meets the characteristics of a probability function and equation (1). Likewise, we can see that when S(t) is very large positive, the function approaches one, and when S(t) is very large negative, the function approaches zero. To be able to understand how logistic regression operates, we will make an example where our function will classify people as tall or not tall. The data that we will use to calibrate our function are those corresponding to the following table (Table 1): Suppose t=wx+b, our goal will be to find w and b in such a way that by placing it in S(t) it will give us the correct prediction. We can start with a random number let’s say w=1 and b=0 and if S(t) is greater than 0.5 then we will consider it a tall person. We notice that the parameters w=1 and b=0, don’t work since in all cases S(x)>0.5 Let’s try now with w=6 and b=-10.5, the result would be: Great, we have found the w and b parameters in such a way that our function makes the predictions correctly! These parameters work to make the prediction; however, many questions arise such as: How do I calculate these parameters? Are these parameters the most recommended? To answer these questions, we will have to introduce two new topics that will help us optimize the function and understand the loss functions. What are the best w and b parameters? The answer to this question is very simple because we want the parameters to give us as little error as possible. For this we use the loss error function: The function basically tells us how far away is our estimate of the actual value (ŷ estimation, y actual value). If we’d make a summation on all our estimation we would get: This summation is the total error of all our estimates and trying to reduce this function to 0 means trying to reduce our error to 0. However, when using this function on logistic regression we get a function that is not convex (we will return to this topic later) and since it is not convex there can be several local optimal points, and a great difficulty when calculating the best w and b. To solve this issue, we will use another function: The function constructed in (5) has the same purpose as the function (3), to reduce the error. We’ll do an experiment on an observation to see how the function J(ŷ,y) behaves. Let’s imagine 4 possible scenarios of J(ŷ,y) Scenario 1- y=1, ŷ=.99 We observe that in this scenario our estimation is practically correct and when replacing, we get: Scenario 2- y=1, ŷ=.01 We observe that in this scenario our estimation is incorrect and when replacing, we get: Scenario 3- y=0, ŷ=.99 We observe that in this scenario our estimation is incorrect and when replacing, we get: Scenario 4- y=0, ŷ=.01 We observe that in this scenario our estimation is incorrect and when replacing, we get: Intuitively, we can observe what this function does. Correct observations have a very low error, and incorrect observations have a very high error. If we did the summation on all the observations, we’d get. The advantage of function (6) over function (4) is that it is convex. With function 6 it’s possible to find the optimal points in a simpler way using the gradient descent method. The gradient descent method seeks to tell us in which direction we need to move our b and w parameters, to optimize the function and get the minimum error. The function described in (6) is convex so you could see it as the following graphic. Now, suppose our loss function is J(w,b) and the parameters to be adjusted are (w,b). We want to find the point where J(w,b) is as small as possible. The gradient descent method tells us the direction where to move (w,b) to decrease J(w,b). These are the partial derivatives of (w,b), that is ∂J/∂w and ∂J/∂b. Knowing the directions where to move w and b. We would only need to know the magnitude to which they would move, this is called a learning rate and is usually defined as α. To finally get: Finally, we will summarize the steps that must be followed to perform the logistic regression: Analyze the problem and accommodate the data.Propose w and b randomly to predict your data.Calculate the errorPerform gradient descent to get new w and b. Analyze the problem and accommodate the data. Propose w and b randomly to predict your data. Calculate the error Perform gradient descent to get new w and b. These 4 steps should be iterated until you get an acceptable error. We finally have all the theoretical elements to apply logistic regression. It is also important to know how to apply them in programming languages such as python. This language is widely used so the implementation of this algorithm is quite easy. For this example, we will use logistic regression to predict the trajectory of basketball players. The data obtained for this exercise was extracted from 1data.world. At the end of the article, the full code is displayed, so that you can follow and run the code along with the article on google colab. It’s important to understand what each of the columns in this table mean: Name- Name of the player GP-Games played Min-Minutes played Pts-Average points made per game FGM- Field goals made FGA-Field goals attempted %FG-Percentage of field goals 3P MADE- Three-pointers made 3PA- Three-pointers attempted FTM-Free throws made FTA-Free throws attempted FT%-Free throw percentage OREB-Offensive rebounds DREB-Defensive rebounds Reb-Rebounds AST-Assists STL-Steals BLK-Blocks TOV-Turnovers TARGET_5YRS-If the player lasted 5 years or more, this value will be one, and it will be 0 otherwise. Before logistic regression, observation and analysis of the data should be done. Pandas library is a very used library on python for handling data and we will use it to read and describe data. ##Import library and read dataimport pandas as pdnbalog=pd.read_csv("path_of_file")###See data descriptiondecri=nbalog.describe() The code preceded by “#”are just comments, so with this code, we have done only 3 things: Import the necessary libraries.Read the base file.Describe the existing data. Import the necessary libraries. Read the base file. Describe the existing data. The description indicates the quantity of data we have, the maximum value, minimum value, standard deviation, etc. By observing the data it can be seen that some fields are empty. Before training the model these issues have to be solved. The empty fields will be substituted by 0, and Pearson Correlation Coefficient will be used to observe the data with the highest correlation. ###Using the data described we notice that 3P% has some blank ###fields.These fields will be filled with 0. nbalog=nbalog.fillna(0) ###We check the correlation that exists between the data. pearson=nbalog.corr(method='pearson') Using Pearson Correlation Coefficient we notice the columns with the highest correlation. This way the columns that are more useful should be kept and the others dropped. ###Some variables are higly correlated so they will be dropped ###(pearson>.8). nbalog=nbalog.drop(['MIN', 'PTS','FGM','3P Made','FTM','FTA','TOV','OREB','DREB'], axis=1) With the clean data we can start training the model. For this, the library sklearn will be used. This library contains many models and is updated constantly making it very useful. In order to train the model, we will indicate which are the variables that predict and the predicted variable. ### X are the variables that predict and y the variable we are ###trying to predict. X=nbalog[['GP','FGA','FG%','3PA','3P%','FT%','REB','AST','STL','BLK']] y=nbalog[['TARGET_5Yrs']] Now, using the library sklearn the data will be divided in training and test set. With the training set, the model will be adjusted, and with the test set we will see how good the model is. ### The data has to be divided in training and test set. from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25) The previous piece of code divides the data between train and test set. The variable X is for the independent variables and y for the dependent variable. This time 75% of the set was used for training and 25% for testing. After separating the data it can be used to fit the model which in this case is the “LogisticRegression” model. ###We import the model that will be used. from sklearn.linear_model import LogisticRegression. # Create an instance of the model. logreg = LogisticRegression() # Training the model. logreg.fit(X_train,y_train) # Do prediction. y_pred=logreg.predict(X_test) So, the model has been calibrated using the function .fit and it’s ready to predict using the test data. This is done using the function .predict and using the independent variables for testing (X_test). The results obtained can be compared with the real values (y_test) to see if it’s a good model. # Analyzing the results. from sklearn import metrics cnf_matrix = metrics.confusion_matrix(y_test, y_pred) The resulting matrix is known as confusion matrix. In the first quadrant the number of entries that were classified correctly with 0 are shown(61). The second and third quadrant sum the incorrect classification(99). Lastly, the fourth quadrant shows the classifications that were done correctly with number 1 (175). The accuracy can be calculated as follows: print("Accuracy:",metrics.accuracy_score(y_test, y_pred))Output:.7045 With this, we conclude the article. As usual, I’ll leave you the code so you can test, run and try different models. Good day and congratulations on learning how to do logistic regression. Bibliography 1Rippner, N. (2017, January 24). Binary Classification Exercise Dataset. Retrieved September 24, 2020, from https://data.world/. 2Indeed123 / CC BY-SA (https://creativecommons.org/licenses/by-sa/3.0) 3Lolikar / CC BY-SA (https://creativecommons.org/licenses/by-sa/4.0) Originally published at https://datasciencestreet.com on September 25, 2020.
[ { "code": null, "e": 578, "s": 172, "text": "In previous articles, I talked about deep learning and the functions used to predict results. In this article, we will use logistic regression to perform binary classification. Binary classification is named this way because it classifies the data into two results. Simply put, the result will be “yes” (1) or “no” (0). To determine whether the result is “yes” or “no”, we will use a probability function:" }, { "code": null, "e": 899, "s": 578, "text": "This probability function will give us a number from 0 to 1 indicating how likely this observation will belong to the classification that we have currently determined to be “yes”. With this, we know what we intend to do with our prediction. Now, we’ll see how to use logistic regression to calculate the equation in (1)." }, { "code": null, "e": 993, "s": 899, "text": "To perform logistic regression, the sigmoid function, presented below with its plot, is used:" }, { "code": null, "e": 1248, "s": 993, "text": "As we can see this function meets the characteristics of a probability function and equation (1). Likewise, we can see that when S(t) is very large positive, the function approaches one, and when S(t) is very large negative, the function approaches zero." }, { "code": null, "e": 1502, "s": 1248, "text": "To be able to understand how logistic regression operates, we will make an example where our function will classify people as tall or not tall. The data that we will use to calibrate our function are those corresponding to the following table (Table 1):" }, { "code": null, "e": 1760, "s": 1502, "text": "Suppose t=wx+b, our goal will be to find w and b in such a way that by placing it in S(t) it will give us the correct prediction. We can start with a random number let’s say w=1 and b=0 and if S(t) is greater than 0.5 then we will consider it a tall person." }, { "code": null, "e": 1899, "s": 1760, "text": "We notice that the parameters w=1 and b=0, don’t work since in all cases S(x)>0.5 Let’s try now with w=6 and b=-10.5, the result would be:" }, { "code": null, "e": 2008, "s": 1899, "text": "Great, we have found the w and b parameters in such a way that our function makes the predictions correctly!" }, { "code": null, "e": 2093, "s": 2008, "text": "These parameters work to make the prediction; however, many questions arise such as:" }, { "code": null, "e": 2130, "s": 2093, "text": "How do I calculate these parameters?" }, { "code": null, "e": 2173, "s": 2130, "text": "Are these parameters the most recommended?" }, { "code": null, "e": 2316, "s": 2173, "text": "To answer these questions, we will have to introduce two new topics that will help us optimize the function and understand the loss functions." }, { "code": null, "e": 2509, "s": 2316, "text": "What are the best w and b parameters? The answer to this question is very simple because we want the parameters to give us as little error as possible. For this we use the loss error function:" }, { "code": null, "e": 2684, "s": 2509, "text": "The function basically tells us how far away is our estimate of the actual value (ŷ estimation, y actual value). If we’d make a summation on all our estimation we would get:" }, { "code": null, "e": 3128, "s": 2684, "text": "This summation is the total error of all our estimates and trying to reduce this function to 0 means trying to reduce our error to 0. However, when using this function on logistic regression we get a function that is not convex (we will return to this topic later) and since it is not convex there can be several local optimal points, and a great difficulty when calculating the best w and b. To solve this issue, we will use another function:" }, { "code": null, "e": 3351, "s": 3128, "text": "The function constructed in (5) has the same purpose as the function (3), to reduce the error. We’ll do an experiment on an observation to see how the function J(ŷ,y) behaves. Let’s imagine 4 possible scenarios of J(ŷ,y)" }, { "code": null, "e": 3375, "s": 3351, "text": "Scenario 1- y=1, ŷ=.99" }, { "code": null, "e": 3474, "s": 3375, "text": "We observe that in this scenario our estimation is practically correct and when replacing, we get:" }, { "code": null, "e": 3498, "s": 3474, "text": "Scenario 2- y=1, ŷ=.01" }, { "code": null, "e": 3587, "s": 3498, "text": "We observe that in this scenario our estimation is incorrect and when replacing, we get:" }, { "code": null, "e": 3611, "s": 3587, "text": "Scenario 3- y=0, ŷ=.99" }, { "code": null, "e": 3700, "s": 3611, "text": "We observe that in this scenario our estimation is incorrect and when replacing, we get:" }, { "code": null, "e": 3724, "s": 3700, "text": "Scenario 4- y=0, ŷ=.01" }, { "code": null, "e": 3813, "s": 3724, "text": "We observe that in this scenario our estimation is incorrect and when replacing, we get:" }, { "code": null, "e": 4020, "s": 3813, "text": "Intuitively, we can observe what this function does. Correct observations have a very low error, and incorrect observations have a very high error. If we did the summation on all the observations, we’d get." }, { "code": null, "e": 4199, "s": 4020, "text": "The advantage of function (6) over function (4) is that it is convex. With function 6 it’s possible to find the optimal points in a simpler way using the gradient descent method." }, { "code": null, "e": 4441, "s": 4199, "text": "The gradient descent method seeks to tell us in which direction we need to move our b and w parameters, to optimize the function and get the minimum error. The function described in (6) is convex so you could see it as the following graphic." }, { "code": null, "e": 4751, "s": 4441, "text": "Now, suppose our loss function is J(w,b) and the parameters to be adjusted are (w,b). We want to find the point where J(w,b) is as small as possible. The gradient descent method tells us the direction where to move (w,b) to decrease J(w,b). These are the partial derivatives of (w,b), that is ∂J/∂w and ∂J/∂b." }, { "code": null, "e": 4940, "s": 4751, "text": "Knowing the directions where to move w and b. We would only need to know the magnitude to which they would move, this is called a learning rate and is usually defined as α. To finally get:" }, { "code": null, "e": 5035, "s": 4940, "text": "Finally, we will summarize the steps that must be followed to perform the logistic regression:" }, { "code": null, "e": 5190, "s": 5035, "text": "Analyze the problem and accommodate the data.Propose w and b randomly to predict your data.Calculate the errorPerform gradient descent to get new w and b." }, { "code": null, "e": 5236, "s": 5190, "text": "Analyze the problem and accommodate the data." }, { "code": null, "e": 5283, "s": 5236, "text": "Propose w and b randomly to predict your data." }, { "code": null, "e": 5303, "s": 5283, "text": "Calculate the error" }, { "code": null, "e": 5348, "s": 5303, "text": "Perform gradient descent to get new w and b." }, { "code": null, "e": 5416, "s": 5348, "text": "These 4 steps should be iterated until you get an acceptable error." }, { "code": null, "e": 5965, "s": 5416, "text": "We finally have all the theoretical elements to apply logistic regression. It is also important to know how to apply them in programming languages such as python. This language is widely used so the implementation of this algorithm is quite easy. For this example, we will use logistic regression to predict the trajectory of basketball players. The data obtained for this exercise was extracted from 1data.world. At the end of the article, the full code is displayed, so that you can follow and run the code along with the article on google colab." }, { "code": null, "e": 6039, "s": 5965, "text": "It’s important to understand what each of the columns in this table mean:" }, { "code": null, "e": 6064, "s": 6039, "text": "Name- Name of the player" }, { "code": null, "e": 6080, "s": 6064, "text": "GP-Games played" }, { "code": null, "e": 6099, "s": 6080, "text": "Min-Minutes played" }, { "code": null, "e": 6132, "s": 6099, "text": "Pts-Average points made per game" }, { "code": null, "e": 6154, "s": 6132, "text": "FGM- Field goals made" }, { "code": null, "e": 6180, "s": 6154, "text": "FGA-Field goals attempted" }, { "code": null, "e": 6210, "s": 6180, "text": "%FG-Percentage of field goals" }, { "code": null, "e": 6239, "s": 6210, "text": "3P MADE- Three-pointers made" }, { "code": null, "e": 6269, "s": 6239, "text": "3PA- Three-pointers attempted" }, { "code": null, "e": 6290, "s": 6269, "text": "FTM-Free throws made" }, { "code": null, "e": 6316, "s": 6290, "text": "FTA-Free throws attempted" }, { "code": null, "e": 6342, "s": 6316, "text": "FT%-Free throw percentage" }, { "code": null, "e": 6366, "s": 6342, "text": "OREB-Offensive rebounds" }, { "code": null, "e": 6390, "s": 6366, "text": "DREB-Defensive rebounds" }, { "code": null, "e": 6403, "s": 6390, "text": "Reb-Rebounds" }, { "code": null, "e": 6415, "s": 6403, "text": "AST-Assists" }, { "code": null, "e": 6426, "s": 6415, "text": "STL-Steals" }, { "code": null, "e": 6437, "s": 6426, "text": "BLK-Blocks" }, { "code": null, "e": 6451, "s": 6437, "text": "TOV-Turnovers" }, { "code": null, "e": 6553, "s": 6451, "text": "TARGET_5YRS-If the player lasted 5 years or more, this value will be one, and it will be 0 otherwise." }, { "code": null, "e": 6746, "s": 6553, "text": "Before logistic regression, observation and analysis of the data should be done. Pandas library is a very used library on python for handling data and we will use it to read and describe data." }, { "code": null, "e": 6876, "s": 6746, "text": "##Import library and read dataimport pandas as pdnbalog=pd.read_csv(\"path_of_file\")###See data descriptiondecri=nbalog.describe()" }, { "code": null, "e": 6966, "s": 6876, "text": "The code preceded by “#”are just comments, so with this code, we have done only 3 things:" }, { "code": null, "e": 7044, "s": 6966, "text": "Import the necessary libraries.Read the base file.Describe the existing data." }, { "code": null, "e": 7076, "s": 7044, "text": "Import the necessary libraries." }, { "code": null, "e": 7096, "s": 7076, "text": "Read the base file." }, { "code": null, "e": 7124, "s": 7096, "text": "Describe the existing data." }, { "code": null, "e": 7504, "s": 7124, "text": "The description indicates the quantity of data we have, the maximum value, minimum value, standard deviation, etc. By observing the data it can be seen that some fields are empty. Before training the model these issues have to be solved. The empty fields will be substituted by 0, and Pearson Correlation Coefficient will be used to observe the data with the highest correlation." }, { "code": null, "e": 7732, "s": 7504, "text": "###Using the data described we notice that 3P% has some blank ###fields.These fields will be filled with 0. nbalog=nbalog.fillna(0) ###We check the correlation that exists between the data. pearson=nbalog.corr(method='pearson')" }, { "code": null, "e": 7903, "s": 7732, "text": "Using Pearson Correlation Coefficient we notice the columns with the highest correlation. This way the columns that are more useful should be kept and the others dropped." }, { "code": null, "e": 8074, "s": 7903, "text": "###Some variables are higly correlated so they will be dropped ###(pearson>.8). nbalog=nbalog.drop(['MIN', 'PTS','FGM','3P Made','FTM','FTA','TOV','OREB','DREB'], axis=1)" }, { "code": null, "e": 8365, "s": 8074, "text": "With the clean data we can start training the model. For this, the library sklearn will be used. This library contains many models and is updated constantly making it very useful. In order to train the model, we will indicate which are the variables that predict and the predicted variable." }, { "code": null, "e": 8548, "s": 8365, "text": "### X are the variables that predict and y the variable we are ###trying to predict. X=nbalog[['GP','FGA','FG%','3PA','3P%','FT%','REB','AST','STL','BLK']] y=nbalog[['TARGET_5Yrs']]" }, { "code": null, "e": 8738, "s": 8548, "text": "Now, using the library sklearn the data will be divided in training and test set. With the training set, the model will be adjusted, and with the test set we will see how good the model is." }, { "code": null, "e": 8915, "s": 8738, "text": "### The data has to be divided in training and test set. from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25)" }, { "code": null, "e": 9249, "s": 8915, "text": "The previous piece of code divides the data between train and test set. The variable X is for the independent variables and y for the dependent variable. This time 75% of the set was used for training and 25% for testing. After separating the data it can be used to fit the model which in this case is the “LogisticRegression” model." }, { "code": null, "e": 9506, "s": 9249, "text": "###We import the model that will be used. from sklearn.linear_model import LogisticRegression. # Create an instance of the model. logreg = LogisticRegression() # Training the model. logreg.fit(X_train,y_train) # Do prediction. y_pred=logreg.predict(X_test)" }, { "code": null, "e": 9806, "s": 9506, "text": "So, the model has been calibrated using the function .fit and it’s ready to predict using the test data. This is done using the function .predict and using the independent variables for testing (X_test). The results obtained can be compared with the real values (y_test) to see if it’s a good model." }, { "code": null, "e": 9913, "s": 9806, "text": "# Analyzing the results. from sklearn import metrics cnf_matrix = metrics.confusion_matrix(y_test, y_pred)" }, { "code": null, "e": 10272, "s": 9913, "text": "The resulting matrix is known as confusion matrix. In the first quadrant the number of entries that were classified correctly with 0 are shown(61). The second and third quadrant sum the incorrect classification(99). Lastly, the fourth quadrant shows the classifications that were done correctly with number 1 (175). The accuracy can be calculated as follows:" }, { "code": null, "e": 10342, "s": 10272, "text": "print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))Output:.7045" }, { "code": null, "e": 10531, "s": 10342, "text": "With this, we conclude the article. As usual, I’ll leave you the code so you can test, run and try different models. Good day and congratulations on learning how to do logistic regression." }, { "code": null, "e": 10544, "s": 10531, "text": "Bibliography" }, { "code": null, "e": 10673, "s": 10544, "text": "1Rippner, N. (2017, January 24). Binary Classification Exercise Dataset. Retrieved September 24, 2020, from https://data.world/." }, { "code": null, "e": 10744, "s": 10673, "text": "2Indeed123 / CC BY-SA (https://creativecommons.org/licenses/by-sa/3.0)" }, { "code": null, "e": 10813, "s": 10744, "text": "3Lolikar / CC BY-SA (https://creativecommons.org/licenses/by-sa/4.0)" } ]
Tryit Editor v3.6 - Show Sass
/* Define standard variables and values for website */ $bgcolor: lightblue; $textcolor: darkblue; $fontsize: 18px; /* Use the variables */ body { background-color: $bgcolor; color: $textcolor; font-size: $fontsize; } body { background-color: lightblue; color: darkblue; font-size: 18px; } <!DOCTYPE html> <html> <link rel="stylesheet" href="mystyle.css"> <body> <h1>Hello World</h1> <p>This is a paragraph.</p> </body> </html> This is a paragraph.
[ { "code": null, "e": 225, "s": 0, "text": "\n/* Define standard variables and values for website */\n$bgcolor: lightblue;\n$textcolor: darkblue;\n$fontsize: 18px;\n\n/* Use the variables */\nbody {\n background-color: $bgcolor;\n color: $textcolor;\n font-size: $fontsize;\n}" }, { "code": null, "e": 304, "s": 225, "text": "\nbody {\n background-color: lightblue;\n color: darkblue;\n font-size: 18px;\n}" }, { "code": null, "e": 446, "s": 304, "text": "\n<!DOCTYPE html>\n<html>\n<link rel=\"stylesheet\" href=\"mystyle.css\">\n<body>\n\n<h1>Hello World</h1>\n\n<p>This is a paragraph.</p>\n\n</body>\n</html>" } ]
Getting and Setting Length of the Vectors in R Programming - length() Function: Title change need - GeeksforGeeks
07 Dec, 2021 length() function in R Programming Language is used to get or set the length of a vector (list) or other objects. Here we are going to get the length of the vector in R Programming, for this we will use length() function. Syntax: length(x) Parameters: x: vector or object R # R program to illustrate# length function # Specifying some vectorsx <- c(6)y <- c(1, 2, 3, 4, 5) # Calling length() function# to get length of the vectorslength(x)length(y) Output : [1] 1 [1] 5 R A = matrix( # Taking sequence of elements c(1, 2, 3, 4, 5, 6, 7, 8, 9), # No of rows nrow = 3, # No of columns ncol = 3, # By default matrices are in column-wise order # So this parameter decides how to arrange the matrix byrow = TRUE )print(A) # length of Alength(A) Output: [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 9 Here BOD is dataframe has 6 rows and 2 columns giving the biochemical oxygen demand versus time in an evaluation of water quality. and we are going to get the length of this dataframe. R print(BOD) length(BOD) Output: Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4 4 16.0 5 5 15.6 6 7 19.8 2 Note: If the parameter is a matrix or dataframe, it returns the number of variables: R # R program to create a List and get the len # The first attributes is a numeric vector# containing the employee IDs which is created# using the command hereempId = c(1, 2, 3, 4) # The second attribute is the employee name# which is created using this line of code here# which is the character vectorempName = c("Debi", "Sandeep", "Subham", "Shiba") # The third attribute is the number of employees# which is a single numeric variable.numberOfEmp = 4 # We can combine all these three different# data types into a list# containing the details of employees# which can be done using a list commandempList = list(empId, empName, numberOfEmp) print(empList) print("Length of the list:")length(empList) Output: [[1]] [1] 1 2 3 4 [[2]] [1] "Debi" "Sandeep" "Subham" "Shiba" [[3]] [1] 4 [1] "Length of the list:" 3 In R Language, we can not easily get the length of the string, first, we have to get the character of the string using split and then unlist each character to count the length. R # R program to split a string # Given Stringstring <- "Geeks For Geeks" # Basic application of length()length(string) # unlist the string and then count the lengthlength(unlist(strsplit(string, ""))) Output: 1 15 Here we are going to set the length of the vector in R Programming, for this we will use length() function. Syntax: length(x) <- value Parameters: x: vector or object R # R program to illustrate# length function # Specifying some vectorsx <- c(3)y <- c(1, 2, 3, 4, 5)z <- c(1, 2, 3, 4, 5) # Setting length of the vectorlength(x) <- 2length(y) <- 7length(z) <- 3 # Getting elements of the# new vectorsxyz Output: [1] 3 NA [1] 1 2 3 4 5 NA NA [1] 1 2 3 arorakashish0911 kumar_satyam simmytarika5 R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? 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 Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 25416, "s": 25388, "text": "\n07 Dec, 2021" }, { "code": null, "e": 25530, "s": 25416, "text": "length() function in R Programming Language is used to get or set the length of a vector (list) or other objects." }, { "code": null, "e": 25638, "s": 25530, "text": "Here we are going to get the length of the vector in R Programming, for this we will use length() function." }, { "code": null, "e": 25656, "s": 25638, "text": "Syntax: length(x)" }, { "code": null, "e": 25669, "s": 25656, "text": "Parameters: " }, { "code": null, "e": 25689, "s": 25669, "text": "x: vector or object" }, { "code": null, "e": 25691, "s": 25689, "text": "R" }, { "code": "# R program to illustrate# length function # Specifying some vectorsx <- c(6)y <- c(1, 2, 3, 4, 5) # Calling length() function# to get length of the vectorslength(x)length(y)", "e": 25866, "s": 25691, "text": null }, { "code": null, "e": 25876, "s": 25866, "text": "Output : " }, { "code": null, "e": 25888, "s": 25876, "text": "[1] 1\n[1] 5" }, { "code": null, "e": 25890, "s": 25888, "text": "R" }, { "code": "A = matrix( # Taking sequence of elements c(1, 2, 3, 4, 5, 6, 7, 8, 9), # No of rows nrow = 3, # No of columns ncol = 3, # By default matrices are in column-wise order # So this parameter decides how to arrange the matrix byrow = TRUE )print(A) # length of Alength(A)", "e": 26200, "s": 25890, "text": null }, { "code": null, "e": 26208, "s": 26200, "text": "Output:" }, { "code": null, "e": 26291, "s": 26208, "text": " [,1] [,2] [,3]\n[1,] 1 2 3\n[2,] 4 5 6\n[3,] 7 8 9\n\n9" }, { "code": null, "e": 26476, "s": 26291, "text": "Here BOD is dataframe has 6 rows and 2 columns giving the biochemical oxygen demand versus time in an evaluation of water quality. and we are going to get the length of this dataframe." }, { "code": null, "e": 26478, "s": 26476, "text": "R" }, { "code": "print(BOD) length(BOD)", "e": 26501, "s": 26478, "text": null }, { "code": null, "e": 26509, "s": 26501, "text": "Output:" }, { "code": null, "e": 26610, "s": 26509, "text": " Time demand\n1 1 8.3\n2 2 10.3\n3 3 19.0\n4 4 16.0\n5 5 15.6\n6 7 19.8\n\n2" }, { "code": null, "e": 26695, "s": 26610, "text": "Note: If the parameter is a matrix or dataframe, it returns the number of variables:" }, { "code": null, "e": 26697, "s": 26695, "text": "R" }, { "code": "# R program to create a List and get the len # The first attributes is a numeric vector# containing the employee IDs which is created# using the command hereempId = c(1, 2, 3, 4) # The second attribute is the employee name# which is created using this line of code here# which is the character vectorempName = c(\"Debi\", \"Sandeep\", \"Subham\", \"Shiba\") # The third attribute is the number of employees# which is a single numeric variable.numberOfEmp = 4 # We can combine all these three different# data types into a list# containing the details of employees# which can be done using a list commandempList = list(empId, empName, numberOfEmp) print(empList) print(\"Length of the list:\")length(empList)", "e": 27394, "s": 26697, "text": null }, { "code": null, "e": 27402, "s": 27394, "text": "Output:" }, { "code": null, "e": 27514, "s": 27402, "text": "[[1]]\n[1] 1 2 3 4\n\n[[2]]\n[1] \"Debi\" \"Sandeep\" \"Subham\" \"Shiba\" \n\n[[3]]\n[1] 4\n\n[1] \"Length of the list:\"\n\n3" }, { "code": null, "e": 27691, "s": 27514, "text": "In R Language, we can not easily get the length of the string, first, we have to get the character of the string using split and then unlist each character to count the length." }, { "code": null, "e": 27693, "s": 27691, "text": "R" }, { "code": "# R program to split a string # Given Stringstring <- \"Geeks For Geeks\" # Basic application of length()length(string) # unlist the string and then count the lengthlength(unlist(strsplit(string, \"\")))", "e": 27895, "s": 27693, "text": null }, { "code": null, "e": 27903, "s": 27895, "text": "Output:" }, { "code": null, "e": 27908, "s": 27903, "text": "1\n15" }, { "code": null, "e": 28016, "s": 27908, "text": "Here we are going to set the length of the vector in R Programming, for this we will use length() function." }, { "code": null, "e": 28043, "s": 28016, "text": "Syntax: length(x) <- value" }, { "code": null, "e": 28056, "s": 28043, "text": "Parameters: " }, { "code": null, "e": 28076, "s": 28056, "text": "x: vector or object" }, { "code": null, "e": 28078, "s": 28076, "text": "R" }, { "code": "# R program to illustrate# length function # Specifying some vectorsx <- c(3)y <- c(1, 2, 3, 4, 5)z <- c(1, 2, 3, 4, 5) # Setting length of the vectorlength(x) <- 2length(y) <- 7length(z) <- 3 # Getting elements of the# new vectorsxyz", "e": 28313, "s": 28078, "text": null }, { "code": null, "e": 28322, "s": 28313, "text": "Output: " }, { "code": null, "e": 28367, "s": 28322, "text": "[1] 3 NA\n[1] 1 2 3 4 5 NA NA\n[1] 1 2 3" }, { "code": null, "e": 28384, "s": 28367, "text": "arorakashish0911" }, { "code": null, "e": 28397, "s": 28384, "text": "kumar_satyam" }, { "code": null, "e": 28410, "s": 28397, "text": "simmytarika5" }, { "code": null, "e": 28428, "s": 28410, "text": "R Object-Function" }, { "code": null, "e": 28446, "s": 28428, "text": "R Vector-Function" }, { "code": null, "e": 28457, "s": 28446, "text": "R Language" }, { "code": null, "e": 28555, "s": 28457, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28564, "s": 28555, "text": "Comments" }, { "code": null, "e": 28577, "s": 28564, "text": "Old Comments" }, { "code": null, "e": 28635, "s": 28577, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 28679, "s": 28635, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 28731, "s": 28679, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 28763, "s": 28731, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 28815, "s": 28763, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28853, "s": 28815, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28888, "s": 28853, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28946, "s": 28888, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28982, "s": 28946, "text": "K-Means Clustering in R Programming" } ]
matplotlib.pyplot.arrow() in Python
20 Jul, 2021 Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. It provides MATLAB like interface only difference is that it uses Python and is open source. This function adds the arrow to the graph based on the coordinates passed to it. Syntax: matplotlib.pyplot.arrow(x, y, dx, dy, **kwargs)Parameters: x, y: The x and y coordinates of the arrow base. dx, dy: The length of the arrow along x and y direction. **kwargs: Optional arguments that helps in adding properties to arrow, like adding color to arrow, changing width of arrow Example #1 Python3 import matplotlib.pyplot as plt # Initializing values# of x and yx =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] # Plotting the graphplt.plot(x, y) # Adding an arrow to graph starting# from the base (2, 4) and with the# length of 2 units from both x and y# And setting the width of arrow for# better visualizationplt.arrow(2, 4, 2, 2, width = 0.05) # Showing the graphplt.show() Output: Example 2# Python3 import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] plt.plot(x, y) # Increasing head_width of# the arrow by setting# head_width parameterplt.arrow(2, 4, 2, 2, head_width = 0.2, width = 0.05) plt.show() Output: Example #3 Python3 import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10]plt.plot(x, y) # changing the edge color# to greenplt.arrow(2, 4, 2, 2, head_width = 0.2, width = 0.05, ec ='green') plt.show() Output: arorakashish0911 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Enumerate() in Python Python Dictionary Python OOPs Concepts Different ways to create Pandas Dataframe *args and **kwargs in Python Python Classes and Objects Introduction To PYTHON Stack in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jul, 2021" }, { "code": null, "e": 375, "s": 28, "text": "Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose. It provides MATLAB like interface only difference is that it uses Python and is open source." }, { "code": null, "e": 457, "s": 375, "text": "This function adds the arrow to the graph based on the coordinates passed to it. " }, { "code": null, "e": 755, "s": 457, "text": "Syntax: matplotlib.pyplot.arrow(x, y, dx, dy, **kwargs)Parameters: x, y: The x and y coordinates of the arrow base. dx, dy: The length of the arrow along x and y direction. **kwargs: Optional arguments that helps in adding properties to arrow, like adding color to arrow, changing width of arrow " }, { "code": null, "e": 768, "s": 755, "text": "Example #1 " }, { "code": null, "e": 776, "s": 768, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Initializing values# of x and yx =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] # Plotting the graphplt.plot(x, y) # Adding an arrow to graph starting# from the base (2, 4) and with the# length of 2 units from both x and y# And setting the width of arrow for# better visualizationplt.arrow(2, 4, 2, 2, width = 0.05) # Showing the graphplt.show()", "e": 1146, "s": 776, "text": null }, { "code": null, "e": 1155, "s": 1146, "text": "Output: " }, { "code": null, "e": 1168, "s": 1155, "text": "Example 2# " }, { "code": null, "e": 1176, "s": 1168, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] plt.plot(x, y) # Increasing head_width of# the arrow by setting# head_width parameterplt.arrow(2, 4, 2, 2, head_width = 0.2, width = 0.05) plt.show()", "e": 1415, "s": 1176, "text": null }, { "code": null, "e": 1424, "s": 1415, "text": "Output: " }, { "code": null, "e": 1437, "s": 1424, "text": "Example #3 " }, { "code": null, "e": 1445, "s": 1437, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10]plt.plot(x, y) # changing the edge color# to greenplt.arrow(2, 4, 2, 2, head_width = 0.2, width = 0.05, ec ='green') plt.show()", "e": 1670, "s": 1445, "text": null }, { "code": null, "e": 1679, "s": 1670, "text": "Output: " }, { "code": null, "e": 1698, "s": 1681, "text": "arorakashish0911" }, { "code": null, "e": 1716, "s": 1698, "text": "Python-matplotlib" }, { "code": null, "e": 1723, "s": 1716, "text": "Python" }, { "code": null, "e": 1821, "s": 1723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1851, "s": 1821, "text": "Iterate over a list in Python" }, { "code": null, "e": 1896, "s": 1851, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 1918, "s": 1896, "text": "Enumerate() in Python" }, { "code": null, "e": 1936, "s": 1918, "text": "Python Dictionary" }, { "code": null, "e": 1957, "s": 1936, "text": "Python OOPs Concepts" }, { "code": null, "e": 1999, "s": 1957, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2028, "s": 1999, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2055, "s": 2028, "text": "Python Classes and Objects" }, { "code": null, "e": 2078, "s": 2055, "text": "Introduction To PYTHON" } ]
How to store a NULL value in a particular column of a DB2 table using COBOL-DB2 program?
We will make use of NULL indicator in order to store a NULL value in any column of a DB2 table. Firstly, we should move a value -1 in the NULL indicator in our COBOL-DB2 program. After that we execute UPDATE or INSERT query to store the NULL value. For example, if we have to update a NULL value in the ORDER_DESCRIPTION column of the ORDER table where ORDER_ID is 3345612. A020-UPDATE-ORDERS. MOVE -1 TO ORDER-DESCRIPTION-N MOVE SPACES TO ORDER-DESCRIPTION-DATA EXEC SQL UPDATE ORDERS SET ORDER_DESCRIPTION = :ORDER-DESCRIPTION-DATA :ORDER-DESCRIPTION-N WHERE ORDER_ID = ‘3345612’ END-SQL. ORDER-DESCRIPTION-N is the NULL indicator here. The important point to note here is that the second line in the paragraph i.e the line highlighted with orange is optional. Once we have moved -1 in the null indicator then no matter what value we give in the data field, only NULL value will be stored in DB2 table.
[ { "code": null, "e": 1436, "s": 1187, "text": "We will make use of NULL indicator in order to store a NULL value in any column of a DB2 table. Firstly, we should move a value -1 in the NULL indicator in our COBOL-DB2 program. After that we execute UPDATE or INSERT query to store the NULL value." }, { "code": null, "e": 1561, "s": 1436, "text": "For example, if we have to update a NULL value in the ORDER_DESCRIPTION column of\nthe ORDER table where ORDER_ID is 3345612." }, { "code": null, "e": 1820, "s": 1561, "text": "A020-UPDATE-ORDERS.\n MOVE -1 TO ORDER-DESCRIPTION-N\n MOVE SPACES TO ORDER-DESCRIPTION-DATA\n EXEC SQL\n UPDATE ORDERS\n SET ORDER_DESCRIPTION =\n :ORDER-DESCRIPTION-DATA\n :ORDER-DESCRIPTION-N\n WHERE ORDER_ID = ‘3345612’\nEND-SQL." }, { "code": null, "e": 2134, "s": 1820, "text": "ORDER-DESCRIPTION-N is the NULL indicator here. The important point to note here is that the second line in the paragraph i.e the line highlighted with orange is optional. Once we have moved -1 in the null indicator then no matter what value we give in the data field,\nonly NULL value will be stored in DB2 table." } ]
Program to delete all even nodes from a Singly Linked List
30 Jun, 2022 Given a singly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input: LL = 1 -> 4 -> 3 -> 18 -> 19 Output: 1 -> 3 -> 19Input: LL = 5 -> 3 -> 6 -> 8 -> 4 -> 1 -> 2 -> 9 Output: 5 -> 3 -> 1 -> 9 Approach 1: The idea is to traverse the nodes of the singly linked list one by one and get the pointer of the nodes having even data. Delete those nodes by following the approach used in this post. Below is the implementation of the above idea: C++ Java Python3 C# Javascript // C++ implementation to delete all// even nodes from the singly linked list #include <bits/stdc++.h>using namespace std; // Node of the singly linked liststruct Node{ int data; struct Node* next;}; // Function to insert a node at// the beginning of the singly// Linked Listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc( sizeof( struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to delete a node in a// singly Linked List.// head_ref --> Pointer to head// node pointer.// key --> Node to be deletedvoid deleteNode(struct Node** head_ref, int key){ // Store head node struct Node *temp = *head_ref, *prev; // If head node itself holds // the key to be deleted if (temp != NULL && temp->data == key) { // Changed head *head_ref = temp->next; return; } // Search for the key to be // deleted, keep track of the // previous node as we need // to change 'prev->next' while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } // If key was not present // in linked list if (temp == NULL) return; // Unlink the node from // linked list prev->next = temp->next; } // Function to delete all the// even nodes from the// singly linked listvoid deleteEvenNodes(Node** head_ref){ Node* ptr = *head_ref; // Node* next; while (ptr != NULL) { // next = ptr->next; // If true, delete node 'ptr' if (ptr->data % 2 == 0) deleteNode(head_ref, ptr->data); ptr = ptr->next; }} // This function prints contents// of linked list starting from// the given nodevoid printList(struct Node* node){ while (node != NULL) { printf(" %d -> ", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 19); push(&head, 18); push(&head, 3); push(&head, 4); push(&head, 1); printf("Initial List: "); printList(head); deleteEvenNodes(&head); printf("\nFinal List: "); printList(head);} // Java implementation to delete all// even nodes from the singly linked listclass LinkedList{ // head of listNode head; // Linked list Nodeclass Node{ int data; Node next; Node(int d) { data = d; next = null; }} // Function to insert a node at// the beginning of the singly// Linked Listpublic void push(int new_data){ Node new_node = new Node(new_data); new_node.next = head; head = new_node;} // Function to delete a node in a// singly Linked List.void deleteNode(int key){ // Store head node Node temp = head, prev = null; // If head node itself holds the // key to be deleted if (temp != null && temp.data == key) { // Changed head head = temp.next; return; } // Search for the key to be deleted, // keep track of the previous node // as we need to change temp.next while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next;} // Function to delete all the nodes// from linked list containing// even numbers.void deleteEvenNodes(){ Node ptr = head; // loop to iterate the linked list while(ptr != null) { // If containing element is even if(ptr.data % 2 == 0) { // Delete the node deleteNode(ptr.data); } ptr = ptr.next; }} // This function prints contents of linked// list starting from the given nodepublic void printList(){ Node ptr = head; while (ptr != null) { System.out.print(ptr.data + "-> "); ptr = ptr.next; }} // Driver codepublic static void main(String[] args){ LinkedList head = new LinkedList(); head.push(19); head.push(18); head.push(3); head.push(4); head.push(1); System.out.print("\nInitial List: "); head.printList(); head.deleteEvenNodes(); System.out.print("\nFinal List: "); head.printList();}} // This code is contributed by Amit Mangal # Python3 implementation to delete all# even nodes from the singly linked list# Node classclass Node: # Function to initialize the node object def __init__(self, data): # Assign data self.data = data # Initialize # next as null self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at # the beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Method to print the linked list def printList(self): # Object to iterate # the list ptr = self.head # Loop to iterate list while(ptr != None): print(ptr.data, '-> ', end = '') # Moving the iterating object # to next node ptr = ptr.next print() # Method to delete a node in # a singly linked list. def deleteNode(self, key): temp = self.head # If head node itself holds # the key to be deleted. if(temp != None and temp.data == key): # Changing head of list. self.head = temp.next return # Search for the key to be # deleted, keep track of the # previous node as we need # to change prev.next while(temp != None and temp.data != key): prev = temp temp = temp.next # If is not present in list if(temp == None): return # Unlink the node from # linked list prev.next = temp.next # Method to delete all the # even nodes from singly # linked list. def deleteEvenNodes(self): ptr = self.head # Loop to iterate the # linked list. while(ptr != None): # If node contains even number. if(ptr.data % 2 == 0): # Deleting the node self.deleteNode(ptr.data) ptr = ptr.next # Driver codeif __name__=='__main__': head = LinkedList() # Pushing elements at start # of linked list. head.push(19) head.push(18) head.push(3) head.push(4) head.push(1) # Print initial linked list print("Initial list: ", end = '') head.printList() # Calling the function to delete # nodes containing even numbers. head.deleteEvenNodes() # Print the final list print("Final list: ", end = '') head.printList() # This code is contributed by Amit Mangal // C# implementation to delete all// even nodes from the singly linked listusing System;class List{ // head of list Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Function to insert a node at // the beginning of the singly // Linked List public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. void deleteNode(int key) { // Store head node Node temp = head, prev = null; // If head node itself holds the // key to be deleted if (temp != null && temp.data == key) { // Changed head head = temp.next; return; } // Search for the key to be deleted, // keep track of the previous node // as we need to change temp.next while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present // in linked list if (temp == null) return; // Unlink the node from // linked list prev.next = temp.next; } // Function to delete // all the nodes from // linked list containing // even numbers. void deleteEvenNodes() { Node ptr = head; // loop to iterate the linked list while(ptr != null) { // If containing element is even if(ptr.data % 2 == 0) { // Delete the node deleteNode(ptr.data); } ptr = ptr.next; } } // This function prints contents of linked // list starting from the given node public void printList() { Node ptr = head; while (ptr != null) { Console.Write(ptr.data + "-> "); ptr = ptr.next; } } // Driver code public static void Main(String []args) { List head = new List(); head.push(19); head.push(18); head.push(3); head.push(4); head.push(1); Console.Write("\nInitial List: "); head.printList(); head.deleteEvenNodes(); Console.Write("\nFinal List: "); head.printList(); }} // This code contributed by gauravrajput1 <script>// javascript implementation to delete all// even nodes from the singly linked list // head of list var head; // Linked list Node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to insert a node at // the beginning of the singly // Linked List function push(new_data) {var new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. function deleteNode(key) { // Store head nodevar temp = head, prev = null; // If head node itself holds the // key to be deleted if (temp != null && temp.data == key) { // Changed head head = temp.next; return; } // Search for the key to be deleted, // keep track of the previous node // as we need to change temp.next while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next; } // Function to delete all the nodes // from linked list containing // even numbers. function deleteEvenNodes() {var ptr = head; // loop to iterate the linked list while (ptr != null) { // If containing element is even if (ptr.data % 2 == 0) { // Delete the node deleteNode(ptr.data); } ptr = ptr.next; } } // This function prints contents of linked // list starting from the given node function printList() {var ptr = head; while (ptr != null) { document.write(ptr.data + "-> "); ptr = ptr.next; } } // Driver code push(19); push(18); push(3); push(4); push(1); document.write("<br/>Initial List: "); printList(); deleteEvenNodes(); document.write("<br/>Final List: "); printList(); // This code contributed by aashish1995</script> Initial List: 1 -> 4 -> 3 -> 18 -> 19 -> Final List: 1 -> 3 -> 19 -> Time Complexity: O(N^2) As the complexity of deleteNode function is O(N) and we need to call it for every even number. Auxiliary Space: O(1) As constant extra space is used. Approach 2: The idea is to traverse the linked list one by one and get the pointer of nodes having even values. Also keep deleting the nodes having even values using the method used in this post. We want the time complexity to be O(1) for deleting a given node in order to get O(N) solution for overall approach. The algorithm for the deleteNode function: In the deleteNode function we get the pointer of the node to be deleted directly.Copy the value of next node’s to this node.delete the next node. In the deleteNode function we get the pointer of the node to be deleted directly. Copy the value of next node’s to this node. delete the next node. The only thing to keep in mind is that the node to be deleted should not be the last node if we are using the above method to delete the node, but it gives the result in O(1) time so we will use this in our solution. The algorithm for the deleteEvenNodes function: We get the head of the linked list as a function parameter.Use dummy pointer variables ptr and prev which are used to store the current and previous node respectively.Traverse the linked list before last element using a while loop and do the following: delete the nodes with odd values and keep updating the prev and ptr pointersThe case of last node is handled explicitly at the end. We get the head of the linked list as a function parameter. Use dummy pointer variables ptr and prev which are used to store the current and previous node respectively. Traverse the linked list before last element using a while loop and do the following: delete the nodes with odd values and keep updating the prev and ptr pointers The case of last node is handled explicitly at the end. Full implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation to delete all// even valed nodes from the singly linked list #include <bits/stdc++.h>using namespace std; // Node of the singly linked liststruct Node { int data; struct Node* next;}; // Function to insert a node at// the beginning of the singly// Linked Listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to delete a node in a// singly Linked List.// node --> Pointer to given nodevoid deleteNode(struct Node* node){ // copy the next node's value in current node node->data = node->next->data; // store the pointer to node's next in a temp variable struct Node* temp = node->next; // connect the node with node's next's next node->next = node->next->next; // delete the temp delete (temp);} // Function to delete all the// even valued nodes from the// singly linked listvoid deleteEvenNodes(Node** head_ref){ Node* ptr = *head_ref; Node* prev; // mark the current head with ptr pointer while (ptr != NULL && ptr->next != NULL) { // traverse the linked list before the last element if (ptr->data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else { prev = ptr; ptr = ptr->next; } // move the pointer to the next element and store // the prev node } if (ptr == *head_ref && ptr->data % 2 == 0) *head_ref = NULL; else if (ptr->data % 2 == 0) { prev->next = NULL; delete ptr; }} // This function prints contents// of linked list starting from// the given nodevoid printList(struct Node* node){ while (node != NULL) { printf(" %d -> ", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 2); push(&head, 6); push(&head, 15); push(&head, 16); push(&head, 18); printf("Initial List: "); printList(head); deleteEvenNodes(&head); printf("\nFinal List: "); printList(head);} // This code was contributed by Abhijeet Kumar // Java implementation to delete all// even valued nodes from the singly linked listclass LinkedList{ // head of listNode head; // Linked list Nodeclass Node{ int data; Node next; Node(int d) { data = d; next = null; }} // Function to insert a node at// the beginning of the singly// Linked Listpublic void push(int new_data){ Node new_node = new Node(new_data); new_node.next = head; head = new_node;} // Function to delete a node in a// singly Linked List.void deleteNode(Node node){ // copy the next node's value in current node node.data = node.next.data; // connect the node with node's next's next node.next = node.next.next;} // Function to delete all the nodes// from linked list containing// even numbers.void deleteEvenNodes(){ Node ptr = head; Node prev = null; //mark the current head with ptr pointer while (ptr!=null && ptr.next != null) { // traverse the linked list before the last element if (ptr.data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else{ prev = ptr; ptr = ptr.next; } // move the pointer to the next element and store the previous pointer } if(ptr==head && ptr.data % 2 == 0) head = null; else if(ptr.data % 2 == 0) prev.next = null;} // This function prints contents of linked// list starting from the given nodepublic void printList(){ Node ptr = head; while (ptr != null) { System.out.print(ptr.data + "-> "); ptr = ptr.next; }} // Driver codepublic static void main(String[] args){ LinkedList head = new LinkedList(); head.push(2); head.push(6); head.push(15); head.push(16); head.push(18); System.out.print("\nInitial List: "); head.printList(); head.deleteEvenNodes(); System.out.print("\nFinal List: "); head.printList();}} // This code is contributed by Abhijeet Kumar(abhijeet19403) # Python3 implementation to delete all# even valued nodes from the singly linked list # Node classclass Node: # Function to initialize the node object def __init__(self, data): # Assign data self.data = data # Initialize # next as null self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at # the beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Method to print the linked list def printList(self): # Object to iterate # the list ptr = self.head # Loop to iterate list while(ptr != None): print(ptr.data, '-> ', end = '') # Moving the iterating object # to next node ptr = ptr.next print() # Method to delete a node in # a singly linked list. def deleteNode(self,node): # copy the next node's value in current node node.data = node.next.data # connect the node with node's next's next node.next = node.next.next # Method to delete all the # even valued nodes from singly # linked list. def deleteEvenNodes(self): #mark the current head with ptr pointer ptr = self.head prev = self.head # traverse the linked list before the last element while (ptr!=None and ptr.next != None): # delete the node if the value of the node is even if (ptr.data % 2 == 0): self.deleteNode(ptr) # move the pointer to the next element and store the previous pointer else: prev = ptr ptr = ptr.next if(ptr==self.head and ptr.data % 2 == 0): head = None elif(ptr.data % 2 == 0): prev.next = None # Driver codeif __name__=='__main__': head = LinkedList() # Pushing elements at start # of linked list. head.push(18) head.push(16) head.push(15) head.push(6) head.push(2) # Print initial linked list print("Initial list: ", end = '') head.printList() # Calling the function to delete # nodes containing even numbers. head.deleteEvenNodes() # Print the final list print("Final list: ", end = '') head.printList() # This code is contributed by Abhijeet Kumar(abhijeet19403) // C# implementation to delete all// even valued nodes from the singly linked listusing System;class List{ // head of list Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Function to insert a node at // the beginning of the singly // Linked List public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. void deleteNode(Node node) { // copy the next node's value in current node node.data = node.next.data; // connect the node with node's next's next node.next = node.next.next; } // Function to delete // all the nodes from // linked list containing // even numbers. void deleteEvenNodes() { Node ptr = head; Node prev = null; //mark the current head with ptr pointer while (ptr!=null && ptr.next != null) { // traverse the linked list before the last element if (ptr.data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else{ prev = ptr; ptr = ptr.next; } // move the pointer to the next element and store the previous pointer } if(ptr==head && ptr.data % 2 == 0) head = null; else if(ptr.data % 2 == 0) prev.next = null; } // This function prints contents of linked // list starting from the given node public void printList() { Node ptr = head; while (ptr != null) { Console.Write(ptr.data + "-> "); ptr = ptr.next; } } // Driver code public static void Main(String []args) { List head = new List(); head.push(2); head.push(6); head.push(15); head.push(16); head.push(18); Console.Write("\nInitial List: "); head.printList(); head.deleteEvenNodes(); Console.Write("\nFinal List: "); head.printList(); }} // This code contributed by Abhijeet Kumar(abhijeet19403) <script>// javascript implementation to delete all// even nodes from the singly linked list // head of list var head; // Linked list Node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to insert a node at // the beginning of the singly // Linked List function push(new_data) {var new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. void deleteNode(Node node) { // copy the next node's value in current node node.data = node.next.data; // connect the node with node's next's next node.next = node.next.next; } // Function to delete all the nodes // from linked list containing // even numbers. function deleteEvenNodes() { var ptr = head,prev = null; //mark the current head with ptr pointer while (ptr!=null && ptr.next != null) { // traverse the linked list before the last element if (ptr.data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else{ prev = ptr; ptr = ptr.next; } // move the pointer to the next element and store the previous pointer } if(ptr==head && ptr.data % 2 == 0) head = null; else if(ptr.data % 2 == 0) prev.next = null; } // This function prints contents of linked // list starting from the given node function printList() { var ptr = head; while (ptr != null) { document.write(ptr.data + "-> "); ptr = ptr.next; } } // Driver code push(2); push(6); push(15); push(16); push(18); document.write("<br/>Initial List: "); printList(); deleteEvenNodes(); document.write("<br/>Final List: "); printList(); // This code contributed by Abhijeet Kumar(abhijeet19403)</script> Initial List: 18 -> 16 -> 15 -> 6 -> 2 -> Final List: 15 -> Time Complexity: O(N) As we are visiting every node and deleting odd valued node which is O(1) operation. Auxiliary Space: O(1) As constant extra space is used. This approach was contributed by Abhijeet Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. amit_mangal_ GauravRajput1 aashish1995 shubhamrajput6156 abhijeet19403 Data Structures Linked List School Programming Write From Home Data Structures Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-II Binary Search Tree | Set 3 (Iterative Delete) Data Structures | Linked List | Question 4 Data Structures | Balanced Binary Search Trees | Question 5 Improving Linear Search Technique Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Doubly Linked List | Set 1 (Introduction and Insertion)
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2022" }, { "code": null, "e": 158, "s": 54, "text": "Given a singly linked list containing N nodes, the task is to delete all the even nodes from the list. " }, { "code": null, "e": 170, "s": 158, "text": "Examples: " }, { "code": null, "e": 302, "s": 170, "text": "Input: LL = 1 -> 4 -> 3 -> 18 -> 19 Output: 1 -> 3 -> 19Input: LL = 5 -> 3 -> 6 -> 8 -> 4 -> 1 -> 2 -> 9 Output: 5 -> 3 -> 1 -> 9 " }, { "code": null, "e": 315, "s": 302, "text": "Approach 1: " }, { "code": null, "e": 501, "s": 315, "text": "The idea is to traverse the nodes of the singly linked list one by one and get the pointer of the nodes having even data. Delete those nodes by following the approach used in this post." }, { "code": null, "e": 549, "s": 501, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 553, "s": 549, "text": "C++" }, { "code": null, "e": 558, "s": 553, "text": "Java" }, { "code": null, "e": 566, "s": 558, "text": "Python3" }, { "code": null, "e": 569, "s": 566, "text": "C#" }, { "code": null, "e": 580, "s": 569, "text": "Javascript" }, { "code": "// C++ implementation to delete all// even nodes from the singly linked list #include <bits/stdc++.h>using namespace std; // Node of the singly linked liststruct Node{ int data; struct Node* next;}; // Function to insert a node at// the beginning of the singly// Linked Listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc( sizeof( struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to delete a node in a// singly Linked List.// head_ref --> Pointer to head// node pointer.// key --> Node to be deletedvoid deleteNode(struct Node** head_ref, int key){ // Store head node struct Node *temp = *head_ref, *prev; // If head node itself holds // the key to be deleted if (temp != NULL && temp->data == key) { // Changed head *head_ref = temp->next; return; } // Search for the key to be // deleted, keep track of the // previous node as we need // to change 'prev->next' while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } // If key was not present // in linked list if (temp == NULL) return; // Unlink the node from // linked list prev->next = temp->next; } // Function to delete all the// even nodes from the// singly linked listvoid deleteEvenNodes(Node** head_ref){ Node* ptr = *head_ref; // Node* next; while (ptr != NULL) { // next = ptr->next; // If true, delete node 'ptr' if (ptr->data % 2 == 0) deleteNode(head_ref, ptr->data); ptr = ptr->next; }} // This function prints contents// of linked list starting from// the given nodevoid printList(struct Node* node){ while (node != NULL) { printf(\" %d -> \", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 19); push(&head, 18); push(&head, 3); push(&head, 4); push(&head, 1); printf(\"Initial List: \"); printList(head); deleteEvenNodes(&head); printf(\"\\nFinal List: \"); printList(head);}", "e": 2865, "s": 580, "text": null }, { "code": "// Java implementation to delete all// even nodes from the singly linked listclass LinkedList{ // head of listNode head; // Linked list Nodeclass Node{ int data; Node next; Node(int d) { data = d; next = null; }} // Function to insert a node at// the beginning of the singly// Linked Listpublic void push(int new_data){ Node new_node = new Node(new_data); new_node.next = head; head = new_node;} // Function to delete a node in a// singly Linked List.void deleteNode(int key){ // Store head node Node temp = head, prev = null; // If head node itself holds the // key to be deleted if (temp != null && temp.data == key) { // Changed head head = temp.next; return; } // Search for the key to be deleted, // keep track of the previous node // as we need to change temp.next while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next;} // Function to delete all the nodes// from linked list containing// even numbers.void deleteEvenNodes(){ Node ptr = head; // loop to iterate the linked list while(ptr != null) { // If containing element is even if(ptr.data % 2 == 0) { // Delete the node deleteNode(ptr.data); } ptr = ptr.next; }} // This function prints contents of linked// list starting from the given nodepublic void printList(){ Node ptr = head; while (ptr != null) { System.out.print(ptr.data + \"-> \"); ptr = ptr.next; }} // Driver codepublic static void main(String[] args){ LinkedList head = new LinkedList(); head.push(19); head.push(18); head.push(3); head.push(4); head.push(1); System.out.print(\"\\nInitial List: \"); head.printList(); head.deleteEvenNodes(); System.out.print(\"\\nFinal List: \"); head.printList();}} // This code is contributed by Amit Mangal", "e": 4970, "s": 2865, "text": null }, { "code": "# Python3 implementation to delete all# even nodes from the singly linked list# Node classclass Node: # Function to initialize the node object def __init__(self, data): # Assign data self.data = data # Initialize # next as null self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at # the beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Method to print the linked list def printList(self): # Object to iterate # the list ptr = self.head # Loop to iterate list while(ptr != None): print(ptr.data, '-> ', end = '') # Moving the iterating object # to next node ptr = ptr.next print() # Method to delete a node in # a singly linked list. def deleteNode(self, key): temp = self.head # If head node itself holds # the key to be deleted. if(temp != None and temp.data == key): # Changing head of list. self.head = temp.next return # Search for the key to be # deleted, keep track of the # previous node as we need # to change prev.next while(temp != None and temp.data != key): prev = temp temp = temp.next # If is not present in list if(temp == None): return # Unlink the node from # linked list prev.next = temp.next # Method to delete all the # even nodes from singly # linked list. def deleteEvenNodes(self): ptr = self.head # Loop to iterate the # linked list. while(ptr != None): # If node contains even number. if(ptr.data % 2 == 0): # Deleting the node self.deleteNode(ptr.data) ptr = ptr.next # Driver codeif __name__=='__main__': head = LinkedList() # Pushing elements at start # of linked list. head.push(19) head.push(18) head.push(3) head.push(4) head.push(1) # Print initial linked list print(\"Initial list: \", end = '') head.printList() # Calling the function to delete # nodes containing even numbers. head.deleteEvenNodes() # Print the final list print(\"Final list: \", end = '') head.printList() # This code is contributed by Amit Mangal", "e": 7794, "s": 4970, "text": null }, { "code": "// C# implementation to delete all// even nodes from the singly linked listusing System;class List{ // head of list Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Function to insert a node at // the beginning of the singly // Linked List public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. void deleteNode(int key) { // Store head node Node temp = head, prev = null; // If head node itself holds the // key to be deleted if (temp != null && temp.data == key) { // Changed head head = temp.next; return; } // Search for the key to be deleted, // keep track of the previous node // as we need to change temp.next while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present // in linked list if (temp == null) return; // Unlink the node from // linked list prev.next = temp.next; } // Function to delete // all the nodes from // linked list containing // even numbers. void deleteEvenNodes() { Node ptr = head; // loop to iterate the linked list while(ptr != null) { // If containing element is even if(ptr.data % 2 == 0) { // Delete the node deleteNode(ptr.data); } ptr = ptr.next; } } // This function prints contents of linked // list starting from the given node public void printList() { Node ptr = head; while (ptr != null) { Console.Write(ptr.data + \"-> \"); ptr = ptr.next; } } // Driver code public static void Main(String []args) { List head = new List(); head.push(19); head.push(18); head.push(3); head.push(4); head.push(1); Console.Write(\"\\nInitial List: \"); head.printList(); head.deleteEvenNodes(); Console.Write(\"\\nFinal List: \"); head.printList(); }} // This code contributed by gauravrajput1", "e": 9970, "s": 7794, "text": null }, { "code": "<script>// javascript implementation to delete all// even nodes from the singly linked list // head of list var head; // Linked list Node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to insert a node at // the beginning of the singly // Linked List function push(new_data) {var new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. function deleteNode(key) { // Store head nodevar temp = head, prev = null; // If head node itself holds the // key to be deleted if (temp != null && temp.data == key) { // Changed head head = temp.next; return; } // Search for the key to be deleted, // keep track of the previous node // as we need to change temp.next while (temp != null && temp.data != key) { prev = temp; temp = temp.next; } // If key was not present in linked list if (temp == null) return; // Unlink the node from linked list prev.next = temp.next; } // Function to delete all the nodes // from linked list containing // even numbers. function deleteEvenNodes() {var ptr = head; // loop to iterate the linked list while (ptr != null) { // If containing element is even if (ptr.data % 2 == 0) { // Delete the node deleteNode(ptr.data); } ptr = ptr.next; } } // This function prints contents of linked // list starting from the given node function printList() {var ptr = head; while (ptr != null) { document.write(ptr.data + \"-> \"); ptr = ptr.next; } } // Driver code push(19); push(18); push(3); push(4); push(1); document.write(\"<br/>Initial List: \"); printList(); deleteEvenNodes(); document.write(\"<br/>Final List: \"); printList(); // This code contributed by aashish1995</script>", "e": 12205, "s": 9970, "text": null }, { "code": null, "e": 12284, "s": 12205, "text": "Initial List: 1 -> 4 -> 3 -> 18 -> 19 -> \nFinal List: 1 -> 3 -> 19 -> " }, { "code": null, "e": 12308, "s": 12284, "text": "Time Complexity: O(N^2)" }, { "code": null, "e": 12405, "s": 12308, "text": "As the complexity of deleteNode function is O(N) and we need to call it for every even number. " }, { "code": null, "e": 12427, "s": 12405, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 12460, "s": 12427, "text": "As constant extra space is used." }, { "code": null, "e": 12472, "s": 12460, "text": "Approach 2:" }, { "code": null, "e": 12656, "s": 12472, "text": "The idea is to traverse the linked list one by one and get the pointer of nodes having even values. Also keep deleting the nodes having even values using the method used in this post." }, { "code": null, "e": 12773, "s": 12656, "text": "We want the time complexity to be O(1) for deleting a given node in order to get O(N) solution for overall approach." }, { "code": null, "e": 12816, "s": 12773, "text": "The algorithm for the deleteNode function:" }, { "code": null, "e": 12963, "s": 12816, "text": "In the deleteNode function we get the pointer of the node to be deleted directly.Copy the value of next node’s to this node.delete the next node." }, { "code": null, "e": 13046, "s": 12963, "text": "In the deleteNode function we get the pointer of the node to be deleted directly." }, { "code": null, "e": 13090, "s": 13046, "text": "Copy the value of next node’s to this node." }, { "code": null, "e": 13112, "s": 13090, "text": "delete the next node." }, { "code": null, "e": 13329, "s": 13112, "text": "The only thing to keep in mind is that the node to be deleted should not be the last node if we are using the above method to delete the node, but it gives the result in O(1) time so we will use this in our solution." }, { "code": null, "e": 13377, "s": 13329, "text": "The algorithm for the deleteEvenNodes function:" }, { "code": null, "e": 13765, "s": 13377, "text": "We get the head of the linked list as a function parameter.Use dummy pointer variables ptr and prev which are used to store the current and previous node respectively.Traverse the linked list before last element using a while loop and do the following: delete the nodes with odd values and keep updating the prev and ptr pointersThe case of last node is handled explicitly at the end." }, { "code": null, "e": 13825, "s": 13765, "text": "We get the head of the linked list as a function parameter." }, { "code": null, "e": 13934, "s": 13825, "text": "Use dummy pointer variables ptr and prev which are used to store the current and previous node respectively." }, { "code": null, "e": 14020, "s": 13934, "text": "Traverse the linked list before last element using a while loop and do the following:" }, { "code": null, "e": 14101, "s": 14020, "text": " delete the nodes with odd values and keep updating the prev and ptr pointers" }, { "code": null, "e": 14157, "s": 14101, "text": "The case of last node is handled explicitly at the end." }, { "code": null, "e": 14196, "s": 14157, "text": "Full implementation of above approach:" }, { "code": null, "e": 14200, "s": 14196, "text": "C++" }, { "code": null, "e": 14205, "s": 14200, "text": "Java" }, { "code": null, "e": 14213, "s": 14205, "text": "Python3" }, { "code": null, "e": 14216, "s": 14213, "text": "C#" }, { "code": null, "e": 14227, "s": 14216, "text": "Javascript" }, { "code": "// C++ implementation to delete all// even valed nodes from the singly linked list #include <bits/stdc++.h>using namespace std; // Node of the singly linked liststruct Node { int data; struct Node* next;}; // Function to insert a node at// the beginning of the singly// Linked Listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to delete a node in a// singly Linked List.// node --> Pointer to given nodevoid deleteNode(struct Node* node){ // copy the next node's value in current node node->data = node->next->data; // store the pointer to node's next in a temp variable struct Node* temp = node->next; // connect the node with node's next's next node->next = node->next->next; // delete the temp delete (temp);} // Function to delete all the// even valued nodes from the// singly linked listvoid deleteEvenNodes(Node** head_ref){ Node* ptr = *head_ref; Node* prev; // mark the current head with ptr pointer while (ptr != NULL && ptr->next != NULL) { // traverse the linked list before the last element if (ptr->data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else { prev = ptr; ptr = ptr->next; } // move the pointer to the next element and store // the prev node } if (ptr == *head_ref && ptr->data % 2 == 0) *head_ref = NULL; else if (ptr->data % 2 == 0) { prev->next = NULL; delete ptr; }} // This function prints contents// of linked list starting from// the given nodevoid printList(struct Node* node){ while (node != NULL) { printf(\" %d -> \", node->data); node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 2); push(&head, 6); push(&head, 15); push(&head, 16); push(&head, 18); printf(\"Initial List: \"); printList(head); deleteEvenNodes(&head); printf(\"\\nFinal List: \"); printList(head);} // This code was contributed by Abhijeet Kumar", "e": 16464, "s": 14227, "text": null }, { "code": "// Java implementation to delete all// even valued nodes from the singly linked listclass LinkedList{ // head of listNode head; // Linked list Nodeclass Node{ int data; Node next; Node(int d) { data = d; next = null; }} // Function to insert a node at// the beginning of the singly// Linked Listpublic void push(int new_data){ Node new_node = new Node(new_data); new_node.next = head; head = new_node;} // Function to delete a node in a// singly Linked List.void deleteNode(Node node){ // copy the next node's value in current node node.data = node.next.data; // connect the node with node's next's next node.next = node.next.next;} // Function to delete all the nodes// from linked list containing// even numbers.void deleteEvenNodes(){ Node ptr = head; Node prev = null; //mark the current head with ptr pointer while (ptr!=null && ptr.next != null) { // traverse the linked list before the last element if (ptr.data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else{ prev = ptr; ptr = ptr.next; } // move the pointer to the next element and store the previous pointer } if(ptr==head && ptr.data % 2 == 0) head = null; else if(ptr.data % 2 == 0) prev.next = null;} // This function prints contents of linked// list starting from the given nodepublic void printList(){ Node ptr = head; while (ptr != null) { System.out.print(ptr.data + \"-> \"); ptr = ptr.next; }} // Driver codepublic static void main(String[] args){ LinkedList head = new LinkedList(); head.push(2); head.push(6); head.push(15); head.push(16); head.push(18); System.out.print(\"\\nInitial List: \"); head.printList(); head.deleteEvenNodes(); System.out.print(\"\\nFinal List: \"); head.printList();}} // This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 18444, "s": 16464, "text": null }, { "code": "# Python3 implementation to delete all# even valued nodes from the singly linked list # Node classclass Node: # Function to initialize the node object def __init__(self, data): # Assign data self.data = data # Initialize # next as null self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at # the beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Method to print the linked list def printList(self): # Object to iterate # the list ptr = self.head # Loop to iterate list while(ptr != None): print(ptr.data, '-> ', end = '') # Moving the iterating object # to next node ptr = ptr.next print() # Method to delete a node in # a singly linked list. def deleteNode(self,node): # copy the next node's value in current node node.data = node.next.data # connect the node with node's next's next node.next = node.next.next # Method to delete all the # even valued nodes from singly # linked list. def deleteEvenNodes(self): #mark the current head with ptr pointer ptr = self.head prev = self.head # traverse the linked list before the last element while (ptr!=None and ptr.next != None): # delete the node if the value of the node is even if (ptr.data % 2 == 0): self.deleteNode(ptr) # move the pointer to the next element and store the previous pointer else: prev = ptr ptr = ptr.next if(ptr==self.head and ptr.data % 2 == 0): head = None elif(ptr.data % 2 == 0): prev.next = None # Driver codeif __name__=='__main__': head = LinkedList() # Pushing elements at start # of linked list. head.push(18) head.push(16) head.push(15) head.push(6) head.push(2) # Print initial linked list print(\"Initial list: \", end = '') head.printList() # Calling the function to delete # nodes containing even numbers. head.deleteEvenNodes() # Print the final list print(\"Final list: \", end = '') head.printList() # This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 21198, "s": 18444, "text": null }, { "code": "// C# implementation to delete all// even valued nodes from the singly linked listusing System;class List{ // head of list Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Function to insert a node at // the beginning of the singly // Linked List public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. void deleteNode(Node node) { // copy the next node's value in current node node.data = node.next.data; // connect the node with node's next's next node.next = node.next.next; } // Function to delete // all the nodes from // linked list containing // even numbers. void deleteEvenNodes() { Node ptr = head; Node prev = null; //mark the current head with ptr pointer while (ptr!=null && ptr.next != null) { // traverse the linked list before the last element if (ptr.data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else{ prev = ptr; ptr = ptr.next; } // move the pointer to the next element and store the previous pointer } if(ptr==head && ptr.data % 2 == 0) head = null; else if(ptr.data % 2 == 0) prev.next = null; } // This function prints contents of linked // list starting from the given node public void printList() { Node ptr = head; while (ptr != null) { Console.Write(ptr.data + \"-> \"); ptr = ptr.next; } } // Driver code public static void Main(String []args) { List head = new List(); head.push(2); head.push(6); head.push(15); head.push(16); head.push(18); Console.Write(\"\\nInitial List: \"); head.printList(); head.deleteEvenNodes(); Console.Write(\"\\nFinal List: \"); head.printList(); }} // This code contributed by Abhijeet Kumar(abhijeet19403)", "e": 23258, "s": 21198, "text": null }, { "code": "<script>// javascript implementation to delete all// even nodes from the singly linked list // head of list var head; // Linked list Node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to insert a node at // the beginning of the singly // Linked List function push(new_data) {var new_node = new Node(new_data); new_node.next = head; head = new_node; } // Function to delete a node in a // singly Linked List. void deleteNode(Node node) { // copy the next node's value in current node node.data = node.next.data; // connect the node with node's next's next node.next = node.next.next; } // Function to delete all the nodes // from linked list containing // even numbers. function deleteEvenNodes() { var ptr = head,prev = null; //mark the current head with ptr pointer while (ptr!=null && ptr.next != null) { // traverse the linked list before the last element if (ptr.data % 2 == 0) deleteNode(ptr); // delete the node if the value of the node is even else{ prev = ptr; ptr = ptr.next; } // move the pointer to the next element and store the previous pointer } if(ptr==head && ptr.data % 2 == 0) head = null; else if(ptr.data % 2 == 0) prev.next = null; } // This function prints contents of linked // list starting from the given node function printList() { var ptr = head; while (ptr != null) { document.write(ptr.data + \"-> \"); ptr = ptr.next; } } // Driver code push(2); push(6); push(15); push(16); push(18); document.write(\"<br/>Initial List: \"); printList(); deleteEvenNodes(); document.write(\"<br/>Final List: \"); printList(); // This code contributed by Abhijeet Kumar(abhijeet19403)</script>", "e": 25311, "s": 23258, "text": null }, { "code": null, "e": 25379, "s": 25311, "text": "Initial List: 18 -> 16 -> 15 -> 6 -> 2 -> \nFinal List: 15 -> " }, { "code": null, "e": 25401, "s": 25379, "text": "Time Complexity: O(N)" }, { "code": null, "e": 25485, "s": 25401, "text": "As we are visiting every node and deleting odd valued node which is O(1) operation." }, { "code": null, "e": 25507, "s": 25485, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 25540, "s": 25507, "text": "As constant extra space is used." }, { "code": null, "e": 25714, "s": 25540, "text": "This approach was contributed by Abhijeet Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25727, "s": 25714, "text": "amit_mangal_" }, { "code": null, "e": 25741, "s": 25727, "text": "GauravRajput1" }, { "code": null, "e": 25753, "s": 25741, "text": "aashish1995" }, { "code": null, "e": 25771, "s": 25753, "text": "shubhamrajput6156" }, { "code": null, "e": 25785, "s": 25771, "text": "abhijeet19403" }, { "code": null, "e": 25801, "s": 25785, "text": "Data Structures" }, { "code": null, "e": 25813, "s": 25801, "text": "Linked List" }, { "code": null, "e": 25832, "s": 25813, "text": "School Programming" }, { "code": null, "e": 25848, "s": 25832, "text": "Write From Home" }, { "code": null, "e": 25864, "s": 25848, "text": "Data Structures" }, { "code": null, "e": 25876, "s": 25864, "text": "Linked List" }, { "code": null, "e": 25974, "s": 25876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26013, "s": 25974, "text": "Amazon Interview Experience for SDE-II" }, { "code": null, "e": 26059, "s": 26013, "text": "Binary Search Tree | Set 3 (Iterative Delete)" }, { "code": null, "e": 26102, "s": 26059, "text": "Data Structures | Linked List | Question 4" }, { "code": null, "e": 26162, "s": 26102, "text": "Data Structures | Balanced Binary Search Trees | Question 5" }, { "code": null, "e": 26196, "s": 26162, "text": "Improving Linear Search Technique" }, { "code": null, "e": 26231, "s": 26196, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 26270, "s": 26231, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 26292, "s": 26270, "text": "Reverse a linked list" }, { "code": null, "e": 26340, "s": 26292, "text": "Stack Data Structure (Introduction and Program)" } ]
Find elements of array using XOR of consecutive elements
24 Jun, 2022 Given an array arr[] in which XOR of every 2 consecutive elements of the original array is given i.e if the total number of elements in the original array is then the size of this XOR array would be n-1. The first element in the original array is also given. The task is to find out the rest of n-1 elements of the original array. Let a, b, c, d, e, f are the original elements, and the xor of every 2 consecutive elements is given, i.e a^b = k1, b ^ c = k2, c ^ d = k3, d ^ e = k4, e ^ f = k5 (where k1, k2, k3, k4, k5 are the elements that are given us along with the first element a), and we have to find the value of b, c, d, e, f. Examples: Input : arr[] = {13, 2, 6, 1}, a = 5 Output : 5 8 10 12 13 5^8=13, 8^10=2, 10^12=6, 12^13=1 Input : arr[] = {12, 5, 26, 7}, a = 6 Output : 6 10 15 21 18 Approach: We can find all the elements one by one with the help of (first elements), and to find the next element i.e we have to xor a by arr[0], similarly for xor arr[1] with b and so on. This works by following the properties of XOR as stated below: XOR of a number to itself is zero. XOR of a number with zero given the number itself. So, as arr[0] contains a^b. Therefore, a ^ arr[0] = a ^ a ^ b = 0 ^ b = b Similarly, arr[i] contains XOR of ai and ai+1. Therefore, ai ^ arr[i] = ai ^ ai ^ ai+1 = 0 ^ ai+1 = ai+1 Below is the implementation of the above approach C++ Java Python3 C# PHP Javascript // C++ program to find the array elements// using XOR of consecutive elements #include <bits/stdc++.h>using namespace std; // Function to find the array elements// using XOR of consecutive elementsvoid getElements(int a, int arr[], int n){ // array to store the original // elements int elements[n + 1]; // first element a i.e elements[0]=a elements[0] = a; for (int i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for (int i = 0; i < n + 1; i++) cout << elements[i] << " ";} // Driver Codeint main(){ int arr[] = { 13, 2, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int a = 5; getElements(a, arr, n); return 0;} // Java program to find the array elements// using XOR of consecutive elements import java.io.*; class GFG { // Function to find the array elements// using XOR of consecutive elementsstatic void getElements(int a, int arr[], int n){ // array to store the original // elements int elements[] = new int[n + 1]; // first element a i.e elements[0]=a elements[0] = a; for (int i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for (int i = 0; i < n + 1; i++) System.out.print( elements[i] + " ");} // Driver Code public static void main (String[] args) { int arr[] = { 13, 2, 6, 1 }; int n = arr.length; int a = 5; getElements(a, arr, n); }}// This code is contributed by anuj_67.. # Python3 program to find the array# elements using xor of consecutive elements # Function to find the array elements# using XOR of consecutive elements def getElements(a, arr, n): # array to store the original elements elements = [1 for i in range(n + 1)] # first elements a i.e elements[0]=a elements[0] = a for i in range(n): # To get the next elements we have to # calculate xor of previous elements # with given xor of 2 consecutive elements. # e.g. if a^b=k1 so to get b xor a both side. # b = k1^a elements[i + 1] = arr[i] ^ elements[i] # Printing the original array elements for i in range(n + 1): print(elements[i], end = " ") # Driver codearr = [13, 2, 6, 1]n = len(arr)a = 5getElements(a, arr, n) # This code is contributed by Mohit Kumar // C# program to find the array elements// using XOR of consecutive elements using System; class GFG { // Function to find the array elements // using XOR of consecutive elements static void getElements(int a, int []arr, int n) { // array to store the original // elements int []elements = new int[n + 1]; // first element a i.e elements[0]=a elements[0] = a; for (int i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for (int i = 0; i < n + 1; i++) Console.Write( elements[i] + " "); } // Driver Code public static void Main () { int []arr = { 13, 2, 6, 1 }; int n = arr.Length; int a = 5; getElements(a, arr, n); } // This code is contributed by Ryuga} <?php// PHP program to find the array elements// using XOR of consecutive elements // Function to find the array elements// using XOR of consecutive elementsfunction getElements($a, &$arr, &$n){ // array to store the original // elements // first element a i.e elements[0]=a $elements[0] = $a; for ($i = 0; $i < $n; $i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ $elements[$i + 1] = $arr[$i] ^ $elements[$i]; } // Printing the original array elements for ($i = 0; $i < $n + 1; $i++) { echo($elements[$i] . " "); }} // Driver Code$arr = array(13, 2, 6, 1); $n = sizeof($arr); $a = 5; getElements($a, $arr, $n); // This code is contributed by Shivi_Aggarwal?> <script> // Javascript program to find the array elements// using XOR of consecutive elements // Function to find the array elements// using XOR of consecutive elementsfunction getElements(a, arr, n){ // Array to store the original // elements let elements = new Array(n + 1); for(let i = 0; i < n + 1; i++) { elements[i] = 0; } // first element a i.e elements[0]=a elements[0] = a; for(let i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for(let i = 0; i < n + 1; i++) document.write( elements[i] + " ");} // Driver Codelet arr = [ 13, 2, 6, 1 ];let n = arr.length;let a = 5; getElements(a, arr, n); // This code is contributed by unknown2108 </script> 5 8 10 12 13 Time Complexity: O(N), since there runs a loop for N times.Auxiliary Space: O(N), since N extra space has been taken. vt_m mohit kumar 29 ankthon Shivi_Aggarwal unknown2108 simranarora5sos pankajsharmagfg souravkumar29 Bitwise-XOR Algorithms Arrays Mathematical Arrays Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2022" }, { "code": null, "e": 384, "s": 53, "text": "Given an array arr[] in which XOR of every 2 consecutive elements of the original array is given i.e if the total number of elements in the original array is then the size of this XOR array would be n-1. The first element in the original array is also given. The task is to find out the rest of n-1 elements of the original array." }, { "code": null, "e": 689, "s": 384, "text": "Let a, b, c, d, e, f are the original elements, and the xor of every 2 consecutive elements is given, i.e a^b = k1, b ^ c = k2, c ^ d = k3, d ^ e = k4, e ^ f = k5 (where k1, k2, k3, k4, k5 are the elements that are given us along with the first element a), and we have to find the value of b, c, d, e, f." }, { "code": null, "e": 701, "s": 689, "text": "Examples: " }, { "code": null, "e": 856, "s": 701, "text": "Input : arr[] = {13, 2, 6, 1}, a = 5\nOutput : 5 8 10 12 13\n5^8=13, 8^10=2, 10^12=6, 12^13=1\n\nInput : arr[] = {12, 5, 26, 7}, a = 6\nOutput : 6 10 15 21 18 " }, { "code": null, "e": 1045, "s": 856, "text": "Approach: We can find all the elements one by one with the help of (first elements), and to find the next element i.e we have to xor a by arr[0], similarly for xor arr[1] with b and so on." }, { "code": null, "e": 1110, "s": 1045, "text": "This works by following the properties of XOR as stated below: " }, { "code": null, "e": 1145, "s": 1110, "text": "XOR of a number to itself is zero." }, { "code": null, "e": 1196, "s": 1145, "text": "XOR of a number with zero given the number itself." }, { "code": null, "e": 1237, "s": 1196, "text": "So, as arr[0] contains a^b. Therefore, " }, { "code": null, "e": 1294, "s": 1237, "text": "a ^ arr[0] = a ^ a ^ b\n = 0 ^ b\n = b" }, { "code": null, "e": 1353, "s": 1294, "text": "Similarly, arr[i] contains XOR of ai and ai+1. Therefore, " }, { "code": null, "e": 1424, "s": 1353, "text": "ai ^ arr[i] = ai ^ ai ^ ai+1\n = 0 ^ ai+1\n = ai+1" }, { "code": null, "e": 1475, "s": 1424, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 1479, "s": 1475, "text": "C++" }, { "code": null, "e": 1484, "s": 1479, "text": "Java" }, { "code": null, "e": 1492, "s": 1484, "text": "Python3" }, { "code": null, "e": 1495, "s": 1492, "text": "C#" }, { "code": null, "e": 1499, "s": 1495, "text": "PHP" }, { "code": null, "e": 1510, "s": 1499, "text": "Javascript" }, { "code": "// C++ program to find the array elements// using XOR of consecutive elements #include <bits/stdc++.h>using namespace std; // Function to find the array elements// using XOR of consecutive elementsvoid getElements(int a, int arr[], int n){ // array to store the original // elements int elements[n + 1]; // first element a i.e elements[0]=a elements[0] = a; for (int i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for (int i = 0; i < n + 1; i++) cout << elements[i] << \" \";} // Driver Codeint main(){ int arr[] = { 13, 2, 6, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int a = 5; getElements(a, arr, n); return 0;}", "e": 2475, "s": 1510, "text": null }, { "code": "// Java program to find the array elements// using XOR of consecutive elements import java.io.*; class GFG { // Function to find the array elements// using XOR of consecutive elementsstatic void getElements(int a, int arr[], int n){ // array to store the original // elements int elements[] = new int[n + 1]; // first element a i.e elements[0]=a elements[0] = a; for (int i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for (int i = 0; i < n + 1; i++) System.out.print( elements[i] + \" \");} // Driver Code public static void main (String[] args) { int arr[] = { 13, 2, 6, 1 }; int n = arr.length; int a = 5; getElements(a, arr, n); }}// This code is contributed by anuj_67..", "e": 3515, "s": 2475, "text": null }, { "code": "# Python3 program to find the array# elements using xor of consecutive elements # Function to find the array elements# using XOR of consecutive elements def getElements(a, arr, n): # array to store the original elements elements = [1 for i in range(n + 1)] # first elements a i.e elements[0]=a elements[0] = a for i in range(n): # To get the next elements we have to # calculate xor of previous elements # with given xor of 2 consecutive elements. # e.g. if a^b=k1 so to get b xor a both side. # b = k1^a elements[i + 1] = arr[i] ^ elements[i] # Printing the original array elements for i in range(n + 1): print(elements[i], end = \" \") # Driver codearr = [13, 2, 6, 1]n = len(arr)a = 5getElements(a, arr, n) # This code is contributed by Mohit Kumar", "e": 4372, "s": 3515, "text": null }, { "code": "// C# program to find the array elements// using XOR of consecutive elements using System; class GFG { // Function to find the array elements // using XOR of consecutive elements static void getElements(int a, int []arr, int n) { // array to store the original // elements int []elements = new int[n + 1]; // first element a i.e elements[0]=a elements[0] = a; for (int i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for (int i = 0; i < n + 1; i++) Console.Write( elements[i] + \" \"); } // Driver Code public static void Main () { int []arr = { 13, 2, 6, 1 }; int n = arr.Length; int a = 5; getElements(a, arr, n); } // This code is contributed by Ryuga}", "e": 5519, "s": 4372, "text": null }, { "code": "<?php// PHP program to find the array elements// using XOR of consecutive elements // Function to find the array elements// using XOR of consecutive elementsfunction getElements($a, &$arr, &$n){ // array to store the original // elements // first element a i.e elements[0]=a $elements[0] = $a; for ($i = 0; $i < $n; $i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ $elements[$i + 1] = $arr[$i] ^ $elements[$i]; } // Printing the original array elements for ($i = 0; $i < $n + 1; $i++) { echo($elements[$i] . \" \"); }} // Driver Code$arr = array(13, 2, 6, 1); $n = sizeof($arr); $a = 5; getElements($a, $arr, $n); // This code is contributed by Shivi_Aggarwal?>", "e": 6424, "s": 5519, "text": null }, { "code": "<script> // Javascript program to find the array elements// using XOR of consecutive elements // Function to find the array elements// using XOR of consecutive elementsfunction getElements(a, arr, n){ // Array to store the original // elements let elements = new Array(n + 1); for(let i = 0; i < n + 1; i++) { elements[i] = 0; } // first element a i.e elements[0]=a elements[0] = a; for(let i = 0; i < n; i++) { /* To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements. e.g. if a^b=k1 so to get b xor a both side. b = k1^a */ elements[i + 1] = arr[i] ^ elements[i]; } // Printing the original array elements for(let i = 0; i < n + 1; i++) document.write( elements[i] + \" \");} // Driver Codelet arr = [ 13, 2, 6, 1 ];let n = arr.length;let a = 5; getElements(a, arr, n); // This code is contributed by unknown2108 </script>", "e": 7450, "s": 6424, "text": null }, { "code": null, "e": 7463, "s": 7450, "text": "5 8 10 12 13" }, { "code": null, "e": 7583, "s": 7465, "text": "Time Complexity: O(N), since there runs a loop for N times.Auxiliary Space: O(N), since N extra space has been taken." }, { "code": null, "e": 7588, "s": 7583, "text": "vt_m" }, { "code": null, "e": 7603, "s": 7588, "text": "mohit kumar 29" }, { "code": null, "e": 7611, "s": 7603, "text": "ankthon" }, { "code": null, "e": 7626, "s": 7611, "text": "Shivi_Aggarwal" }, { "code": null, "e": 7638, "s": 7626, "text": "unknown2108" }, { "code": null, "e": 7654, "s": 7638, "text": "simranarora5sos" }, { "code": null, "e": 7670, "s": 7654, "text": "pankajsharmagfg" }, { "code": null, "e": 7684, "s": 7670, "text": "souravkumar29" }, { "code": null, "e": 7696, "s": 7684, "text": "Bitwise-XOR" }, { "code": null, "e": 7707, "s": 7696, "text": "Algorithms" }, { "code": null, "e": 7714, "s": 7707, "text": "Arrays" }, { "code": null, "e": 7727, "s": 7714, "text": "Mathematical" }, { "code": null, "e": 7734, "s": 7727, "text": "Arrays" }, { "code": null, "e": 7747, "s": 7734, "text": "Mathematical" }, { "code": null, "e": 7758, "s": 7747, "text": "Algorithms" } ]
Find Last Digit of a^b for Large Numbers
13 Apr, 2021 You are given two integer numbers, the base a (number of digits d, such that 1 <= d <= 1000) and the index b (0 <= b <= 922*10^15). You have to find the last digit of a^b.Examples: Input : 3 10 Output : 9 Input : 6 2 Output : 6 Input : 150 53 Output : 0 After taking few examples, we can notice below pattern. Number | Last digits that repeat in cycle 1 | 1 2 | 4, 8, 6, 2 3 | 9, 7, 1, 3 4 | 6, 4 5 | 5 6 | 6 7 | 9, 3, 1, 7 8 | 4, 2, 6, 8 9 | 1, 9 In the given table, we can see that maximum length for cycle repetition is 4. Example: 2*2 = 4*2 = 8*2 = 16*2 = 32 last digit in 32 is 2 that means after multiplying 4 times digit repeat itself. So the algorithm is very simple .Source : Brilliants.orgAlgorithm : Since number are very large we store them as a string.Take last digit in base a.Now calculate b%4. Here b is very large. If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram.If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram.Now calculate ldigit = pow( last_digit_in_base, exp ).Last digit of a^b will be ldigit%10. Since number are very large we store them as a string. Take last digit in base a. Now calculate b%4. Here b is very large. If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram.If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram.Now calculate ldigit = pow( last_digit_in_base, exp ).Last digit of a^b will be ldigit%10. If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram. If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram. Now calculate ldigit = pow( last_digit_in_base, exp ). Last digit of a^b will be ldigit%10. Below is the implementation of above algorithm. C++ Java C# PHP Javascript // C++ code to find last digit of a^b#include <bits/stdc++.h>using namespace std; // Function to find b % aint Modulo(int a, char b[]){ // Initialize result int mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (int i = 0; i < strlen(b); i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo} // function to find last digit of a^bint LastDigit(char a[], char b[]){ int len_a = strlen(a), len_b = strlen(b); // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 that means last // digit will be pow(a, 4) % 10. // if exponent is not divisible by 4 that means last // digit will be pow(a, b%4) % 10 int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and compute its exponent int res = pow(a[len_a - 1] - '0', exp); // Return last digit of result return res % 10;} // Driver program to run test caseint main(){ char a[] = "117", b[] = "3"; cout << LastDigit(a, b); return 0;} // Java code to find last digit of a^bimport java.io.*;import java.math.*; class GFG { // Function to find b % a static int Modulo(int a, char b[]) { // Initialize result int mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (int i = 0; i < b.length; i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo } // Function to find last digit of a^b static int LastDigit(char a[], char b[]) { int len_a = a.length, len_b = b.length; // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 that means last // digit will be pow(a, 4) % 10. // if exponent is not divisible by 4 that means last // digit will be pow(a, b%4) % 10 int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and compute its exponent int res = (int)(Math.pow(a[len_a - 1] - '0', exp)); // Return last digit of result return res % 10; } // Driver program to run test case public static void main(String args[]) throws IOException { char a[] = "117".toCharArray(), b[] = { '3' }; System.out.println(LastDigit(a, b)); }} // This code is contributed by Nikita Tiwari. Python3 # Python 3 code to find last digit of a ^ b import math # Function to find b % a def Modulo(a, b) : # Initialize result mod = 0 # calculating mod of b with a to make # b like 0 <= b < a for i in range(0, len(b)) : mod = (mod * 10 + (int)(b[i])) % a return mod # return modulo # function to find last digit of a ^ b def LastDigit(a, b) : len_a = len(a) len_b = len(b) # if a and b both are 0 if (len_a == 1 and len_b == 1 and b[0] == '0' and a[0] == '0') : return 1 # if exponent is 0 if (len_b == 1 and b[0]=='0') : return 1 # if base is 0 if (len_a == 1 and a[0] == '0') : return 0 # if exponent is divisible by 4 that means last # digit will be pow(a, 4) % 10. # if exponent is not divisible by 4 that means last # digit will be pow(a, b % 4) % 10 if((Modulo(4, b) == 0)) : exp = 4 else : exp = Modulo(4, b) # Find last digit in 'a' and compute its exponent res = math.pow((int)(a[len_a - 1]), exp) # Return last digit of result return res % 10 # Driver program to run test case a = ['1', '1', '7'] b = ['3'] print(LastDigit(a, b)) # This code is contributed to Nikita Tiwari. // C# code to find last digit of a^b.using System; class GFG { // Function to find b % a static int Modulo(int a, char[] b) { // Initialize result int mod = 0; // calculating mod of b with a // to make b like 0 <= b < a for (int i = 0; i < b.Length; i++) mod = (mod * 10 + b[i] - '0') % a; // return modulo return mod; } // Function to find last digit of a^b static int LastDigit(char[] a, char[] b) { int len_a = a.Length, len_b = b.Length; // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 // that means last digit will be // pow(a, 4) % 10. if exponent is //not divisible by 4 that means last // digit will be pow(a, b%4) % 10 int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and // compute its exponent int res = (int)(Math.Pow(a[len_a - 1] - '0', exp)); // Return last digit of result return res % 10; } // Driver program to run test case public static void Main() { char[] a = "117".ToCharArray(), b = { '3' }; Console.Write(LastDigit(a, b)); }} // This code is contributed by nitin mittal. <?php// php code to find last digit of a^b // Function to find b % afunction Modulo($a, $b){ // Initialize result $mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for ($i = 0; $i < strlen($b); $i++) $mod = ($mod * 10 + $b[$i] - '0') % $a; return $mod; // return modulo} // function to find last digit of a^bfunction LastDigit($a, $b){ $len_a = strlen($a); $len_b = strlen($b); // if a and b both are 0 if ($len_a == 1 && $len_b == 1 && $b[0] == '0' && $a[0] == '0') return 1; // if exponent is 0 if ($len_b == 1 && $b[0] == '0') return 1; // if base is 0 if ($len_a == 1 && $a[0] == '0') return 0; // if exponent is divisible by 4 that // means last digit will be pow(a, 4) // % 10. if exponent is not divisible // by 4 that means last digit will be // pow(a, b%4) % 10 $exp = (Modulo(4, $b) == 0) ? 4 : Modulo(4, $b); // Find last digit in 'a' and compute // its exponent $res = pow($a[$len_a - 1] - '0', $exp); // Return last digit of result return $res % 10;} // Driver program to run test case$a = "117";$b = "3";echo LastDigit($a, $b); // This code is contributed by nitin mittal.?> <script> // Javascript code to find last digit of a^b // Function to find b % afunction Modulo(a, b){ // Initialize result let mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (let i = 0; i < b.length; i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo} // function to find last digit of a^bfunction LastDigit(a, b){ let len_a = a.length; let len_b = b.length; // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 that // means last digit will be pow(a, 4) // % 10. if exponent is not divisible // by 4 that means last digit will be // pow(a, b%4) % 10 exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and compute // its exponent res = Math.pow(a[len_a - 1] - '0', exp); // Return last digit of result return res % 10;} // Driver program to run test caselet a = "117";let b = "3";document.write(LastDigit(a, b)); // This code is contributed by _saurabh_jaiswal </script> Output : 3 This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team geeksforgeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal _saurabh_jaiswal large-numbers Modular Arithmetic Samsung Mathematical Samsung Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Apr, 2021" }, { "code": null, "e": 237, "s": 54, "text": "You are given two integer numbers, the base a (number of digits d, such that 1 <= d <= 1000) and the index b (0 <= b <= 922*10^15). You have to find the last digit of a^b.Examples: " }, { "code": null, "e": 315, "s": 237, "text": "Input : 3 10\nOutput : 9\n\nInput : 6 2\nOutput : 6\n\nInput : 150 53\nOutput : 0" }, { "code": null, "e": 374, "s": 317, "text": "After taking few examples, we can notice below pattern. " }, { "code": null, "e": 580, "s": 374, "text": "Number | Last digits that repeat in cycle\n 1 | 1\n 2 | 4, 8, 6, 2\n 3 | 9, 7, 1, 3\n 4 | 6, 4\n 5 | 5\n 6 | 6\n 7 | 9, 3, 1, 7\n 8 | 4, 2, 6, 8\n 9 | 1, 9" }, { "code": null, "e": 844, "s": 580, "text": "In the given table, we can see that maximum length for cycle repetition is 4. Example: 2*2 = 4*2 = 8*2 = 16*2 = 32 last digit in 32 is 2 that means after multiplying 4 times digit repeat itself. So the algorithm is very simple .Source : Brilliants.orgAlgorithm : " }, { "code": null, "e": 1451, "s": 844, "text": "Since number are very large we store them as a string.Take last digit in base a.Now calculate b%4. Here b is very large. If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram.If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram.Now calculate ldigit = pow( last_digit_in_base, exp ).Last digit of a^b will be ldigit%10." }, { "code": null, "e": 1506, "s": 1451, "text": "Since number are very large we store them as a string." }, { "code": null, "e": 1533, "s": 1506, "text": "Take last digit in base a." }, { "code": null, "e": 2060, "s": 1533, "text": "Now calculate b%4. Here b is very large. If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram.If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram.Now calculate ldigit = pow( last_digit_in_base, exp ).Last digit of a^b will be ldigit%10." }, { "code": null, "e": 2253, "s": 2060, "text": "If b%4==0 that means b is completely divisible by 4, so our exponent now will be exp = 4 because by multiplying number 4 times, we get the last digit according to cycle table in above diagram." }, { "code": null, "e": 2457, "s": 2253, "text": "If b%4!=0 that means b is not completely divisible by 4, so our exponent now will be exp=b%4 because by multiplying number exponent times, we get the last digit according to cycle table in above diagram." }, { "code": null, "e": 2512, "s": 2457, "text": "Now calculate ldigit = pow( last_digit_in_base, exp )." }, { "code": null, "e": 2549, "s": 2512, "text": "Last digit of a^b will be ldigit%10." }, { "code": null, "e": 2599, "s": 2549, "text": "Below is the implementation of above algorithm. " }, { "code": null, "e": 2603, "s": 2599, "text": "C++" }, { "code": null, "e": 2608, "s": 2603, "text": "Java" }, { "code": null, "e": 2611, "s": 2608, "text": "C#" }, { "code": null, "e": 2615, "s": 2611, "text": "PHP" }, { "code": null, "e": 2626, "s": 2615, "text": "Javascript" }, { "code": "// C++ code to find last digit of a^b#include <bits/stdc++.h>using namespace std; // Function to find b % aint Modulo(int a, char b[]){ // Initialize result int mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (int i = 0; i < strlen(b); i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo} // function to find last digit of a^bint LastDigit(char a[], char b[]){ int len_a = strlen(a), len_b = strlen(b); // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 that means last // digit will be pow(a, 4) % 10. // if exponent is not divisible by 4 that means last // digit will be pow(a, b%4) % 10 int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and compute its exponent int res = pow(a[len_a - 1] - '0', exp); // Return last digit of result return res % 10;} // Driver program to run test caseint main(){ char a[] = \"117\", b[] = \"3\"; cout << LastDigit(a, b); return 0;}", "e": 3865, "s": 2626, "text": null }, { "code": "// Java code to find last digit of a^bimport java.io.*;import java.math.*; class GFG { // Function to find b % a static int Modulo(int a, char b[]) { // Initialize result int mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (int i = 0; i < b.length; i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo } // Function to find last digit of a^b static int LastDigit(char a[], char b[]) { int len_a = a.length, len_b = b.length; // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 that means last // digit will be pow(a, 4) % 10. // if exponent is not divisible by 4 that means last // digit will be pow(a, b%4) % 10 int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and compute its exponent int res = (int)(Math.pow(a[len_a - 1] - '0', exp)); // Return last digit of result return res % 10; } // Driver program to run test case public static void main(String args[]) throws IOException { char a[] = \"117\".toCharArray(), b[] = { '3' }; System.out.println(LastDigit(a, b)); }} // This code is contributed by Nikita Tiwari.", "e": 5403, "s": 3865, "text": null }, { "code": null, "e": 5412, "s": 5403, "text": "Python3 " }, { "code": null, "e": 6657, "s": 5412, "text": "\n# Python 3 code to find last digit of a ^ b\n\nimport math\n\n# Function to find b % a\ndef Modulo(a, b) :\n # Initialize result\n mod = 0\n\n # calculating mod of b with a to make\n # b like 0 <= b < a\n for i in range(0, len(b)) :\n mod = (mod * 10 + (int)(b[i])) % a\n\n return mod # return modulo\n\n\n# function to find last digit of a ^ b\ndef LastDigit(a, b) :\n len_a = len(a)\n len_b = len(b)\n\n # if a and b both are 0\n if (len_a == 1 and len_b == 1 and b[0] == '0' and a[0] == '0') :\n return 1\n\n # if exponent is 0\n if (len_b == 1 and b[0]=='0') :\n return 1\n\n # if base is 0\n if (len_a == 1 and a[0] == '0') :\n return 0\n\n # if exponent is divisible by 4 that means last\n # digit will be pow(a, 4) % 10.\n # if exponent is not divisible by 4 that means last\n # digit will be pow(a, b % 4) % 10\n if((Modulo(4, b) == 0)) :\n exp = 4\n else : \n exp = Modulo(4, b)\n\n # Find last digit in 'a' and compute its exponent\n res = math.pow((int)(a[len_a - 1]), exp)\n\n # Return last digit of result\n return res % 10\n \n\n# Driver program to run test case\na = ['1', '1', '7']\nb = ['3']\nprint(LastDigit(a, b))\n\n# This code is contributed to Nikita Tiwari.\n" }, { "code": "// C# code to find last digit of a^b.using System; class GFG { // Function to find b % a static int Modulo(int a, char[] b) { // Initialize result int mod = 0; // calculating mod of b with a // to make b like 0 <= b < a for (int i = 0; i < b.Length; i++) mod = (mod * 10 + b[i] - '0') % a; // return modulo return mod; } // Function to find last digit of a^b static int LastDigit(char[] a, char[] b) { int len_a = a.Length, len_b = b.Length; // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 // that means last digit will be // pow(a, 4) % 10. if exponent is //not divisible by 4 that means last // digit will be pow(a, b%4) % 10 int exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and // compute its exponent int res = (int)(Math.Pow(a[len_a - 1] - '0', exp)); // Return last digit of result return res % 10; } // Driver program to run test case public static void Main() { char[] a = \"117\".ToCharArray(), b = { '3' }; Console.Write(LastDigit(a, b)); }} // This code is contributed by nitin mittal.", "e": 8267, "s": 6657, "text": null }, { "code": "<?php// php code to find last digit of a^b // Function to find b % afunction Modulo($a, $b){ // Initialize result $mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for ($i = 0; $i < strlen($b); $i++) $mod = ($mod * 10 + $b[$i] - '0') % $a; return $mod; // return modulo} // function to find last digit of a^bfunction LastDigit($a, $b){ $len_a = strlen($a); $len_b = strlen($b); // if a and b both are 0 if ($len_a == 1 && $len_b == 1 && $b[0] == '0' && $a[0] == '0') return 1; // if exponent is 0 if ($len_b == 1 && $b[0] == '0') return 1; // if base is 0 if ($len_a == 1 && $a[0] == '0') return 0; // if exponent is divisible by 4 that // means last digit will be pow(a, 4) // % 10. if exponent is not divisible // by 4 that means last digit will be // pow(a, b%4) % 10 $exp = (Modulo(4, $b) == 0) ? 4 : Modulo(4, $b); // Find last digit in 'a' and compute // its exponent $res = pow($a[$len_a - 1] - '0', $exp); // Return last digit of result return $res % 10;} // Driver program to run test case$a = \"117\";$b = \"3\";echo LastDigit($a, $b); // This code is contributed by nitin mittal.?>", "e": 9533, "s": 8267, "text": null }, { "code": "<script> // Javascript code to find last digit of a^b // Function to find b % afunction Modulo(a, b){ // Initialize result let mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (let i = 0; i < b.length; i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo} // function to find last digit of a^bfunction LastDigit(a, b){ let len_a = a.length; let len_b = b.length; // if a and b both are 0 if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0') return 1; // if exponent is 0 if (len_b == 1 && b[0] == '0') return 1; // if base is 0 if (len_a == 1 && a[0] == '0') return 0; // if exponent is divisible by 4 that // means last digit will be pow(a, 4) // % 10. if exponent is not divisible // by 4 that means last digit will be // pow(a, b%4) % 10 exp = (Modulo(4, b) == 0) ? 4 : Modulo(4, b); // Find last digit in 'a' and compute // its exponent res = Math.pow(a[len_a - 1] - '0', exp); // Return last digit of result return res % 10;} // Driver program to run test caselet a = \"117\";let b = \"3\";document.write(LastDigit(a, b)); // This code is contributed by _saurabh_jaiswal </script>", "e": 10820, "s": 9533, "text": null }, { "code": null, "e": 10830, "s": 10820, "text": "Output : " }, { "code": null, "e": 10832, "s": 10830, "text": "3" }, { "code": null, "e": 11064, "s": 10832, "text": "This article is contributed by Shashank Mishra ( Gullu ). This article is reviewed by team geeksforgeeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11077, "s": 11064, "text": "nitin mittal" }, { "code": null, "e": 11094, "s": 11077, "text": "_saurabh_jaiswal" }, { "code": null, "e": 11108, "s": 11094, "text": "large-numbers" }, { "code": null, "e": 11127, "s": 11108, "text": "Modular Arithmetic" }, { "code": null, "e": 11135, "s": 11127, "text": "Samsung" }, { "code": null, "e": 11148, "s": 11135, "text": "Mathematical" }, { "code": null, "e": 11156, "s": 11148, "text": "Samsung" }, { "code": null, "e": 11169, "s": 11156, "text": "Mathematical" }, { "code": null, "e": 11188, "s": 11169, "text": "Modular Arithmetic" }, { "code": null, "e": 11286, "s": 11188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11310, "s": 11286, "text": "Merge two sorted arrays" }, { "code": null, "e": 11331, "s": 11310, "text": "Operators in C / C++" }, { "code": null, "e": 11345, "s": 11331, "text": "Prime Numbers" }, { "code": null, "e": 11387, "s": 11345, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 11440, "s": 11387, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 11477, "s": 11440, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 11520, "s": 11477, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 11552, "s": 11520, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 11593, "s": 11552, "text": "Program for Decimal to Binary Conversion" } ]
list empty() function in C++ STL
20 Jun, 2018 The list::empty() is a built-in function in C++ STL is used to check whether a particular list container is empty or not. This function does not modifies the list, it simply checks whether a list is empty or not, i.e. the size of list is zero or not. Syntax: list_name.empty() Parameters: This function does not accept any parameter, it simply checks whether a list container is empty or not. Return Value: The return type of this function is boolean. It returns True is the size of the list container is zero otherwise it returns False. Below program illustrates the list::empty() function. // CPP program to illustrate the// list::empty() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // check if list is empty if (demoList.empty()) cout << "Empty List\n"; else cout << "Not Empty\n"; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // check again if list is empty if (demoList.empty()) cout << "Empty List\n"; else cout << "Not Empty\n"; return 0;} Empty List Not Empty Note: This function works in constant time complexity. CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Substring in C++ C++ Classes and Objects Sorting a vector in C++ Object Oriented Programming in C++ Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2018" }, { "code": null, "e": 279, "s": 28, "text": "The list::empty() is a built-in function in C++ STL is used to check whether a particular list container is empty or not. This function does not modifies the list, it simply checks whether a list is empty or not, i.e. the size of list is zero or not." }, { "code": null, "e": 287, "s": 279, "text": "Syntax:" }, { "code": null, "e": 307, "s": 287, "text": "list_name.empty() \n" }, { "code": null, "e": 423, "s": 307, "text": "Parameters: This function does not accept any parameter, it simply checks whether a list container is empty or not." }, { "code": null, "e": 568, "s": 423, "text": "Return Value: The return type of this function is boolean. It returns True is the size of the list container is zero otherwise it returns False." }, { "code": null, "e": 622, "s": 568, "text": "Below program illustrates the list::empty() function." }, { "code": "// CPP program to illustrate the// list::empty() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // check if list is empty if (demoList.empty()) cout << \"Empty List\\n\"; else cout << \"Not Empty\\n\"; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // check again if list is empty if (demoList.empty()) cout << \"Empty List\\n\"; else cout << \"Not Empty\\n\"; return 0;}", "e": 1195, "s": 622, "text": null }, { "code": null, "e": 1217, "s": 1195, "text": "Empty List\nNot Empty\n" }, { "code": null, "e": 1272, "s": 1217, "text": "Note: This function works in constant time complexity." }, { "code": null, "e": 1286, "s": 1272, "text": "CPP-Functions" }, { "code": null, "e": 1295, "s": 1286, "text": "cpp-list" }, { "code": null, "e": 1299, "s": 1295, "text": "STL" }, { "code": null, "e": 1303, "s": 1299, "text": "C++" }, { "code": null, "e": 1307, "s": 1303, "text": "STL" }, { "code": null, "e": 1311, "s": 1307, "text": "CPP" }, { "code": null, "e": 1409, "s": 1311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1436, "s": 1409, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1479, "s": 1436, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1513, "s": 1479, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1538, "s": 1513, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1557, "s": 1538, "text": "Inheritance in C++" }, { "code": null, "e": 1574, "s": 1557, "text": "Substring in C++" }, { "code": null, "e": 1598, "s": 1574, "text": "C++ Classes and Objects" }, { "code": null, "e": 1622, "s": 1598, "text": "Sorting a vector in C++" }, { "code": null, "e": 1657, "s": 1622, "text": "Object Oriented Programming in C++" } ]
Moment.js moment().daysInMonth() Function
29 Jul, 2020 The moment().daysInMonth() function is used to get the number of days in month of a particular month in Node.js. It returns an integer denoting the number of days. Syntax: moment().daysInMonth(); Parameters: This function has no parameter. Return Value: This function returns integer. Installation of moment module: You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below. You can visit the link to Install moment module. You can install this package by using this command.npm install moment npm install moment After installing the moment module, you can check your moment version in command prompt using the command.npm version moment npm version moment After that, you can just create a folder and add a file for example, index.js as shown below. Example 1: Filename: index.js // Requiring the moduleconst moment = require('moment'); // Function callvar result = moment("2020-02", "YYYY-MM").daysInMonth() console.log("No of days in 2020-02 is:", result) Steps to run the program: The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of days in 2020-02 is: 29 The project structure will look like this: Run index.js file using below command:node index.jsOutput:No of days in 2020-02 is: 29 node index.js Output: No of days in 2020-02 is: 29 Example 2: Filename: index.js // Requiring the moduleconst moment = require('moment'); function getNoOfDays(date) { return moment(date, "YYYY-MM").daysInMonth() } // Function callvar result = getNoOfDays("2019-03");console.log("No of days in given date is:", result) Steps to run the program: The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of days in given date is: 31 The project structure will look like this: Run index.js file using below command:node index.jsOutput:No of days in given date is: 31 node index.js Output: No of days in given date is: 31 Reference: https://momentjs.com/docs/#/displaying/days-in-month/ Moment.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Windows JWT Authentication with Node.js Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2020" }, { "code": null, "e": 192, "s": 28, "text": "The moment().daysInMonth() function is used to get the number of days in month of a particular month in Node.js. It returns an integer denoting the number of days." }, { "code": null, "e": 200, "s": 192, "text": "Syntax:" }, { "code": null, "e": 224, "s": 200, "text": "moment().daysInMonth();" }, { "code": null, "e": 268, "s": 224, "text": "Parameters: This function has no parameter." }, { "code": null, "e": 313, "s": 268, "text": "Return Value: This function returns integer." }, { "code": null, "e": 344, "s": 313, "text": "Installation of moment module:" }, { "code": null, "e": 680, "s": 344, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js as shown below." }, { "code": null, "e": 799, "s": 680, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install moment" }, { "code": null, "e": 818, "s": 799, "text": "npm install moment" }, { "code": null, "e": 943, "s": 818, "text": "After installing the moment module, you can check your moment version in command prompt using the command.npm version moment" }, { "code": null, "e": 962, "s": 943, "text": "npm version moment" }, { "code": null, "e": 1056, "s": 962, "text": "After that, you can just create a folder and add a file for example, index.js as shown below." }, { "code": null, "e": 1086, "s": 1056, "text": "Example 1: Filename: index.js" }, { "code": "// Requiring the moduleconst moment = require('moment'); // Function callvar result = moment(\"2020-02\", \"YYYY-MM\").daysInMonth() console.log(\"No of days in 2020-02 is:\", result)", "e": 1267, "s": 1086, "text": null }, { "code": null, "e": 1293, "s": 1267, "text": "Steps to run the program:" }, { "code": null, "e": 1423, "s": 1293, "text": "The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of days in 2020-02 is: 29\n" }, { "code": null, "e": 1466, "s": 1423, "text": "The project structure will look like this:" }, { "code": null, "e": 1554, "s": 1466, "text": "Run index.js file using below command:node index.jsOutput:No of days in 2020-02 is: 29\n" }, { "code": null, "e": 1568, "s": 1554, "text": "node index.js" }, { "code": null, "e": 1576, "s": 1568, "text": "Output:" }, { "code": null, "e": 1606, "s": 1576, "text": "No of days in 2020-02 is: 29\n" }, { "code": null, "e": 1636, "s": 1606, "text": "Example 2: Filename: index.js" }, { "code": "// Requiring the moduleconst moment = require('moment'); function getNoOfDays(date) { return moment(date, \"YYYY-MM\").daysInMonth() } // Function callvar result = getNoOfDays(\"2019-03\");console.log(\"No of days in given date is:\", result)", "e": 1879, "s": 1636, "text": null }, { "code": null, "e": 1905, "s": 1879, "text": "Steps to run the program:" }, { "code": null, "e": 2038, "s": 1905, "text": "The project structure will look like this:Run index.js file using below command:node index.jsOutput:No of days in given date is: 31\n" }, { "code": null, "e": 2081, "s": 2038, "text": "The project structure will look like this:" }, { "code": null, "e": 2172, "s": 2081, "text": "Run index.js file using below command:node index.jsOutput:No of days in given date is: 31\n" }, { "code": null, "e": 2186, "s": 2172, "text": "node index.js" }, { "code": null, "e": 2194, "s": 2186, "text": "Output:" }, { "code": null, "e": 2227, "s": 2194, "text": "No of days in given date is: 31\n" }, { "code": null, "e": 2292, "s": 2227, "text": "Reference: https://momentjs.com/docs/#/displaying/days-in-month/" }, { "code": null, "e": 2302, "s": 2292, "text": "Moment.js" }, { "code": null, "e": 2310, "s": 2302, "text": "Node.js" }, { "code": null, "e": 2327, "s": 2310, "text": "Web Technologies" }, { "code": null, "e": 2425, "s": 2327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2460, "s": 2425, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2492, "s": 2460, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2562, "s": 2492, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2589, "s": 2562, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2614, "s": 2589, "text": "Mongoose find() Function" }, { "code": null, "e": 2676, "s": 2614, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2737, "s": 2676, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2787, "s": 2737, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2830, "s": 2787, "text": "How to fetch data from an API in ReactJS ?" } ]
How can I return multiple values from a function?
21 Sep, 2018 We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values.Well, first take a look at the declaration of a function. int foo(int arg1, int arg2); So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the globals inside the function) Let us take a deeper look...Even though a function can return only one value but that value can be of pointer type. That’s correct, now you’re speculating right!We can declare the function such that, it returns a structure type user defined variable or a pointer to it . And by the property of a structure, we know that a structure in C can hold multiple values of asymmetrical types (i.e. one int variable, four char variables, two float variables and so on...) If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function. How? By providing the pointers as arguments. Usually, when a function needs to return several values, we use one pointer in return instead of several pointers as arguments. Please see How to return multiple values from a function in C or C++? for more details. C-Functions c-puzzle C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library rand() and srand() in C/C++ Enumeration (or enum) in C C Language Introduction Power Function in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Sep, 2018" }, { "code": null, "e": 232, "s": 52, "text": "We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values.Well, first take a look at the declaration of a function." }, { "code": "int foo(int arg1, int arg2);", "e": 261, "s": 232, "text": null }, { "code": null, "e": 427, "s": 261, "text": "So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the globals inside the function)" }, { "code": null, "e": 890, "s": 427, "text": "Let us take a deeper look...Even though a function can return only one value but that value can be of pointer type. That’s correct, now you’re speculating right!We can declare the function such that, it returns a structure type user defined variable or a pointer to it . And by the property of a structure, we know that a structure in C can hold multiple values of asymmetrical types (i.e. one int variable, four char variables, two float variables and so on...)" }, { "code": null, "e": 1017, "s": 890, "text": "If we want the function to return multiple values of same data types, we could return the pointer to array of that data types." }, { "code": null, "e": 1155, "s": 1017, "text": "We can also make the function return multiple values by using the arguments of the function. How? By providing the pointers as arguments." }, { "code": null, "e": 1283, "s": 1155, "text": "Usually, when a function needs to return several values, we use one pointer in return instead of several pointers as arguments." }, { "code": null, "e": 1371, "s": 1283, "text": "Please see How to return multiple values from a function in C or C++? for more details." }, { "code": null, "e": 1383, "s": 1371, "text": "C-Functions" }, { "code": null, "e": 1392, "s": 1383, "text": "c-puzzle" }, { "code": null, "e": 1403, "s": 1392, "text": "C Language" }, { "code": null, "e": 1501, "s": 1403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1518, "s": 1501, "text": "Substring in C++" }, { "code": null, "e": 1540, "s": 1518, "text": "Function Pointer in C" }, { "code": null, "e": 1586, "s": 1540, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 1631, "s": 1586, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 1656, "s": 1631, "text": "std::string class in C++" }, { "code": null, "e": 1704, "s": 1656, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1732, "s": 1704, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 1759, "s": 1732, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 1783, "s": 1759, "text": "C Language Introduction" } ]
HTML <picture> Tag
20 May, 2021 The <picture> tag in HTML is used to give flexibility to the web-developers to specify image resources. The <picture> tag contains <source> and <img> tags. The attribute value is set to load more appropriate image. The <img> element is used for the last child element of the picture declaration block. The <img> element is used to provide backward compatibility for browsers that do not support the element, or if none of the source tags matched. The <picture> tag is similar to <video> and <audio>. We add different sources, and the first source that fits the preferences is the one that will be used. Syntax: <picture> Image and source tag <picture> Below example illustrates the <picture> tag in HTML: Example: html <!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <picture> Tag</h2> <picture> <source media="(min-width: 700px)" srcset="https://media.geeksforgeeks.org/wp-content/uploads/20190825000042/geeks-221.png"> <source media="(min-width: 450px)" srcset="https://media.geeksforgeeks.org/wp-content/uploads/20190802021607/geeks14.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190808102629/geeks15.png" alt="GFG" style="width:auto;"> </picture></body> </html> Output: Supported Browsers: Google Chrome 38.0 Internet Explorer 13.0 Firefox 38.0 Safari 9.1 Opera 25.0 ghoshsuman0129 HTML-Tags HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2021" }, { "code": null, "e": 476, "s": 28, "text": "The <picture> tag in HTML is used to give flexibility to the web-developers to specify image resources. The <picture> tag contains <source> and <img> tags. The attribute value is set to load more appropriate image. The <img> element is used for the last child element of the picture declaration block. The <img> element is used to provide backward compatibility for browsers that do not support the element, or if none of the source tags matched. " }, { "code": null, "e": 632, "s": 476, "text": "The <picture> tag is similar to <video> and <audio>. We add different sources, and the first source that fits the preferences is the one that will be used." }, { "code": null, "e": 641, "s": 632, "text": "Syntax: " }, { "code": null, "e": 686, "s": 641, "text": "<picture>\n Image and source tag\n<picture>" }, { "code": null, "e": 739, "s": 686, "text": "Below example illustrates the <picture> tag in HTML:" }, { "code": null, "e": 749, "s": 739, "text": "Example: " }, { "code": null, "e": 754, "s": 749, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML <picture> Tag</h2> <picture> <source media=\"(min-width: 700px)\" srcset=\"https://media.geeksforgeeks.org/wp-content/uploads/20190825000042/geeks-221.png\"> <source media=\"(min-width: 450px)\" srcset=\"https://media.geeksforgeeks.org/wp-content/uploads/20190802021607/geeks14.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190808102629/geeks15.png\" alt=\"GFG\" style=\"width:auto;\"> </picture></body> </html>", "e": 1474, "s": 754, "text": null }, { "code": null, "e": 1484, "s": 1474, "text": "Output: " }, { "code": null, "e": 1505, "s": 1484, "text": "Supported Browsers: " }, { "code": null, "e": 1524, "s": 1505, "text": "Google Chrome 38.0" }, { "code": null, "e": 1547, "s": 1524, "text": "Internet Explorer 13.0" }, { "code": null, "e": 1560, "s": 1547, "text": "Firefox 38.0" }, { "code": null, "e": 1571, "s": 1560, "text": "Safari 9.1" }, { "code": null, "e": 1582, "s": 1571, "text": "Opera 25.0" }, { "code": null, "e": 1597, "s": 1582, "text": "ghoshsuman0129" }, { "code": null, "e": 1607, "s": 1597, "text": "HTML-Tags" }, { "code": null, "e": 1612, "s": 1607, "text": "HTML" }, { "code": null, "e": 1629, "s": 1612, "text": "Web Technologies" }, { "code": null, "e": 1634, "s": 1629, "text": "HTML" }, { "code": null, "e": 1732, "s": 1634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1780, "s": 1732, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1804, "s": 1780, "text": "REST API (Introduction)" }, { "code": null, "e": 1854, "s": 1804, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1891, "s": 1854, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1930, "s": 1891, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1963, "s": 1930, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2024, "s": 1963, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2067, "s": 2024, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2139, "s": 2067, "text": "Differences between Functional Components and Class Components in React" } ]
Apache Pig - Grunt Shell
After invoking the Grunt shell, you can run your Pig scripts in the shell. In addition to that, there are certain useful shell and utility commands provided by the Grunt shell. This chapter explains the shell and utility commands provided by the Grunt shell. Note − In some portions of this chapter, the commands like Load and Store are used. Refer the respective chapters to get in-detail information on them. The Grunt shell of Apache Pig is mainly used to write Pig Latin scripts. Prior to that, we can invoke any shell commands using sh and fs. Using sh command, we can invoke any shell commands from the Grunt shell. Using sh command from the Grunt shell, we cannot execute the commands that are a part of the shell environment (ex − cd). Syntax Given below is the syntax of sh command. grunt> sh shell command parameters Example We can invoke the ls command of Linux shell from the Grunt shell using the sh option as shown below. In this example, it lists out the files in the /pig/bin/ directory. grunt> sh ls pig pig_1444799121955.log pig.cmd pig.py Using the fs command, we can invoke any FsShell commands from the Grunt shell. Syntax Given below is the syntax of fs command. grunt> sh File System command parameters Example We can invoke the ls command of HDFS from the Grunt shell using fs command. In the following example, it lists the files in the HDFS root directory. grunt> fs –ls Found 3 items drwxrwxrwx - Hadoop supergroup 0 2015-09-08 14:13 Hbase drwxr-xr-x - Hadoop supergroup 0 2015-09-09 14:52 seqgen_data drwxr-xr-x - Hadoop supergroup 0 2015-09-08 11:30 twitter_data In the same way, we can invoke all the other file system shell commands from the Grunt shell using the fs command. The Grunt shell provides a set of utility commands. These include utility commands such as clear, help, history, quit, and set; and commands such as exec, kill, and run to control Pig from the Grunt shell. Given below is the description of the utility commands provided by the Grunt shell. The clear command is used to clear the screen of the Grunt shell. Syntax You can clear the screen of the grunt shell using the clear command as shown below. grunt> clear The help command gives you a list of Pig commands or Pig properties. Usage You can get a list of Pig commands using the help command as shown below. grunt> help Commands: <pig latin statement>; - See the PigLatin manual for details: http://hadoop.apache.org/pig File system commands:fs <fs arguments> - Equivalent to Hadoop dfs command: http://hadoop.apache.org/common/docs/current/hdfs_shell.html Diagnostic Commands:describe <alias>[::<alias] - Show the schema for the alias. Inner aliases can be described as A::B. explain [-script <pigscript>] [-out <path>] [-brief] [-dot|-xml] [-param <param_name>=<pCram_value>] [-param_file <file_name>] [<alias>] - Show the execution plan to compute the alias or for entire script. -script - Explain the entire script. -out - Store the output into directory rather than print to stdout. -brief - Don't expand nested plans (presenting a smaller graph for overview). -dot - Generate the output in .dot format. Default is text format. -xml - Generate the output in .xml format. Default is text format. -param <param_name - See parameter substitution for details. -param_file <file_name> - See parameter substitution for details. alias - Alias to explain. dump <alias> - Compute the alias and writes the results to stdout. Utility Commands: exec [-param <param_name>=param_value] [-param_file <file_name>] <script> - Execute the script with access to grunt environment including aliases. -param <param_name - See parameter substitution for details. -param_file <file_name> - See parameter substitution for details. script - Script to be executed. run [-param <param_name>=param_value] [-param_file <file_name>] <script> - Execute the script with access to grunt environment. -param <param_name - See parameter substitution for details. -param_file <file_name> - See parameter substitution for details. script - Script to be executed. sh <shell command> - Invoke a shell command. kill <job_id> - Kill the hadoop job specified by the hadoop job id. set <key> <value> - Provide execution parameters to Pig. Keys and values are case sensitive. The following keys are supported: default_parallel - Script-level reduce parallelism. Basic input size heuristics used by default. debug - Set debug on or off. Default is off. job.name - Single-quoted name for jobs. Default is PigLatin:<script name> job.priority - Priority for jobs. Values: very_low, low, normal, high, very_high. Default is normal stream.skippath - String that contains the path. This is used by streaming any hadoop property. help - Display this message. history [-n] - Display the list statements in cache. -n Hide line numbers. quit - Quit the grunt shell. This command displays a list of statements executed / used so far since the Grunt sell is invoked. Usage Assume we have executed three statements since opening the Grunt shell. grunt> customers = LOAD 'hdfs://localhost:9000/pig_data/customers.txt' USING PigStorage(','); grunt> orders = LOAD 'hdfs://localhost:9000/pig_data/orders.txt' USING PigStorage(','); grunt> student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING PigStorage(','); Then, using the history command will produce the following output. grunt> history customers = LOAD 'hdfs://localhost:9000/pig_data/customers.txt' USING PigStorage(','); orders = LOAD 'hdfs://localhost:9000/pig_data/orders.txt' USING PigStorage(','); student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING PigStorage(','); The set command is used to show/assign values to keys used in Pig. Usage Using this command, you can set values to the following keys. You can set the job priority to a job by passing one of the following values to this key − very_low low normal high very_high You can quit from the Grunt shell using this command. Usage Quit from the Grunt shell as shown below. grunt> quit Let us now take a look at the commands using which you can control Apache Pig from the Grunt shell. Using the exec command, we can execute Pig scripts from the Grunt shell. Syntax Given below is the syntax of the utility command exec. grunt> exec [–param param_name = param_value] [–param_file file_name] [script] Example Let us assume there is a file named student.txt in the /pig_data/ directory of HDFS with the following content. Student.txt 001,Rajiv,Hyderabad 002,siddarth,Kolkata 003,Rajesh,Delhi And, assume we have a script file named sample_script.pig in the /pig_data/ directory of HDFS with the following content. Sample_script.pig student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING PigStorage(',') as (id:int,name:chararray,city:chararray); Dump student; Now, let us execute the above script from the Grunt shell using the exec command as shown below. grunt> exec /sample_script.pig Output The exec command executes the script in the sample_script.pig. As directed in the script, it loads the student.txt file into Pig and gives you the result of the Dump operator displaying the following content. (1,Rajiv,Hyderabad) (2,siddarth,Kolkata) (3,Rajesh,Delhi) You can kill a job from the Grunt shell using this command. Syntax Given below is the syntax of the kill command. grunt> kill JobId Example Suppose there is a running Pig job having id Id_0055, you can kill it from the Grunt shell using the kill command, as shown below. grunt> kill Id_0055 You can run a Pig script from the Grunt shell using the run command Syntax Given below is the syntax of the run command. grunt> run [–param param_name = param_value] [–param_file file_name] script Example Let us assume there is a file named student.txt in the /pig_data/ directory of HDFS with the following content. Student.txt 001,Rajiv,Hyderabad 002,siddarth,Kolkata 003,Rajesh,Delhi And, assume we have a script file named sample_script.pig in the local filesystem with the following content. Sample_script.pig student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING PigStorage(',') as (id:int,name:chararray,city:chararray); Now, let us run the above script from the Grunt shell using the run command as shown below. grunt> run /sample_script.pig You can see the output of the script using the Dump operator as shown below. grunt> Dump; (1,Rajiv,Hyderabad) (2,siddarth,Kolkata) (3,Rajesh,Delhi) Note − The difference between exec and the run command is that if we use run, the statements from the script are available in the command history.
[ { "code": null, "e": 3077, "s": 2818, "text": "After invoking the Grunt shell, you can run your Pig scripts in the shell. In addition to that, there are certain useful shell and utility commands provided by the Grunt shell. This chapter explains the shell and utility commands provided by the Grunt shell." }, { "code": null, "e": 3229, "s": 3077, "text": "Note − In some portions of this chapter, the commands like Load and Store are used. Refer the respective chapters to get in-detail information on them." }, { "code": null, "e": 3367, "s": 3229, "text": "The Grunt shell of Apache Pig is mainly used to write Pig Latin scripts. Prior to that, we can invoke any shell commands using sh and fs." }, { "code": null, "e": 3562, "s": 3367, "text": "Using sh command, we can invoke any shell commands from the Grunt shell. Using sh command from the Grunt shell, we cannot execute the commands that are a part of the shell environment (ex − cd)." }, { "code": null, "e": 3569, "s": 3562, "text": "Syntax" }, { "code": null, "e": 3610, "s": 3569, "text": "Given below is the syntax of sh command." }, { "code": null, "e": 3646, "s": 3610, "text": "grunt> sh shell command parameters\n" }, { "code": null, "e": 3654, "s": 3646, "text": "Example" }, { "code": null, "e": 3823, "s": 3654, "text": "We can invoke the ls command of Linux shell from the Grunt shell using the sh option as shown below. In this example, it lists out the files in the /pig/bin/ directory." }, { "code": null, "e": 3885, "s": 3823, "text": "grunt> sh ls\n \npig \npig_1444799121955.log \npig.cmd \npig.py\n" }, { "code": null, "e": 3964, "s": 3885, "text": "Using the fs command, we can invoke any FsShell commands from the Grunt shell." }, { "code": null, "e": 3971, "s": 3964, "text": "Syntax" }, { "code": null, "e": 4012, "s": 3971, "text": "Given below is the syntax of fs command." }, { "code": null, "e": 4054, "s": 4012, "text": "grunt> sh File System command parameters\n" }, { "code": null, "e": 4062, "s": 4054, "text": "Example" }, { "code": null, "e": 4211, "s": 4062, "text": "We can invoke the ls command of HDFS from the Grunt shell using fs command. In the following example, it lists the files in the HDFS root directory." }, { "code": null, "e": 4457, "s": 4211, "text": "grunt> fs –ls\n \nFound 3 items\ndrwxrwxrwx - Hadoop supergroup 0 2015-09-08 14:13 Hbase\ndrwxr-xr-x - Hadoop supergroup 0 2015-09-09 14:52 seqgen_data\ndrwxr-xr-x - Hadoop supergroup 0 2015-09-08 11:30 twitter_data\n" }, { "code": null, "e": 4572, "s": 4457, "text": "In the same way, we can invoke all the other file system shell commands from the Grunt shell using the fs command." }, { "code": null, "e": 4862, "s": 4572, "text": "The Grunt shell provides a set of utility commands. These include utility commands such as clear, help, history, quit, and set; and commands such as exec, kill, and run to control Pig from the Grunt shell. Given below is the description of the utility commands provided by the Grunt shell." }, { "code": null, "e": 4928, "s": 4862, "text": "The clear command is used to clear the screen of the Grunt shell." }, { "code": null, "e": 4935, "s": 4928, "text": "Syntax" }, { "code": null, "e": 5019, "s": 4935, "text": "You can clear the screen of the grunt shell using the clear command as shown below." }, { "code": null, "e": 5033, "s": 5019, "text": "grunt> clear\n" }, { "code": null, "e": 5102, "s": 5033, "text": "The help command gives you a list of Pig commands or Pig properties." }, { "code": null, "e": 5108, "s": 5102, "text": "Usage" }, { "code": null, "e": 5182, "s": 5108, "text": "You can get a list of Pig commands using the help command as shown below." }, { "code": null, "e": 7950, "s": 5182, "text": "grunt> help\n\nCommands: <pig latin statement>; - See the PigLatin manual for details:\nhttp://hadoop.apache.org/pig\n \nFile system commands:fs <fs arguments> - Equivalent to Hadoop dfs command:\nhttp://hadoop.apache.org/common/docs/current/hdfs_shell.html\n\t \nDiagnostic Commands:describe <alias>[::<alias] - Show the schema for the alias.\nInner aliases can be described as A::B.\n explain [-script <pigscript>] [-out <path>] [-brief] [-dot|-xml] \n [-param <param_name>=<pCram_value>]\n [-param_file <file_name>] [<alias>] - \n Show the execution plan to compute the alias or for entire script.\n -script - Explain the entire script.\n -out - Store the output into directory rather than print to stdout.\n -brief - Don't expand nested plans (presenting a smaller graph for overview).\n -dot - Generate the output in .dot format. Default is text format.\n -xml - Generate the output in .xml format. Default is text format.\n -param <param_name - See parameter substitution for details.\n -param_file <file_name> - See parameter substitution for details.\n alias - Alias to explain.\n dump <alias> - Compute the alias and writes the results to stdout.\n\nUtility Commands: exec [-param <param_name>=param_value] [-param_file <file_name>] <script> -\n Execute the script with access to grunt environment including aliases.\n -param <param_name - See parameter substitution for details.\n -param_file <file_name> - See parameter substitution for details.\n script - Script to be executed.\n run [-param <param_name>=param_value] [-param_file <file_name>] <script> -\n Execute the script with access to grunt environment.\n\t\t -param <param_name - See parameter substitution for details. \n -param_file <file_name> - See parameter substitution for details.\n script - Script to be executed.\n sh <shell command> - Invoke a shell command.\n kill <job_id> - Kill the hadoop job specified by the hadoop job id.\n set <key> <value> - Provide execution parameters to Pig. Keys and values are case sensitive.\n The following keys are supported:\n default_parallel - Script-level reduce parallelism. Basic input size heuristics used \n by default.\n debug - Set debug on or off. Default is off.\n job.name - Single-quoted name for jobs. Default is PigLatin:<script name> \n job.priority - Priority for jobs. Values: very_low, low, normal, high, very_high.\n Default is normal stream.skippath - String that contains the path.\n This is used by streaming any hadoop property.\n help - Display this message.\n history [-n] - Display the list statements in cache.\n -n Hide line numbers.\n quit - Quit the grunt shell. \n" }, { "code": null, "e": 8049, "s": 7950, "text": "This command displays a list of statements executed / used so far since the Grunt sell is invoked." }, { "code": null, "e": 8055, "s": 8049, "text": "Usage" }, { "code": null, "e": 8127, "s": 8055, "text": "Assume we have executed three statements since opening the Grunt shell." }, { "code": null, "e": 8405, "s": 8127, "text": "grunt> customers = LOAD 'hdfs://localhost:9000/pig_data/customers.txt' USING PigStorage(',');\n \ngrunt> orders = LOAD 'hdfs://localhost:9000/pig_data/orders.txt' USING PigStorage(',');\n \ngrunt> student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING PigStorage(',');\n " }, { "code": null, "e": 8472, "s": 8405, "text": "Then, using the history command will produce the following output." }, { "code": null, "e": 8750, "s": 8472, "text": "grunt> history\n\ncustomers = LOAD 'hdfs://localhost:9000/pig_data/customers.txt' USING PigStorage(','); \n \norders = LOAD 'hdfs://localhost:9000/pig_data/orders.txt' USING PigStorage(',');\n \nstudent = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING PigStorage(',');\n \n" }, { "code": null, "e": 8817, "s": 8750, "text": "The set command is used to show/assign values to keys used in Pig." }, { "code": null, "e": 8823, "s": 8817, "text": "Usage" }, { "code": null, "e": 8885, "s": 8823, "text": "Using this command, you can set values to the following keys." }, { "code": null, "e": 8976, "s": 8885, "text": "You can set the job priority to a job by passing one of the following values to this key −" }, { "code": null, "e": 8985, "s": 8976, "text": "very_low" }, { "code": null, "e": 8989, "s": 8985, "text": "low" }, { "code": null, "e": 8996, "s": 8989, "text": "normal" }, { "code": null, "e": 9001, "s": 8996, "text": "high" }, { "code": null, "e": 9011, "s": 9001, "text": "very_high" }, { "code": null, "e": 9065, "s": 9011, "text": "You can quit from the Grunt shell using this command." }, { "code": null, "e": 9071, "s": 9065, "text": "Usage" }, { "code": null, "e": 9113, "s": 9071, "text": "Quit from the Grunt shell as shown below." }, { "code": null, "e": 9126, "s": 9113, "text": "grunt> quit\n" }, { "code": null, "e": 9226, "s": 9126, "text": "Let us now take a look at the commands using which you can control Apache Pig from the Grunt shell." }, { "code": null, "e": 9299, "s": 9226, "text": "Using the exec command, we can execute Pig scripts from the Grunt shell." }, { "code": null, "e": 9306, "s": 9299, "text": "Syntax" }, { "code": null, "e": 9361, "s": 9306, "text": "Given below is the syntax of the utility command exec." }, { "code": null, "e": 9441, "s": 9361, "text": "grunt> exec [–param param_name = param_value] [–param_file file_name] [script]\n" }, { "code": null, "e": 9449, "s": 9441, "text": "Example" }, { "code": null, "e": 9561, "s": 9449, "text": "Let us assume there is a file named student.txt in the /pig_data/ directory of HDFS with the following content." }, { "code": null, "e": 9573, "s": 9561, "text": "Student.txt" }, { "code": null, "e": 9632, "s": 9573, "text": "001,Rajiv,Hyderabad\n002,siddarth,Kolkata\n003,Rajesh,Delhi\n" }, { "code": null, "e": 9754, "s": 9632, "text": "And, assume we have a script file named sample_script.pig in the /pig_data/ directory of HDFS with the following content." }, { "code": null, "e": 9772, "s": 9754, "text": "Sample_script.pig" }, { "code": null, "e": 9918, "s": 9772, "text": "student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING PigStorage(',') \n as (id:int,name:chararray,city:chararray);\n \nDump student;" }, { "code": null, "e": 10015, "s": 9918, "text": "Now, let us execute the above script from the Grunt shell using the exec command as shown below." }, { "code": null, "e": 10047, "s": 10015, "text": "grunt> exec /sample_script.pig\n" }, { "code": null, "e": 10054, "s": 10047, "text": "Output" }, { "code": null, "e": 10263, "s": 10054, "text": "The exec command executes the script in the sample_script.pig. As directed in the script, it loads the student.txt file into Pig and gives you the result of the Dump operator displaying the following content." }, { "code": null, "e": 10323, "s": 10263, "text": "(1,Rajiv,Hyderabad)\n(2,siddarth,Kolkata)\n(3,Rajesh,Delhi) \n" }, { "code": null, "e": 10383, "s": 10323, "text": "You can kill a job from the Grunt shell using this command." }, { "code": null, "e": 10390, "s": 10383, "text": "Syntax" }, { "code": null, "e": 10437, "s": 10390, "text": "Given below is the syntax of the kill command." }, { "code": null, "e": 10456, "s": 10437, "text": "grunt> kill JobId\n" }, { "code": null, "e": 10464, "s": 10456, "text": "Example" }, { "code": null, "e": 10595, "s": 10464, "text": "Suppose there is a running Pig job having id Id_0055, you can kill it from the Grunt shell using the kill command, as shown below." }, { "code": null, "e": 10616, "s": 10595, "text": "grunt> kill Id_0055\n" }, { "code": null, "e": 10684, "s": 10616, "text": "You can run a Pig script from the Grunt shell using the run command" }, { "code": null, "e": 10691, "s": 10684, "text": "Syntax" }, { "code": null, "e": 10737, "s": 10691, "text": "Given below is the syntax of the run command." }, { "code": null, "e": 10814, "s": 10737, "text": "grunt> run [–param param_name = param_value] [–param_file file_name] script\n" }, { "code": null, "e": 10822, "s": 10814, "text": "Example" }, { "code": null, "e": 10934, "s": 10822, "text": "Let us assume there is a file named student.txt in the /pig_data/ directory of HDFS with the following content." }, { "code": null, "e": 10946, "s": 10934, "text": "Student.txt" }, { "code": null, "e": 11005, "s": 10946, "text": "001,Rajiv,Hyderabad\n002,siddarth,Kolkata\n003,Rajesh,Delhi\n" }, { "code": null, "e": 11115, "s": 11005, "text": "And, assume we have a script file named sample_script.pig in the local filesystem with the following content." }, { "code": null, "e": 11133, "s": 11115, "text": "Sample_script.pig" }, { "code": null, "e": 11261, "s": 11133, "text": "student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING\n PigStorage(',') as (id:int,name:chararray,city:chararray);" }, { "code": null, "e": 11353, "s": 11261, "text": "Now, let us run the above script from the Grunt shell using the run command as shown below." }, { "code": null, "e": 11384, "s": 11353, "text": "grunt> run /sample_script.pig\n" }, { "code": null, "e": 11461, "s": 11384, "text": "You can see the output of the script using the Dump operator as shown below." }, { "code": null, "e": 11534, "s": 11461, "text": "grunt> Dump;\n\n(1,Rajiv,Hyderabad)\n(2,siddarth,Kolkata)\n(3,Rajesh,Delhi)\n" } ]
Random nextGaussian() method in Java with Examples
07 Jan, 2019 The nextGaussian() method of Random class returns the next pseudorandom, Gaussian(normally) distributed double value with mean 0.0 and standard deviation 1.0 from the random number generator’s sequence. Syntax: public double nextGaussian() Parameters: The function does not accepts any parameter. Return Value: This method returns the next pseudorandom Gaussian distributed double number with mean 0.0 and standard deviation 1.0. Exception: The function does not throws any exception. Program below demonstrates the above mentioned function: Program 1: // program to demonstrate the// function java.util.Random.nextGaussian() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // check next Gaussian value and print it System.out.println("Next Gaussian value is = " + r.nextGaussian()); }} Next Gaussian value is = 0.3350871100964153 Program 2: // program to demonstrate the// function java.util.Random.nextGaussian() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // check next Gaussian value and print it System.out.println("Next Gaussian value is = " + r.nextGaussian()); }} Next Gaussian value is = 1.5685150659018154 Java-Functions Java-Random Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2019" }, { "code": null, "e": 231, "s": 28, "text": "The nextGaussian() method of Random class returns the next pseudorandom, Gaussian(normally) distributed double value with mean 0.0 and standard deviation 1.0 from the random number generator’s sequence." }, { "code": null, "e": 239, "s": 231, "text": "Syntax:" }, { "code": null, "e": 269, "s": 239, "text": "public double nextGaussian()\n" }, { "code": null, "e": 326, "s": 269, "text": "Parameters: The function does not accepts any parameter." }, { "code": null, "e": 459, "s": 326, "text": "Return Value: This method returns the next pseudorandom Gaussian distributed double number with mean 0.0 and standard deviation 1.0." }, { "code": null, "e": 514, "s": 459, "text": "Exception: The function does not throws any exception." }, { "code": null, "e": 571, "s": 514, "text": "Program below demonstrates the above mentioned function:" }, { "code": null, "e": 582, "s": 571, "text": "Program 1:" }, { "code": "// program to demonstrate the// function java.util.Random.nextGaussian() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // check next Gaussian value and print it System.out.println(\"Next Gaussian value is = \" + r.nextGaussian()); }}", "e": 964, "s": 582, "text": null }, { "code": null, "e": 1009, "s": 964, "text": "Next Gaussian value is = 0.3350871100964153\n" }, { "code": null, "e": 1020, "s": 1009, "text": "Program 2:" }, { "code": "// program to demonstrate the// function java.util.Random.nextGaussian() import java.util.*;public class GFG { public static void main(String[] args) { // create random object Random r = new Random(); // check next Gaussian value and print it System.out.println(\"Next Gaussian value is = \" + r.nextGaussian()); }}", "e": 1402, "s": 1020, "text": null }, { "code": null, "e": 1447, "s": 1402, "text": "Next Gaussian value is = 1.5685150659018154\n" }, { "code": null, "e": 1462, "s": 1447, "text": "Java-Functions" }, { "code": null, "e": 1474, "s": 1462, "text": "Java-Random" }, { "code": null, "e": 1479, "s": 1474, "text": "Java" }, { "code": null, "e": 1484, "s": 1479, "text": "Java" }, { "code": null, "e": 1582, "s": 1484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1633, "s": 1582, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 1664, "s": 1633, "text": "How to iterate any Map in Java" }, { "code": null, "e": 1683, "s": 1664, "text": "Interfaces in Java" }, { "code": null, "e": 1713, "s": 1683, "text": "HashMap in Java with Examples" }, { "code": null, "e": 1731, "s": 1713, "text": "ArrayList in Java" }, { "code": null, "e": 1751, "s": 1731, "text": "Collections in Java" }, { "code": null, "e": 1766, "s": 1751, "text": "Stream In Java" }, { "code": null, "e": 1798, "s": 1766, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 1822, "s": 1798, "text": "Singleton Class in Java" } ]
Convert DataFrame with Date Column to Time Series Object in R
23 May, 2021 In this article, we will discuss how to convert dataframe with date column to time series object in the R programming language. Time series object are a series of data points in which each data point is associated with a timestamp. For example, is a price of a stock in the stock market at different points of time. The data for the time series is stored in an R object called time-series object. These are also called as xts / zoo Object. To convert the given dataframe with the date column to the time series object, the user first needs to import and load the xts package. Syntax: install.packages(“xts”) library(“xts”) The user then needs to call the xts() function with the required parameters the main need to call this function is to create the time-series object in R language and at the end use is.xts() function we will be conforming to the time-series object created by xts() function in R language. xts() function is basically used as the constructor for creating an extensible time-series object. Syntax: xts(x = NULL, order.by = index(x), frequency = NULL, unique = TRUE, tzone = Sys.getenv(“TZ”), ...) Parameters: x:-an object containing the time series data order.by:-a corresponding vector of unique times/dates – must be of a known time-based class. frequency:-numeric indicating the frequency of order. unique:-should index be checked for unique time-stamps? tzone:-time zone of series. This is ignored for Date indices ...:-additional attributes to be added. Example: R library("xts") gfg_date <- data.frame(date = c("2004-05-07","2005-10-12", "2011-11-11","2020-11-11", "2021-12-11"),val=c(1,2,3,4,5)) gfg_date$date<-as.Date(gfg_date$date) gfg_ts <- xts(gfg_date$val, gfg_date$date)gfg_ts is.xts(gfg_ts) 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. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2021" }, { "code": null, "e": 156, "s": 28, "text": "In this article, we will discuss how to convert dataframe with date column to time series object in the R programming language." }, { "code": null, "e": 468, "s": 156, "text": "Time series object are a series of data points in which each data point is associated with a timestamp. For example, is a price of a stock in the stock market at different points of time. The data for the time series is stored in an R object called time-series object. These are also called as xts / zoo Object." }, { "code": null, "e": 604, "s": 468, "text": "To convert the given dataframe with the date column to the time series object, the user first needs to import and load the xts package." }, { "code": null, "e": 612, "s": 604, "text": "Syntax:" }, { "code": null, "e": 655, "s": 612, "text": "install.packages(“xts”) " }, { "code": null, "e": 670, "s": 655, "text": "library(“xts”)" }, { "code": null, "e": 958, "s": 670, "text": "The user then needs to call the xts() function with the required parameters the main need to call this function is to create the time-series object in R language and at the end use is.xts() function we will be conforming to the time-series object created by xts() function in R language." }, { "code": null, "e": 1058, "s": 958, "text": " xts() function is basically used as the constructor for creating an extensible time-series object." }, { "code": null, "e": 1066, "s": 1058, "text": "Syntax:" }, { "code": null, "e": 1167, "s": 1066, "text": "xts(x = NULL, order.by = index(x), frequency = NULL, unique = TRUE, tzone = Sys.getenv(“TZ”), ...)" }, { "code": null, "e": 1179, "s": 1167, "text": "Parameters:" }, { "code": null, "e": 1224, "s": 1179, "text": "x:-an object containing the time series data" }, { "code": null, "e": 1318, "s": 1224, "text": "order.by:-a corresponding vector of unique times/dates – must be of a known time-based class." }, { "code": null, "e": 1372, "s": 1318, "text": "frequency:-numeric indicating the frequency of order." }, { "code": null, "e": 1428, "s": 1372, "text": "unique:-should index be checked for unique time-stamps?" }, { "code": null, "e": 1489, "s": 1428, "text": "tzone:-time zone of series. This is ignored for Date indices" }, { "code": null, "e": 1529, "s": 1489, "text": "...:-additional attributes to be added." }, { "code": null, "e": 1538, "s": 1529, "text": "Example:" }, { "code": null, "e": 1540, "s": 1538, "text": "R" }, { "code": "library(\"xts\") gfg_date <- data.frame(date = c(\"2004-05-07\",\"2005-10-12\", \"2011-11-11\",\"2020-11-11\", \"2021-12-11\"),val=c(1,2,3,4,5)) gfg_date$date<-as.Date(gfg_date$date) gfg_ts <- xts(gfg_date$val, gfg_date$date)gfg_ts is.xts(gfg_ts)", "e": 1847, "s": 1540, "text": null }, { "code": null, "e": 1855, "s": 1847, "text": "Output:" }, { "code": null, "e": 1862, "s": 1855, "text": "Picked" }, { "code": null, "e": 1883, "s": 1862, "text": "R DataFrame-Programs" }, { "code": null, "e": 1895, "s": 1883, "text": "R-DataFrame" }, { "code": null, "e": 1906, "s": 1895, "text": "R Language" }, { "code": null, "e": 1917, "s": 1906, "text": "R Programs" }, { "code": null, "e": 2015, "s": 1917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2067, "s": 2015, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2125, "s": 2067, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2160, "s": 2125, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2198, "s": 2160, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2247, "s": 2198, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2305, "s": 2247, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2354, "s": 2305, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2397, "s": 2354, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2435, "s": 2397, "text": "Merge DataFrames by Column Names in R" } ]
Scala | map() method
14 Mar, 2019 A collection in Scala is a data structure which holds a group of objects. Examples of collections include Arrays, Lists, etc. We can apply some transformations to these collections using several methods. One such widely used method offered by Scala is map().Important points about map() method: map() is a higher order function. Every collection object has the map() method. map() takes some function as a parameter. map() applies the function to every element of the source collection. map() returns a new collection of the same type as the source collection. Syntax: collection = (e1, e2, e3, ...) //func is some function collection.map(func) //returns collection(func(e1), func(e2), func(e3), ...) Example 1: Using user-defined function // Scala program to// transform a collection// using map() //Creating objectobject GfG{ // square of an integer def square(a:Int):Int = { a*a } // Main method def main(args:Array[String]) { // source collection val collection = List(1, 3, 2, 5, 4, 7, 6) // transformed collection val new_collection = collection.map(square) println(new_collection) } } List(1, 9, 4, 25, 16, 49, 36) In the above example, we are passing a user-defined function square as a parameter to the map() method. A new collection is created which contains squares of elements of the original collection. The source collection remains unaffected. Example 2: Using anonymous function // Scala program to// transform a collection// using map() //Creating objectobject GfG{ // Main method def main(args:Array[String]) { // source collection val collection = List(1, 3, 2, 5, 4, 7, 6) // transformed collection val new_collection = collection.map(x => x * x ) println(new_collection) }} List(1, 9, 4, 25, 16, 49, 36) In the above example, an anonymous function is passed as a parameter to the map() method instead of defining a whole function for square operation. This approach reduces the code size. Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Singleton and Companion Objects Introduction to Scala Method Overloading in Scala Scala | yield Keyword Throw Keyword in Scala Scala | Functions - Basics Scala | Option Tail Recursion in Scala Scala | Traits
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Mar, 2019" }, { "code": null, "e": 323, "s": 28, "text": "A collection in Scala is a data structure which holds a group of objects. Examples of collections include Arrays, Lists, etc. We can apply some transformations to these collections using several methods. One such widely used method offered by Scala is map().Important points about map() method:" }, { "code": null, "e": 357, "s": 323, "text": "map() is a higher order function." }, { "code": null, "e": 403, "s": 357, "text": "Every collection object has the map() method." }, { "code": null, "e": 445, "s": 403, "text": "map() takes some function as a parameter." }, { "code": null, "e": 515, "s": 445, "text": "map() applies the function to every element of the source collection." }, { "code": null, "e": 589, "s": 515, "text": "map() returns a new collection of the same type as the source collection." }, { "code": null, "e": 597, "s": 589, "text": "Syntax:" }, { "code": null, "e": 732, "s": 597, "text": "collection = (e1, e2, e3, ...)\n\n//func is some function\ncollection.map(func)\n\n//returns collection(func(e1), func(e2), func(e3), ...)\n" }, { "code": null, "e": 771, "s": 732, "text": "Example 1: Using user-defined function" }, { "code": "// Scala program to// transform a collection// using map() //Creating objectobject GfG{ // square of an integer def square(a:Int):Int = { a*a } // Main method def main(args:Array[String]) { // source collection val collection = List(1, 3, 2, 5, 4, 7, 6) // transformed collection val new_collection = collection.map(square) println(new_collection) } }", "e": 1208, "s": 771, "text": null }, { "code": null, "e": 1239, "s": 1208, "text": "List(1, 9, 4, 25, 16, 49, 36)\n" }, { "code": null, "e": 1476, "s": 1239, "text": "In the above example, we are passing a user-defined function square as a parameter to the map() method. A new collection is created which contains squares of elements of the original collection. The source collection remains unaffected." }, { "code": null, "e": 1512, "s": 1476, "text": "Example 2: Using anonymous function" }, { "code": "// Scala program to// transform a collection// using map() //Creating objectobject GfG{ // Main method def main(args:Array[String]) { // source collection val collection = List(1, 3, 2, 5, 4, 7, 6) // transformed collection val new_collection = collection.map(x => x * x ) println(new_collection) }}", "e": 1870, "s": 1512, "text": null }, { "code": null, "e": 1901, "s": 1870, "text": "List(1, 9, 4, 25, 16, 49, 36)\n" }, { "code": null, "e": 2086, "s": 1901, "text": "In the above example, an anonymous function is passed as a parameter to the map() method instead of defining a whole function for square operation. This approach reduces the code size." }, { "code": null, "e": 2092, "s": 2086, "text": "Scala" }, { "code": null, "e": 2105, "s": 2092, "text": "Scala-Method" }, { "code": null, "e": 2111, "s": 2105, "text": "Scala" }, { "code": null, "e": 2209, "s": 2111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2235, "s": 2209, "text": "Class and Object in Scala" }, { "code": null, "e": 2273, "s": 2235, "text": "Scala Singleton and Companion Objects" }, { "code": null, "e": 2295, "s": 2273, "text": "Introduction to Scala" }, { "code": null, "e": 2323, "s": 2295, "text": "Method Overloading in Scala" }, { "code": null, "e": 2345, "s": 2323, "text": "Scala | yield Keyword" }, { "code": null, "e": 2368, "s": 2345, "text": "Throw Keyword in Scala" }, { "code": null, "e": 2395, "s": 2368, "text": "Scala | Functions - Basics" }, { "code": null, "e": 2410, "s": 2395, "text": "Scala | Option" }, { "code": null, "e": 2434, "s": 2410, "text": "Tail Recursion in Scala" } ]
Static Blocks in Java
10 May, 2022 In simpler language whenever we use a static keyword and associate it to a block then that block is referred to as a static block. Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory. Calling of static block in java? Now comes the point of how to call this static block. So in order to call any static block, there is no specified way as static block executes automatically when the class is loaded in memory. Refer to the below illustration for understanding how static block is called. Illustration: class GFG { // Constructor of this class GFG() {} // Method of this class public static void print() { } static{} public static void main(String[] args) { // Calling of method inside main() GFG geeks = new GFG(); // Calling of constructor inside main() new GFG(); // Calling of static block // Nothing to do here as it is called // automatically as class is loaded in memory } } Note: From the above illustration we can perceive that static blocks are automatically called as soon as class is loaded in memory and there is nothing to do as we have to in case of calling methods and constructors inside main(). Can we print something on the console without creating main() method? It is very important question from the interview’s perceptive point. The answer is yes we can print if we are using JDK version 1.6 or previous and if after that it will throw an. error. Example 1-A: Running on JDK version 1.6 of Previous Java // Java Program Running on JDK version 1.6 of Previous // Main classclass GFG { // Static block static { // Print statement System.out.print( "Static block can be printed without main method"); }} Output: Static block can be printed without main method Example 1-B: Running on JDK version 1.6 and Later Java // Java Program Running on JDK version 1.6 and Later // Main classclass GFG { // Static block static { // Print statement System.out.print( "Static block can be printed without main method"); }} Output: Example 1: Java // Java Program to Illustrate How Static block is Called // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: non-static variables int j; // Case 3: Static block // Start of static block static { i = 10; System.out.println("static block called "); } // End of static block} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we don't have an object of Test, static // block is called because i is being accessed in // following statement. System.out.println(Test.i); }} static block called 10 Remember: Static blocks can also be executed before constructors. Example 2: Java // Java Program to Illustrate Execution of Static Block// Before Constructors // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: Non-static variable int j; // Case 3: Static blocks static { i = 10; System.out.println("static block called "); } // Constructor calling Test() { System.out.println("Constructor called"); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we have two objects, static block is // executed only once. Test t1 = new Test(); Test t2 = new Test(); }} static block called Constructor called Constructor called A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ayushpratapsingh amsherihan solankimayank singghakshay as5853535 kk773572498 draghavgupta96 sagartomar9927 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2022" }, { "code": null, "e": 437, "s": 52, "text": "In simpler language whenever we use a static keyword and associate it to a block then that block is referred to as a static block. Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory. " }, { "code": null, "e": 470, "s": 437, "text": "Calling of static block in java?" }, { "code": null, "e": 741, "s": 470, "text": "Now comes the point of how to call this static block. So in order to call any static block, there is no specified way as static block executes automatically when the class is loaded in memory. Refer to the below illustration for understanding how static block is called." }, { "code": null, "e": 755, "s": 741, "text": "Illustration:" }, { "code": null, "e": 1326, "s": 755, "text": "class GFG {\n\n // Constructor of this class\n GFG() {}\n \n // Method of this class\n public static void print() { }\n \n static{}\n\n public static void main(String[] args) {\n\n // Calling of method inside main()\n GFG geeks = new GFG();\n\n // Calling of constructor inside main()\n new GFG();\n\n // Calling of static block\n // Nothing to do here as it is called\n // automatically as class is loaded in memory\n\n }\n}" }, { "code": null, "e": 1558, "s": 1326, "text": "Note: From the above illustration we can perceive that static blocks are automatically called as soon as class is loaded in memory and there is nothing to do as we have to in case of calling methods and constructors inside main(). " }, { "code": null, "e": 1628, "s": 1558, "text": "Can we print something on the console without creating main() method?" }, { "code": null, "e": 1817, "s": 1628, "text": "It is very important question from the interview’s perceptive point. The answer is yes we can print if we are using JDK version 1.6 or previous and if after that it will throw an. error. " }, { "code": null, "e": 1870, "s": 1817, "text": "Example 1-A: Running on JDK version 1.6 of Previous" }, { "code": null, "e": 1875, "s": 1870, "text": "Java" }, { "code": "// Java Program Running on JDK version 1.6 of Previous // Main classclass GFG { // Static block static { // Print statement System.out.print( \"Static block can be printed without main method\"); }}", "e": 2112, "s": 1875, "text": null }, { "code": null, "e": 2120, "s": 2112, "text": "Output:" }, { "code": null, "e": 2168, "s": 2120, "text": "Static block can be printed without main method" }, { "code": null, "e": 2218, "s": 2168, "text": "Example 1-B: Running on JDK version 1.6 and Later" }, { "code": null, "e": 2223, "s": 2218, "text": "Java" }, { "code": "// Java Program Running on JDK version 1.6 and Later // Main classclass GFG { // Static block static { // Print statement System.out.print( \"Static block can be printed without main method\"); }}", "e": 2458, "s": 2223, "text": null }, { "code": null, "e": 2467, "s": 2458, "text": "Output: " }, { "code": null, "e": 2478, "s": 2467, "text": "Example 1:" }, { "code": null, "e": 2483, "s": 2478, "text": "Java" }, { "code": "// Java Program to Illustrate How Static block is Called // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: non-static variables int j; // Case 3: Static block // Start of static block static { i = 10; System.out.println(\"static block called \"); } // End of static block} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we don't have an object of Test, static // block is called because i is being accessed in // following statement. System.out.println(Test.i); }}", "e": 3137, "s": 2483, "text": null }, { "code": null, "e": 3161, "s": 3137, "text": "static block called \n10" }, { "code": null, "e": 3227, "s": 3161, "text": "Remember: Static blocks can also be executed before constructors." }, { "code": null, "e": 3238, "s": 3227, "text": "Example 2:" }, { "code": null, "e": 3243, "s": 3238, "text": "Java" }, { "code": "// Java Program to Illustrate Execution of Static Block// Before Constructors // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: Non-static variable int j; // Case 3: Static blocks static { i = 10; System.out.println(\"static block called \"); } // Constructor calling Test() { System.out.println(\"Constructor called\"); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we have two objects, static block is // executed only once. Test t1 = new Test(); Test t2 = new Test(); }}", "e": 3909, "s": 3243, "text": null }, { "code": null, "e": 3968, "s": 3909, "text": "static block called \nConstructor called\nConstructor called" }, { "code": null, "e": 4202, "s": 3968, "text": "A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code." }, { "code": null, "e": 4364, "s": 4202, "text": "Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development. " }, { "code": null, "e": 4489, "s": 4364, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4506, "s": 4489, "text": "ayushpratapsingh" }, { "code": null, "e": 4517, "s": 4506, "text": "amsherihan" }, { "code": null, "e": 4531, "s": 4517, "text": "solankimayank" }, { "code": null, "e": 4544, "s": 4531, "text": "singghakshay" }, { "code": null, "e": 4554, "s": 4544, "text": "as5853535" }, { "code": null, "e": 4566, "s": 4554, "text": "kk773572498" }, { "code": null, "e": 4581, "s": 4566, "text": "draghavgupta96" }, { "code": null, "e": 4596, "s": 4581, "text": "sagartomar9927" }, { "code": null, "e": 4601, "s": 4596, "text": "Java" }, { "code": null, "e": 4606, "s": 4601, "text": "Java" }, { "code": null, "e": 4704, "s": 4606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4719, "s": 4704, "text": "Arrays in Java" }, { "code": null, "e": 4763, "s": 4719, "text": "Split() String method in Java with examples" }, { "code": null, "e": 4788, "s": 4763, "text": "Reverse a string in Java" }, { "code": null, "e": 4824, "s": 4788, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 4875, "s": 4824, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4897, "s": 4875, "text": "For-each loop in Java" }, { "code": null, "e": 4928, "s": 4897, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4947, "s": 4928, "text": "Interfaces in Java" }, { "code": null, "e": 4977, "s": 4947, "text": "HashMap in Java with Examples" } ]
Spring Data JPA – @Id Annotation
29 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernate. In this article, we will discuss how to make a specific variable of the class primary key in the Spring Application. @Id annotation is the JPA is used for making specific variable primary key. The @Id annotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of the current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation. Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer. Step 1: Go to this link. Fill in the details as per the requirements. For this application: Project: Maven Language: Java Spring Boot: 2.5.6 Packaging: JAR Java: 11 Dependencies: Spring Web,Spring Data JPA, MySql Driver Click on Generate which will download the starter project. Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Mapping and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows: Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name) spring.datasource.username=root spring.datasource.password=Aayush spring.datasource.url=jdbc:mysql://localhost:3306/mapping spring.jpa.hibernate.ddl-auto=update Step 4: Go to src->main->java->com->example->Mapping and create a file StudentInformation.java Project Structure: StudentInformation: Java @Entity@Table(name = "Student")public class StudentInformation { // Making roll number primary key @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int rollno; private String name; public int getRollno() { return rollno; } public StudentInformation() {} public StudentInformation(int rollno, String name) { this.rollno = rollno; this.name = name; } public void setRollno(int rollno) { this.rollno = rollno; } public String getName() { return name; } public void setName(String name) { this.name = name; }} Run the main application: Terminal Output: Database Output: Java-Spring-Data-JPA Java Java 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": 673, "s": 28, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernate. In this article, we will discuss how to make a specific variable of the class primary key in the Spring Application. @Id annotation is the JPA is used for making specific variable primary key." }, { "code": null, "e": 918, "s": 673, "text": "The @Id annotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of the current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation. " }, { "code": null, "e": 1292, "s": 918, "text": "Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer." }, { "code": null, "e": 1384, "s": 1292, "text": "Step 1: Go to this link. Fill in the details as per the requirements. For this application:" }, { "code": null, "e": 1512, "s": 1384, "text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.5.6\nPackaging: JAR\nJava: 11\nDependencies: Spring Web,Spring Data JPA, MySql Driver" }, { "code": null, "e": 1571, "s": 1512, "text": "Click on Generate which will download the starter project." }, { "code": null, "e": 1822, "s": 1571, "text": "Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Mapping and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:" }, { "code": null, "e": 1929, "s": 1822, "text": "Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name)" }, { "code": null, "e": 2090, "s": 1929, "text": "spring.datasource.username=root\nspring.datasource.password=Aayush\nspring.datasource.url=jdbc:mysql://localhost:3306/mapping\nspring.jpa.hibernate.ddl-auto=update" }, { "code": null, "e": 2185, "s": 2090, "text": "Step 4: Go to src->main->java->com->example->Mapping and create a file StudentInformation.java" }, { "code": null, "e": 2204, "s": 2185, "text": "Project Structure:" }, { "code": null, "e": 2224, "s": 2204, "text": "StudentInformation:" }, { "code": null, "e": 2229, "s": 2224, "text": "Java" }, { "code": "@Entity@Table(name = \"Student\")public class StudentInformation { // Making roll number primary key @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int rollno; private String name; public int getRollno() { return rollno; } public StudentInformation() {} public StudentInformation(int rollno, String name) { this.rollno = rollno; this.name = name; } public void setRollno(int rollno) { this.rollno = rollno; } public String getName() { return name; } public void setName(String name) { this.name = name; }}", "e": 2830, "s": 2229, "text": null }, { "code": null, "e": 2856, "s": 2830, "text": "Run the main application:" }, { "code": null, "e": 2873, "s": 2856, "text": "Terminal Output:" }, { "code": null, "e": 2890, "s": 2873, "text": "Database Output:" }, { "code": null, "e": 2911, "s": 2890, "text": "Java-Spring-Data-JPA" }, { "code": null, "e": 2916, "s": 2911, "text": "Java" }, { "code": null, "e": 2921, "s": 2916, "text": "Java" } ]
Convert an array to reduced form | Set 1 (Simple and Hashing)
30 Jun, 2022 Given an array with n distinct elements, convert the given array to a form where all elements are in the range from 0 to n-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is placed for the second smallest element, ... n-1 is placed for the largest element. Input: arr[] = {10, 40, 20} Output: arr[] = {0, 2, 1} Input: arr[] = {5, 10, 40, 30, 20} Output: arr[] = {0, 1, 4, 3, 2} The expected time complexity is O(n Log n). Method 1 (Simple): A simple solution is to first find the minimum element, replace it with 0, consider the remaining array and find the minimum in the remaining array and replace it with 1, and so on. The time complexity of this solution is O(n2) Method 2 (Efficient): Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. The idea is to use hashing and sorting. Below are the steps. Create a temp array and copy the contents of the given array to temp[]. This takes O(n) time. Sort temp[] in ascending order. This takes O(n Log n) time. Create an empty hash table. This takes O(1) time. Traverse temp[] from left to right and store mapping of numbers and their values (in converted array) in the hash table. This takes O(n) time on average. Traverse given array and change elements to their positions using a hash table. This takes O(n) time on average. Create a temp array and copy the contents of the given array to temp[]. This takes O(n) time. Sort temp[] in ascending order. This takes O(n Log n) time. Create an empty hash table. This takes O(1) time. Traverse temp[] from left to right and store mapping of numbers and their values (in converted array) in the hash table. This takes O(n) time on average. Traverse given array and change elements to their positions using a hash table. This takes O(n) time on average. Below are implementations of the above idea. C++ Java Python3 C# Javascript // C++ program to convert an array in reduced// form#include <bits/stdc++.h>using namespace std; void convert(int arr[], int n){ // Create a temp array and copy contents // of arr[] to temp int temp[n]; memcpy(temp, arr, n*sizeof(int)); // Sort temp array sort(temp, temp + n); // Create a hash table. Refer // http://tinyurl.com/zp5wgef unordered_map<int, int> umap; // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 int val = 0; for (int i = 0; i < n; i++) umap[temp[i]] = val++; // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap[arr[i]];} void printArr(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << " ";} // Driver program to test above methodint main(){ int arr[] = {10, 20, 15, 12, 11, 50}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Given Array is \n"; printArr(arr, n); convert(arr , n); cout << "\n\nConverted Array is \n"; printArr(arr, n); return 0;} // Java Program to convert an Array// to reduced formimport java.util.*; class GFG{ public static void convert(int arr[], int n) { // Create a temp array and copy contents // of arr[] to temp int temp[] = arr.clone(); // Sort temp array Arrays.sort(temp); // Create a hash table. HashMap<Integer, Integer> umap = new HashMap<>(); // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 int val = 0; for (int i = 0; i < n; i++) umap.put(temp[i], val++); // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap.get(arr[i]); } public static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Driver code public static void main(String[] args) { int arr[] = {10, 20, 15, 12, 11, 50}; int n = arr.length; System.out.println("Given Array is "); printArr(arr, n); convert(arr , n); System.out.println("\n\nConverted Array is "); printArr(arr, n); }} // This code is contributed by Abhishek Panwar # Python3 program to convert an array# in reduced formdef convert(arr, n): # Create a temp array and copy contents # of arr[] to temp temp = [arr[i] for i in range (n) ] # Sort temp array temp.sort() # create a map umap = {} # One by one insert elements of sorted # temp[] and assign them values from 0 # to n-1 val = 0 for i in range (n): umap[temp[i]] = val val += 1 # Convert array by taking positions from umap for i in range (n): arr[i] = umap[arr[i]] def printArr(arr, n): for i in range(n): print(arr[i], end = " ") # Driver Codeif __name__ == "__main__": arr = [10, 20, 15, 12, 11, 50] n = len(arr) print("Given Array is ") printArr(arr, n) convert(arr , n) print("\n\nConverted Array is ") printArr(arr, n) # This code is contributed by Abhishek Gupta // C# Program to convert an Array// to reduced formusing System;using System.Collections.Generic;using System.Linq; class GFG{ public static void convert(int []arr, int n) { // Create a temp array and copy contents // of []arr to temp int []temp = new int[arr.Length]; Array.Copy(arr, 0, temp, 0, arr.Length); // Sort temp array Array.Sort(temp); // Create a hash table. Dictionary<int, int> umap = new Dictionary<int, int>(); // One by one insert elements of sorted // []temp and assign them values from 0 // to n - 1 int val = 0; for (int i = 0; i < n; i++) if(umap.ContainsKey(temp[i])) umap[temp[i]] = val++; else umap.Add(temp[i], val++); // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap[arr[i]]; } public static void printArr(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Driver code public static void Main(String[] args) { int []arr = {10, 20, 15, 12, 11, 50}; int n = arr.Length; Console.WriteLine("Given Array is "); printArr(arr, n); convert(arr , n); Console.WriteLine("\n\nConverted Array is "); printArr(arr, n); }} // This code is contributed by PrinciRaj1992 <script> // Javascript Program to convert an Array// to reduced form function convert(arr, n) { // Create a temp array and copy contents // of arr[] to temp let temp = [...arr]; // Sort temp array temp.sort((a, b) => a - b); // Create a hash table. let umap = new Map(); // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 let val = 0; for (let i = 0; i < n; i++) umap.set(temp[i], val++); // Convert array by taking positions from // umap for (let i = 0; i < n; i++) arr[i] = umap.get(arr[i]); } function prletArr(arr, n) { for (let i = 0; i < n; i++) document.write(arr[i] + " "); } // Driver program let arr = [10, 20, 15, 12, 11, 50]; let n = arr.length; document.write("Given Array is " + "<br/>"); prletArr(arr, n); convert(arr , n); document.write("<br/>" + "Converted Array is " + "<br/>"); prletArr(arr, n); </script> Given Array is 10 20 15 12 11 50 Converted Array is 0 4 3 2 1 5 Time complexity: O(n)Auxiliary Space: O(n) Convert an array to reduced form | Set 2 (Using vector of pairs) This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. panwarabhishek345 ab_gupta princiraj1992 target_2 anandkumarshivam2266 hardikkoriintern Hash Sorting Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 358, "s": 52, "text": "Given an array with n distinct elements, convert the given array to a form where all elements are in the range from 0 to n-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is placed for the second smallest element, ... n-1 is placed for the largest element. " }, { "code": null, "e": 482, "s": 358, "text": "Input: arr[] = {10, 40, 20}\nOutput: arr[] = {0, 2, 1}\n\nInput: arr[] = {5, 10, 40, 30, 20}\nOutput: arr[] = {0, 1, 4, 3, 2}" }, { "code": null, "e": 526, "s": 482, "text": "The expected time complexity is O(n Log n)." }, { "code": null, "e": 545, "s": 526, "text": "Method 1 (Simple):" }, { "code": null, "e": 773, "s": 545, "text": "A simple solution is to first find the minimum element, replace it with 0, consider the remaining array and find the minimum in the remaining array and replace it with 1, and so on. The time complexity of this solution is O(n2)" }, { "code": null, "e": 795, "s": 773, "text": "Method 2 (Efficient):" }, { "code": null, "e": 804, "s": 795, "text": "Chapters" }, { "code": null, "e": 831, "s": 804, "text": "descriptions off, selected" }, { "code": null, "e": 881, "s": 831, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 904, "s": 881, "text": "captions off, selected" }, { "code": null, "e": 912, "s": 904, "text": "English" }, { "code": null, "e": 936, "s": 912, "text": "This is a modal window." }, { "code": null, "e": 1005, "s": 936, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1027, "s": 1005, "text": "End of dialog window." }, { "code": null, "e": 1089, "s": 1027, "text": "The idea is to use hashing and sorting. Below are the steps. " }, { "code": null, "e": 1560, "s": 1089, "text": "Create a temp array and copy the contents of the given array to temp[]. This takes O(n) time. Sort temp[] in ascending order. This takes O(n Log n) time. Create an empty hash table. This takes O(1) time. Traverse temp[] from left to right and store mapping of numbers and their values (in converted array) in the hash table. This takes O(n) time on average. Traverse given array and change elements to their positions using a hash table. This takes O(n) time on average." }, { "code": null, "e": 1655, "s": 1560, "text": "Create a temp array and copy the contents of the given array to temp[]. This takes O(n) time. " }, { "code": null, "e": 1716, "s": 1655, "text": "Sort temp[] in ascending order. This takes O(n Log n) time. " }, { "code": null, "e": 1767, "s": 1716, "text": "Create an empty hash table. This takes O(1) time. " }, { "code": null, "e": 1922, "s": 1767, "text": "Traverse temp[] from left to right and store mapping of numbers and their values (in converted array) in the hash table. This takes O(n) time on average. " }, { "code": null, "e": 2035, "s": 1922, "text": "Traverse given array and change elements to their positions using a hash table. This takes O(n) time on average." }, { "code": null, "e": 2081, "s": 2035, "text": "Below are implementations of the above idea. " }, { "code": null, "e": 2085, "s": 2081, "text": "C++" }, { "code": null, "e": 2090, "s": 2085, "text": "Java" }, { "code": null, "e": 2098, "s": 2090, "text": "Python3" }, { "code": null, "e": 2101, "s": 2098, "text": "C#" }, { "code": null, "e": 2112, "s": 2101, "text": "Javascript" }, { "code": "// C++ program to convert an array in reduced// form#include <bits/stdc++.h>using namespace std; void convert(int arr[], int n){ // Create a temp array and copy contents // of arr[] to temp int temp[n]; memcpy(temp, arr, n*sizeof(int)); // Sort temp array sort(temp, temp + n); // Create a hash table. Refer // http://tinyurl.com/zp5wgef unordered_map<int, int> umap; // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 int val = 0; for (int i = 0; i < n; i++) umap[temp[i]] = val++; // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap[arr[i]];} void printArr(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << \" \";} // Driver program to test above methodint main(){ int arr[] = {10, 20, 15, 12, 11, 50}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Given Array is \\n\"; printArr(arr, n); convert(arr , n); cout << \"\\n\\nConverted Array is \\n\"; printArr(arr, n); return 0;}", "e": 3179, "s": 2112, "text": null }, { "code": "// Java Program to convert an Array// to reduced formimport java.util.*; class GFG{ public static void convert(int arr[], int n) { // Create a temp array and copy contents // of arr[] to temp int temp[] = arr.clone(); // Sort temp array Arrays.sort(temp); // Create a hash table. HashMap<Integer, Integer> umap = new HashMap<>(); // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 int val = 0; for (int i = 0; i < n; i++) umap.put(temp[i], val++); // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap.get(arr[i]); } public static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); } // Driver code public static void main(String[] args) { int arr[] = {10, 20, 15, 12, 11, 50}; int n = arr.length; System.out.println(\"Given Array is \"); printArr(arr, n); convert(arr , n); System.out.println(\"\\n\\nConverted Array is \"); printArr(arr, n); }} // This code is contributed by Abhishek Panwar", "e": 4422, "s": 3179, "text": null }, { "code": "# Python3 program to convert an array# in reduced formdef convert(arr, n): # Create a temp array and copy contents # of arr[] to temp temp = [arr[i] for i in range (n) ] # Sort temp array temp.sort() # create a map umap = {} # One by one insert elements of sorted # temp[] and assign them values from 0 # to n-1 val = 0 for i in range (n): umap[temp[i]] = val val += 1 # Convert array by taking positions from umap for i in range (n): arr[i] = umap[arr[i]] def printArr(arr, n): for i in range(n): print(arr[i], end = \" \") # Driver Codeif __name__ == \"__main__\": arr = [10, 20, 15, 12, 11, 50] n = len(arr) print(\"Given Array is \") printArr(arr, n) convert(arr , n) print(\"\\n\\nConverted Array is \") printArr(arr, n) # This code is contributed by Abhishek Gupta", "e": 5306, "s": 4422, "text": null }, { "code": "// C# Program to convert an Array// to reduced formusing System;using System.Collections.Generic;using System.Linq; class GFG{ public static void convert(int []arr, int n) { // Create a temp array and copy contents // of []arr to temp int []temp = new int[arr.Length]; Array.Copy(arr, 0, temp, 0, arr.Length); // Sort temp array Array.Sort(temp); // Create a hash table. Dictionary<int, int> umap = new Dictionary<int, int>(); // One by one insert elements of sorted // []temp and assign them values from 0 // to n - 1 int val = 0; for (int i = 0; i < n; i++) if(umap.ContainsKey(temp[i])) umap[temp[i]] = val++; else umap.Add(temp[i], val++); // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap[arr[i]]; } public static void printArr(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Driver code public static void Main(String[] args) { int []arr = {10, 20, 15, 12, 11, 50}; int n = arr.Length; Console.WriteLine(\"Given Array is \"); printArr(arr, n); convert(arr , n); Console.WriteLine(\"\\n\\nConverted Array is \"); printArr(arr, n); }} // This code is contributed by PrinciRaj1992", "e": 6753, "s": 5306, "text": null }, { "code": "<script> // Javascript Program to convert an Array// to reduced form function convert(arr, n) { // Create a temp array and copy contents // of arr[] to temp let temp = [...arr]; // Sort temp array temp.sort((a, b) => a - b); // Create a hash table. let umap = new Map(); // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 let val = 0; for (let i = 0; i < n; i++) umap.set(temp[i], val++); // Convert array by taking positions from // umap for (let i = 0; i < n; i++) arr[i] = umap.get(arr[i]); } function prletArr(arr, n) { for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); } // Driver program let arr = [10, 20, 15, 12, 11, 50]; let n = arr.length; document.write(\"Given Array is \" + \"<br/>\"); prletArr(arr, n); convert(arr , n); document.write(\"<br/>\" + \"Converted Array is \" + \"<br/>\"); prletArr(arr, n); </script>", "e": 7864, "s": 6753, "text": null }, { "code": null, "e": 7933, "s": 7864, "text": "Given Array is \n10 20 15 12 11 50 \n\nConverted Array is \n0 4 3 2 1 5 " }, { "code": null, "e": 7976, "s": 7933, "text": "Time complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 8041, "s": 7976, "text": "Convert an array to reduced form | Set 2 (Using vector of pairs)" }, { "code": null, "e": 8212, "s": 8041, "text": "This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8230, "s": 8212, "text": "panwarabhishek345" }, { "code": null, "e": 8239, "s": 8230, "text": "ab_gupta" }, { "code": null, "e": 8253, "s": 8239, "text": "princiraj1992" }, { "code": null, "e": 8262, "s": 8253, "text": "target_2" }, { "code": null, "e": 8283, "s": 8262, "text": "anandkumarshivam2266" }, { "code": null, "e": 8300, "s": 8283, "text": "hardikkoriintern" }, { "code": null, "e": 8305, "s": 8300, "text": "Hash" }, { "code": null, "e": 8313, "s": 8305, "text": "Sorting" }, { "code": null, "e": 8318, "s": 8313, "text": "Hash" }, { "code": null, "e": 8326, "s": 8318, "text": "Sorting" } ]
Quoting Mechanisms in Linux
25 Jun, 2021 In Linux Shell, many special characters have their own special meanings. Sometimes they are used to perform an action while other times they are just used as a character, so the quoting mechanism performs this task it makes us use them in whatever way we want to. Metacharacters: These are the special characters that are first interpreted by the shell before passing the same to the command. They are also known as shell wildcards. $ Variable Substitution or expand the value of Variable. > used for Output Redirection. >> used for Output Redirection to append. < Input redirection. << used for input redirection and is also known as here document. * Match any number of characters, Substitution wildcard for zero or more characters ? Match one character, Substitution wildcard for 1 character [] Match range of characters, Substitution wildcard for any character between brackets `cmd` Replace cmd with the command to execute and will execute that, Substitution wildcard for command execution $(cmd) Replace cmd with the command to execute and will execute that, Substitution wildcard for command execution | Pipe is a Redirection to send the output of one command/program/process to another command/program/process for further processing. ; Command separator is used to execute 2 or more commands with one statement. || OR conditional execution of the commands. && AND conditional execution of the commands. () Groups the command in to one output stream. & executes command in the background and will display the assigned Pid. # to comment something. $ To expand the value of a variable. \ used to escape the interpretation of a character or to prevent that. A Backslash(‘\’) is the bash escape character. Any character immediately following the backslash loses its special meaning and any letter following the backslash gains its special meaning. Enter the following commands in the terminal. echo "Quotation" echo \"Quotation\" As it can be seen with the example that double could be not printed without backslash and with backslash as they lost their special meaning, so they were printed. The Backslash Escaped Characters \a alert (bell) \b backspace \e an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \’ single quote \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \cx a control-x character Single Quotes(”) are used to preserve the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. All special characters within the single quotes lose their special meanings. Some strings have a lot of special characters so it is hard to use a backslash before every special character. Hence, if we will put the same string within single quotes, most of the special characters will lose their special meanings. Enter the following commands in the terminal. echo \<Welcome\>\<to\>\<geeksforgeeks\> echo '<Welcome><to><geeksforgeeks>' You can be seen from the example that we had to use a lot of backslash in the first statement which made it complex. While with single quotes output was same without using backslash Double Quotes(“”) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and when history expansion is enabled, ‘!’. The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘`’, ‘”’, ‘\’, or newline. Enter the following commands in the terminal. name=geeksforgeeks echo '$name' echo "$name" You can be seen that in the case of single quotes the value of the variable was not printed while in the case of double quotes the value of the variable was printed. Back Quotes(“) are used to execute a command. Anything enclosed between them will be treated as a command and would be executed. Open the terminal and execute the following commands. hostname=`hostname` echo $hostname You can be seen from the example the hostname command gets executed and the name gets stored in the variable. as5853535 Linux-Unix Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Jun, 2021" }, { "code": null, "e": 317, "s": 52, "text": "In Linux Shell, many special characters have their own special meanings. Sometimes they are used to perform an action while other times they are just used as a character, so the quoting mechanism performs this task it makes us use them in whatever way we want to. " }, { "code": null, "e": 487, "s": 317, "text": "Metacharacters: These are the special characters that are first interpreted by the shell before passing the same to the command. They are also known as shell wildcards. " }, { "code": null, "e": 546, "s": 489, "text": "$ Variable Substitution or expand the value of Variable." }, { "code": null, "e": 577, "s": 546, "text": "> used for Output Redirection." }, { "code": null, "e": 619, "s": 577, "text": ">> used for Output Redirection to append." }, { "code": null, "e": 640, "s": 619, "text": "< Input redirection." }, { "code": null, "e": 706, "s": 640, "text": "<< used for input redirection and is also known as here document." }, { "code": null, "e": 790, "s": 706, "text": "* Match any number of characters, Substitution wildcard for zero or more characters" }, { "code": null, "e": 851, "s": 790, "text": "? Match one character, Substitution wildcard for 1 character" }, { "code": null, "e": 938, "s": 851, "text": "[] Match range of characters, Substitution wildcard for any character between brackets" }, { "code": null, "e": 1051, "s": 938, "text": "`cmd` Replace cmd with the command to execute and will execute that, Substitution wildcard for command execution" }, { "code": null, "e": 1165, "s": 1051, "text": "$(cmd) Replace cmd with the command to execute and will execute that, Substitution wildcard for command execution" }, { "code": null, "e": 1298, "s": 1165, "text": "| Pipe is a Redirection to send the output of one command/program/process to another command/program/process for further processing." }, { "code": null, "e": 1376, "s": 1298, "text": "; Command separator is used to execute 2 or more commands with one statement." }, { "code": null, "e": 1421, "s": 1376, "text": "|| OR conditional execution of the commands." }, { "code": null, "e": 1467, "s": 1421, "text": "&& AND conditional execution of the commands." }, { "code": null, "e": 1514, "s": 1467, "text": "() Groups the command in to one output stream." }, { "code": null, "e": 1586, "s": 1514, "text": "& executes command in the background and will display the assigned Pid." }, { "code": null, "e": 1610, "s": 1586, "text": "# to comment something." }, { "code": null, "e": 1647, "s": 1610, "text": "$ To expand the value of a variable." }, { "code": null, "e": 1718, "s": 1647, "text": "\\ used to escape the interpretation of a character or to prevent that." }, { "code": null, "e": 1956, "s": 1720, "text": "A Backslash(‘\\’) is the bash escape character. Any character immediately following the backslash loses its special meaning and any letter following the backslash gains its special meaning. Enter the following commands in the terminal. " }, { "code": null, "e": 1994, "s": 1958, "text": "echo \"Quotation\"\necho \\\"Quotation\\\"" }, { "code": null, "e": 2158, "s": 1994, "text": "As it can be seen with the example that double could be not printed without backslash and with backslash as they lost their special meaning, so they were printed. " }, { "code": null, "e": 2195, "s": 2160, "text": "The Backslash Escaped Characters " }, { "code": null, "e": 2561, "s": 2195, "text": "\\a alert (bell) \\b backspace \\e an escape character \\f form feed \\n new line \\r carriage return \\t horizontal tab \\v vertical tab \\\\ backslash \\’ single quote \\nnn the eight-bit character whose value is the octal value nnn (one to three digits) \\xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \\cx a control-x character " }, { "code": null, "e": 3103, "s": 2563, "text": "Single Quotes(”) are used to preserve the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. All special characters within the single quotes lose their special meanings. Some strings have a lot of special characters so it is hard to use a backslash before every special character. Hence, if we will put the same string within single quotes, most of the special characters will lose their special meanings. Enter the following commands in the terminal. " }, { "code": null, "e": 3181, "s": 3105, "text": "echo \\<Welcome\\>\\<to\\>\\<geeksforgeeks\\>\necho '<Welcome><to><geeksforgeeks>'" }, { "code": null, "e": 3364, "s": 3181, "text": "You can be seen from the example that we had to use a lot of backslash in the first statement which made it complex. While with single quotes output was same without using backslash " }, { "code": null, "e": 3708, "s": 3368, "text": "Double Quotes(“”) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\\’, and when history expansion is enabled, ‘!’. The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘`’, ‘”’, ‘\\’, or newline. Enter the following commands in the terminal. " }, { "code": null, "e": 3755, "s": 3710, "text": "name=geeksforgeeks\necho '$name'\necho \"$name\"" }, { "code": null, "e": 3922, "s": 3755, "text": "You can be seen that in the case of single quotes the value of the variable was not printed while in the case of double quotes the value of the variable was printed. " }, { "code": null, "e": 4110, "s": 3926, "text": "Back Quotes(“) are used to execute a command. Anything enclosed between them will be treated as a command and would be executed. Open the terminal and execute the following commands. " }, { "code": null, "e": 4147, "s": 4112, "text": "hostname=`hostname`\necho $hostname" }, { "code": null, "e": 4258, "s": 4147, "text": "You can be seen from the example the hostname command gets executed and the name gets stored in the variable. " }, { "code": null, "e": 4272, "s": 4262, "text": "as5853535" }, { "code": null, "e": 4283, "s": 4272, "text": "Linux-Unix" }, { "code": null, "e": 4299, "s": 4283, "text": "Write From Home" } ]
Morris traversal for Preorder
29 Sep, 2021 Using Morris Traversal, we can traverse the tree without using stack and recursion. The algorithm for Preorder is almost similar to Morris traversal for Inorder. 1...If left child is null, print the current node data. Move to right child. ....Else, Make the right child of the inorder predecessor point to the current node. Two cases arise: .........a) The right child of the inorder predecessor already points to the current node. Set right child to NULL. Move to right child of current node. .........b) The right child is NULL. Set it to current node. Print current node’s data and move to left child of current node. 2...Iterate until current node is not NULL. Following is the implementation of the above algorithm. C++ C Java Python3 C# Javascript // C++ program for Morris Preorder traversal#include <bits/stdc++.h>using namespace std; class node{ public: int data; node *left, *right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Preorder traversal without recursion and without stackvoid morrisTraversalPreorder(node* root){ while (root) { // If left child is null, print the current node data. Move to // right child. if (root->left == NULL) { cout<<root->data<<" "; root = root->right; } else { // Find inorder predecessor node* current = root->left; while (current->right && current->right != root) current = current->right; // If the right child of inorder predecessor already points to // this node if (current->right == root) { current->right = NULL; root = root->right; } // If right child doesn't point to this node, then print this // node and make right child point to this node else { cout<<root->data<<" "; current->right = root; root = root->left; } } }} // Function for Standard preorder traversalvoid preorder(node* root){ if (root) { cout<<root->data<<" "; preorder(root->left); preorder(root->right); }} /* Driver program to test above functions*/int main(){ node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); morrisTraversalPreorder(root); cout<<endl; preorder(root); return 0;} //This code is contributed by rathbhupendra // C program for Morris Preorder traversal#include <stdio.h>#include <stdlib.h> struct node{ int data; struct node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* temp = (struct node*) malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // Preorder traversal without recursion and without stackvoid morrisTraversalPreorder(struct node* root){ while (root) { // If left child is null, print the current node data. Move to // right child. if (root->left == NULL) { printf( "%d ", root->data ); root = root->right; } else { // Find inorder predecessor struct node* current = root->left; while (current->right && current->right != root) current = current->right; // If the right child of inorder predecessor already points to // this node if (current->right == root) { current->right = NULL; root = root->right; } // If right child doesn't point to this node, then print this // node and make right child point to this node else { printf("%d ", root->data); current->right = root; root = root->left; } } }} // Function for Standard preorder traversalvoid preorder(struct node* root){ if (root) { printf( "%d ", root->data); preorder(root->left); preorder(root->right); }} /* Driver program to test above functions*/int main(){ struct node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); morrisTraversalPreorder(root); printf("\n"); preorder(root); return 0;} // Java program to implement Morris preorder traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; void morrisTraversalPreorder() { morrisTraversalPreorder(root); } // Preorder traversal without recursion and without stack void morrisTraversalPreorder(Node node) { while (node != null) { // If left child is null, print the current node data. Move to // right child. if (node.left == null) { System.out.print(node.data + " "); node = node.right; } else { // Find inorder predecessor Node current = node.left; while (current.right != null && current.right != node) { current = current.right; } // If the right child of inorder predecessor // already points to this node if (current.right == node) { current.right = null; node = node.right; } // If right child doesn't point to this node, then print // this node and make right child point to this node else { System.out.print(node.data + " "); current.right = node; node = node.left; } } } } void preorder() { preorder(root); } // Function for Standard preorder traversal void preorder(Node node) { if (node != null) { System.out.print(node.data + " "); preorder(node.left); preorder(node.right); } } // Driver programs to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.morrisTraversalPreorder(); System.out.println(""); tree.preorder(); }} // this code has been contributed by Mayank Jaiswal # Python program for Morris Preorder traversal # A binary tree Nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Preorder traversal without# recursion and without stackdef MorrisTraversal(root): curr = root while curr: # If left child is null, print the # current node data. And, update # the current pointer to right child. if curr.left is None: print(curr.data, end= " ") curr = curr.right else: # Find the inorder predecessor prev = curr.left while prev.right is not None and prev.right is not curr: prev = prev.right # If the right child of inorder # predecessor already points to # the current node, update the # current with it's right child if prev.right is curr: prev.right = None curr = curr.right # else If right child doesn't point # to the current node, then print this # node's data and update the right child # pointer with the current node and update # the current with it's left child else: print (curr.data, end=" ") prev.right = curr curr = curr.left # Function for Standard preorder traversaldef preorfer(root): if root : print(root.data, end = " ") preorfer(root.left) preorfer(root.right) # Driver program to testroot = Node(1)root.left = Node(2)root.right = Node(3) root.left.left = Node(4)root.left.right = Node(5) root.right.left= Node(6)root.right.right = Node(7) root.left.left.left = Node(8)root.left.left.right = Node(9) root.left.right.left = Node(10)root.left.right.right = Node(11) MorrisTraversal(root)print("\n")preorfer(root) # This code is contributed by 'Aartee' // C# program to implement Morris// preorder traversalusing System; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; public virtual void morrisTraversalPreorder(){ morrisTraversalPreorder(root);} // Preorder traversal without// recursion and without stackpublic virtual void morrisTraversalPreorder(Node node){ while (node != null) { // If left child is null, print the // current node data. Move to right child. if (node.left == null) { Console.Write(node.data + " "); node = node.right; } else { // Find inorder predecessor Node current = node.left; while (current.right != null && current.right != node) { current = current.right; } // If the right child of inorder predecessor // already points to this node if (current.right == node) { current.right = null; node = node.right; } // If right child doesn't point to // this node, then print this node // and make right child point to this node else { Console.Write(node.data + " "); current.right = node; node = node.left; } } }} public virtual void preorder(){ preorder(root);} // Function for Standard preorder traversalpublic virtual void preorder(Node node){ if (node != null) { Console.Write(node.data + " "); preorder(node.left); preorder(node.right); }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.morrisTraversalPreorder(); Console.WriteLine(""); tree.preorder();}} // This code is contributed by Shrikant13 <script> // Javascript program to implement Morris// preorder traversal // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root = null; // Preorder traversal without// recursion and without stackfunction morrisTraversalPreorder(node){ while (node != null) { // If left child is null, print the // current node data. Move to right child. if (node.left == null) { document.write(node.data + " "); node = node.right; } else { // Find inorder predecessor var current = node.left; while (current.right != null && current.right != node) { current = current.right; } // If the right child of inorder predecessor // already points to this node if (current.right == node) { current.right = null; node = node.right; } // If right child doesn't point to // this node, then print this node // and make right child point to this node else { document.write(node.data + " "); current.right = node; node = node.left; } } }} // Function for Standard preorder traversalfunction preorder(node){ if (node != null) { document.write(node.data + " "); preorder(node.left); preorder(node.right); }} // Driver Coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);morrisTraversalPreorder(root);document.write("<br>");preorder(root); </script> Output: 1 2 4 8 9 5 10 11 3 6 7 1 2 4 8 9 5 10 11 3 6 7 Limitations: Morris traversal modifies the tree during the process. It establishes the right links while moving down the tree and resets the right links while moving up the tree. So the algorithm cannot be applied if write operations are not allowed. Morris traversal for Preorder | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMorris traversal for Preorder | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fLwUTc0kQHI" 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 compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 rathbhupendra rutvik_56 surindertarika1234 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Introduction to Data Structures What is Data Structure: Types, Classifications and Applications A program to check if a binary tree is BST or not Decision Tree Top 50 Tree Coding Problems for Interviews Segment Tree | Set 1 (Sum of given range) Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Lowest Common Ancestor in a Binary Search Tree.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Sep, 2021" }, { "code": null, "e": 214, "s": 52, "text": "Using Morris Traversal, we can traverse the tree without using stack and recursion. The algorithm for Preorder is almost similar to Morris traversal for Inorder." }, { "code": null, "e": 717, "s": 214, "text": "1...If left child is null, print the current node data. Move to right child. ....Else, Make the right child of the inorder predecessor point to the current node. Two cases arise: .........a) The right child of the inorder predecessor already points to the current node. Set right child to NULL. Move to right child of current node. .........b) The right child is NULL. Set it to current node. Print current node’s data and move to left child of current node. 2...Iterate until current node is not NULL." }, { "code": null, "e": 774, "s": 717, "text": "Following is the implementation of the above algorithm. " }, { "code": null, "e": 778, "s": 774, "text": "C++" }, { "code": null, "e": 780, "s": 778, "text": "C" }, { "code": null, "e": 785, "s": 780, "text": "Java" }, { "code": null, "e": 793, "s": 785, "text": "Python3" }, { "code": null, "e": 796, "s": 793, "text": "C#" }, { "code": null, "e": 807, "s": 796, "text": "Javascript" }, { "code": "// C++ program for Morris Preorder traversal#include <bits/stdc++.h>using namespace std; class node{ public: int data; node *left, *right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Preorder traversal without recursion and without stackvoid morrisTraversalPreorder(node* root){ while (root) { // If left child is null, print the current node data. Move to // right child. if (root->left == NULL) { cout<<root->data<<\" \"; root = root->right; } else { // Find inorder predecessor node* current = root->left; while (current->right && current->right != root) current = current->right; // If the right child of inorder predecessor already points to // this node if (current->right == root) { current->right = NULL; root = root->right; } // If right child doesn't point to this node, then print this // node and make right child point to this node else { cout<<root->data<<\" \"; current->right = root; root = root->left; } } }} // Function for Standard preorder traversalvoid preorder(node* root){ if (root) { cout<<root->data<<\" \"; preorder(root->left); preorder(root->right); }} /* Driver program to test above functions*/int main(){ node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); morrisTraversalPreorder(root); cout<<endl; preorder(root); return 0;} //This code is contributed by rathbhupendra", "e": 3028, "s": 807, "text": null }, { "code": "// C program for Morris Preorder traversal#include <stdio.h>#include <stdlib.h> struct node{ int data; struct node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* temp = (struct node*) malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp;} // Preorder traversal without recursion and without stackvoid morrisTraversalPreorder(struct node* root){ while (root) { // If left child is null, print the current node data. Move to // right child. if (root->left == NULL) { printf( \"%d \", root->data ); root = root->right; } else { // Find inorder predecessor struct node* current = root->left; while (current->right && current->right != root) current = current->right; // If the right child of inorder predecessor already points to // this node if (current->right == root) { current->right = NULL; root = root->right; } // If right child doesn't point to this node, then print this // node and make right child point to this node else { printf(\"%d \", root->data); current->right = root; root = root->left; } } }} // Function for Standard preorder traversalvoid preorder(struct node* root){ if (root) { printf( \"%d \", root->data); preorder(root->left); preorder(root->right); }} /* Driver program to test above functions*/int main(){ struct node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); morrisTraversalPreorder(root); printf(\"\\n\"); preorder(root); return 0;}", "e": 5287, "s": 3028, "text": null }, { "code": "// Java program to implement Morris preorder traversal // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; void morrisTraversalPreorder() { morrisTraversalPreorder(root); } // Preorder traversal without recursion and without stack void morrisTraversalPreorder(Node node) { while (node != null) { // If left child is null, print the current node data. Move to // right child. if (node.left == null) { System.out.print(node.data + \" \"); node = node.right; } else { // Find inorder predecessor Node current = node.left; while (current.right != null && current.right != node) { current = current.right; } // If the right child of inorder predecessor // already points to this node if (current.right == node) { current.right = null; node = node.right; } // If right child doesn't point to this node, then print // this node and make right child point to this node else { System.out.print(node.data + \" \"); current.right = node; node = node.left; } } } } void preorder() { preorder(root); } // Function for Standard preorder traversal void preorder(Node node) { if (node != null) { System.out.print(node.data + \" \"); preorder(node.left); preorder(node.right); } } // Driver programs to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.morrisTraversalPreorder(); System.out.println(\"\"); tree.preorder(); }} // this code has been contributed by Mayank Jaiswal", "e": 7862, "s": 5287, "text": null }, { "code": "# Python program for Morris Preorder traversal # A binary tree Nodeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Preorder traversal without# recursion and without stackdef MorrisTraversal(root): curr = root while curr: # If left child is null, print the # current node data. And, update # the current pointer to right child. if curr.left is None: print(curr.data, end= \" \") curr = curr.right else: # Find the inorder predecessor prev = curr.left while prev.right is not None and prev.right is not curr: prev = prev.right # If the right child of inorder # predecessor already points to # the current node, update the # current with it's right child if prev.right is curr: prev.right = None curr = curr.right # else If right child doesn't point # to the current node, then print this # node's data and update the right child # pointer with the current node and update # the current with it's left child else: print (curr.data, end=\" \") prev.right = curr curr = curr.left # Function for Standard preorder traversaldef preorfer(root): if root : print(root.data, end = \" \") preorfer(root.left) preorfer(root.right) # Driver program to testroot = Node(1)root.left = Node(2)root.right = Node(3) root.left.left = Node(4)root.left.right = Node(5) root.right.left= Node(6)root.right.right = Node(7) root.left.left.left = Node(8)root.left.left.right = Node(9) root.left.right.left = Node(10)root.left.right.right = Node(11) MorrisTraversal(root)print(\"\\n\")preorfer(root) # This code is contributed by 'Aartee'", "e": 9794, "s": 7862, "text": null }, { "code": "// C# program to implement Morris// preorder traversalusing System; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; public virtual void morrisTraversalPreorder(){ morrisTraversalPreorder(root);} // Preorder traversal without// recursion and without stackpublic virtual void morrisTraversalPreorder(Node node){ while (node != null) { // If left child is null, print the // current node data. Move to right child. if (node.left == null) { Console.Write(node.data + \" \"); node = node.right; } else { // Find inorder predecessor Node current = node.left; while (current.right != null && current.right != node) { current = current.right; } // If the right child of inorder predecessor // already points to this node if (current.right == node) { current.right = null; node = node.right; } // If right child doesn't point to // this node, then print this node // and make right child point to this node else { Console.Write(node.data + \" \"); current.right = node; node = node.left; } } }} public virtual void preorder(){ preorder(root);} // Function for Standard preorder traversalpublic virtual void preorder(Node node){ if (node != null) { Console.Write(node.data + \" \"); preorder(node.left); preorder(node.right); }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); tree.morrisTraversalPreorder(); Console.WriteLine(\"\"); tree.preorder();}} // This code is contributed by Shrikant13", "e": 12204, "s": 9794, "text": null }, { "code": "<script> // Javascript program to implement Morris// preorder traversal // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} var root = null; // Preorder traversal without// recursion and without stackfunction morrisTraversalPreorder(node){ while (node != null) { // If left child is null, print the // current node data. Move to right child. if (node.left == null) { document.write(node.data + \" \"); node = node.right; } else { // Find inorder predecessor var current = node.left; while (current.right != null && current.right != node) { current = current.right; } // If the right child of inorder predecessor // already points to this node if (current.right == node) { current.right = null; node = node.right; } // If right child doesn't point to // this node, then print this node // and make right child point to this node else { document.write(node.data + \" \"); current.right = node; node = node.left; } } }} // Function for Standard preorder traversalfunction preorder(node){ if (node != null) { document.write(node.data + \" \"); preorder(node.left); preorder(node.right); }} // Driver Coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);morrisTraversalPreorder(root);document.write(\"<br>\");preorder(root); </script>", "e": 14187, "s": 12204, "text": null }, { "code": null, "e": 14196, "s": 14187, "text": "Output: " }, { "code": null, "e": 14244, "s": 14196, "text": "1 2 4 8 9 5 10 11 3 6 7\n1 2 4 8 9 5 10 11 3 6 7" }, { "code": null, "e": 14495, "s": 14244, "text": "Limitations: Morris traversal modifies the tree during the process. It establishes the right links while moving down the tree and resets the right links while moving up the tree. So the algorithm cannot be applied if write operations are not allowed." }, { "code": null, "e": 15371, "s": 14495, "text": "Morris traversal for Preorder | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersMorris traversal for Preorder | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fLwUTc0kQHI\" 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": 15577, "s": 15371, "text": "This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 15589, "s": 15577, "text": "shrikanth13" }, { "code": null, "e": 15603, "s": 15589, "text": "rathbhupendra" }, { "code": null, "e": 15613, "s": 15603, "text": "rutvik_56" }, { "code": null, "e": 15632, "s": 15613, "text": "surindertarika1234" }, { "code": null, "e": 15637, "s": 15632, "text": "Tree" }, { "code": null, "e": 15642, "s": 15637, "text": "Tree" }, { "code": null, "e": 15740, "s": 15642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15769, "s": 15740, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 15801, "s": 15769, "text": "Introduction to Data Structures" }, { "code": null, "e": 15865, "s": 15801, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15915, "s": 15865, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 15929, "s": 15915, "text": "Decision Tree" }, { "code": null, "e": 15972, "s": 15929, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 16014, "s": 15972, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 16084, "s": 16014, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 16167, "s": 16084, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" } ]
How to use Greek symbols in ggplot2? - GeeksforGeeks
06 Jun, 2021 In this article, we will be looking at the approach to use Greeks symbols in ggplot2 using some in-built functions in the R programming language. Greeks Symbols are used in mathematics, science, engineering, and other areas where the mathematical notation is used as symbols for constants, special functions, and also conventionally for variables representing certain quantities. In these contexts, the capital letters and the small letters represent distinct and unrelated entities. In this method to use Greeks symbols in ggplot2 user need to call the expression function which is a base function of the R programming language, and pass the name of the Greek symbols to be used as the parameters to this function to get a Greek symbol to the ggplot2. expression() function in R Language is used to create an expression from the values passed as an argument. It creates an object of the expression class. Syntax: expression(character) Parameter: character: Expression, like calls, symbols, constants Example: R library("ggplot2") gfg_data<-data.frame(x=c(1,2,3,4,5),y=c(5,4,3,2,1)) gfg_plot<-ggplot(data=gfg_data, aes(x, y)) + geom_bar(stat="identity") gfg_plot + ggtitle(expression(~ alpha * beta*gamma*delta*zeta*tau*phi*xi)) Output: The approach is the same as above, here also expression() method is used but to add symbols to the main plot annotate() function is used. Syntax: annotate() Parameters: geom : specify text x : x axis location y : y axis location label : custom textual content color : color of textual content size : size of text fontface : fontface of text angle : angle of text Example: R library("ggplot2") gfg_data<-data.frame(x=c(1,2,3,4,5),y=c(5,4,3,2,1)) gfg_plot<-ggplot(data=gfg_data, aes(x, y)) + geom_bar(stat="identity") gfg_plot + annotate("text", x = 4, y = 4, label = expression( ~ alpha * beta*delta*zeta*tau*phi)) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Logistic Regression in R Programming How to change the order of bars in bar chart in R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Data Visualization in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25308, "s": 25162, "text": "In this article, we will be looking at the approach to use Greeks symbols in ggplot2 using some in-built functions in the R programming language." }, { "code": null, "e": 25646, "s": 25308, "text": "Greeks Symbols are used in mathematics, science, engineering, and other areas where the mathematical notation is used as symbols for constants, special functions, and also conventionally for variables representing certain quantities. In these contexts, the capital letters and the small letters represent distinct and unrelated entities." }, { "code": null, "e": 25915, "s": 25646, "text": "In this method to use Greeks symbols in ggplot2 user need to call the expression function which is a base function of the R programming language, and pass the name of the Greek symbols to be used as the parameters to this function to get a Greek symbol to the ggplot2." }, { "code": null, "e": 26068, "s": 25915, "text": "expression() function in R Language is used to create an expression from the values passed as an argument. It creates an object of the expression class." }, { "code": null, "e": 26076, "s": 26068, "text": "Syntax:" }, { "code": null, "e": 26098, "s": 26076, "text": "expression(character)" }, { "code": null, "e": 26109, "s": 26098, "text": "Parameter:" }, { "code": null, "e": 26163, "s": 26109, "text": "character: Expression, like calls, symbols, constants" }, { "code": null, "e": 26172, "s": 26163, "text": "Example:" }, { "code": null, "e": 26174, "s": 26172, "text": "R" }, { "code": "library(\"ggplot2\") gfg_data<-data.frame(x=c(1,2,3,4,5),y=c(5,4,3,2,1)) gfg_plot<-ggplot(data=gfg_data, aes(x, y)) + geom_bar(stat=\"identity\") gfg_plot + ggtitle(expression(~ alpha * beta*gamma*delta*zeta*tau*phi*xi))", "e": 26400, "s": 26174, "text": null }, { "code": null, "e": 26408, "s": 26400, "text": "Output:" }, { "code": null, "e": 26546, "s": 26408, "text": "The approach is the same as above, here also expression() method is used but to add symbols to the main plot annotate() function is used." }, { "code": null, "e": 26566, "s": 26546, "text": "Syntax: annotate() " }, { "code": null, "e": 26578, "s": 26566, "text": "Parameters:" }, { "code": null, "e": 26598, "s": 26578, "text": "geom : specify text" }, { "code": null, "e": 26618, "s": 26598, "text": "x : x axis location" }, { "code": null, "e": 26638, "s": 26618, "text": "y : y axis location" }, { "code": null, "e": 26669, "s": 26638, "text": "label : custom textual content" }, { "code": null, "e": 26702, "s": 26669, "text": "color : color of textual content" }, { "code": null, "e": 26722, "s": 26702, "text": "size : size of text" }, { "code": null, "e": 26750, "s": 26722, "text": "fontface : fontface of text" }, { "code": null, "e": 26772, "s": 26750, "text": "angle : angle of text" }, { "code": null, "e": 26781, "s": 26772, "text": "Example:" }, { "code": null, "e": 26783, "s": 26781, "text": "R" }, { "code": "library(\"ggplot2\") gfg_data<-data.frame(x=c(1,2,3,4,5),y=c(5,4,3,2,1)) gfg_plot<-ggplot(data=gfg_data, aes(x, y)) + geom_bar(stat=\"identity\") gfg_plot + annotate(\"text\", x = 4, y = 4, label = expression( ~ alpha * beta*delta*zeta*tau*phi))", "e": 27076, "s": 26783, "text": null }, { "code": null, "e": 27084, "s": 27076, "text": "Output:" }, { "code": null, "e": 27091, "s": 27084, "text": "Picked" }, { "code": null, "e": 27100, "s": 27091, "text": "R-ggplot" }, { "code": null, "e": 27111, "s": 27100, "text": "R Language" }, { "code": null, "e": 27209, "s": 27111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27218, "s": 27209, "text": "Comments" }, { "code": null, "e": 27231, "s": 27218, "text": "Old Comments" }, { "code": null, "e": 27283, "s": 27231, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27321, "s": 27283, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27356, "s": 27321, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27414, "s": 27356, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27463, "s": 27414, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27500, "s": 27463, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27552, "s": 27500, "text": "How to change the order of bars in bar chart in R ?" }, { "code": null, "e": 27602, "s": 27552, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27645, "s": 27602, "text": "Replace Specific Characters in String in R" } ]
Why Is Logistic Regression the Spokesperson of Binomial Regression Models? | by Yufeng | Towards Data Science
A lot of events in our daily life follow the binomial distribution that describes the number of successes in a sequence of independent Bernoulli experiments. For example, assuming that the probability of James Harden making his shot is constant and each shot is independent, the number of field goals follows the binomial distribution. If we want to find the relationship between the success probability (p) of a binomially distributed variable Y with a list of independent variables xs, the binomial regression model is among our top choices. The link function is the major difference between a binomial regression and a linear regression model. Specifically, the linear regression model uses p directly as the response variable. The problem of the linear regression is that its response value is not bounded. However, the binomial regression uses a link function (l) of p as the response variable. The link function maps the linear combination of xs to a value that is between 0 and 1 but never reaches 0 or 1. Based on such criteria, there are mainly three common choices: When the link function is the logit function, the binomial regression becomes the well-known logistic regression. As one of the most first examples of classifiers in data science books, logistic regression undoubtedly has become the spokesperson of binomial regression models. There are mainly three reasons for that. 1. Applicable to more general cases.2. Easy interpretation.3. Works in retrospective studies. Let’s go over them in detail. A major difference of the complementary log-log model is that probit and logit functions are symmetrical but the complementary log-log function is asymmetric. # R codeeq = function(x){log(x/(1-x))}curve(eq, xlab="probability", ylab="l(probability)",col="red",lwd=2)curve(qnorm,add = T,lty="dashed",col="blue",lwd=2)curve(cloglog,add=T,lty="dotted",col="green",lwd=2)abline(v=0.5,lty="dashed",col="grey")legend("topleft",legend=c("logit","probit","cloglog"),lty = c("solid","dashed","dotted"),col = c("red","blue","green"),lwd=2) Specifically, we can see that the symmetric functions (logit and probit) cross at the position of p=0.5. However, the cloglog function has a different rate of approaching 0 and 1 on the probability. With such a feature, the cloglog link function is always used on extreme events where the probability of the event is close to either 0 or 1. In reality, it’s nearly impossible for us to make the assumption of the extreme value distribution with a limited amount of data. Therefore, in most cases, the cloglog link function is not selected for the binomial regression model. In other words, the logit and probit model could be applied to more general cases than the cloglog model. Let’s next look at the advantages of the logit model over the probit model. Logistic regression is more widely used than probit regression because of its easy interpretation, which benefits from the concept of odds. Interestingly, odds are sometimes more frequently used than probability in our daily life because of its better scale to represent chance, eg. the NBA playoffs bet. The relationship between the odds (o) and the probability (p) can be described in the following equation. And the logistic regression could be rewritten as, It is super easy to interpret the model above. For example, with all the other independent variables fixed, a unit increase in x1 increases the log-odds of success by β1. However, the interpretation of the probit model is not straightforward. The probit link function calculates the Z-score of the probability. Therefore, the interpretation of the same example should be that with all the other independent variables fixed, a unit increase in x1 increases the Z-score by β1. If the playoff bet website says that “the Z-score that Lakers wins the semi-final series is 1.65!”, few basketball fans will praise the website runner for his/her profession in statistics. In most practical situations, the data comes from retrospective sampling instead of prospective sampling. In retrospective studies, the outcome is fixed and the predictors are observed and collected, however, the predictors are fixed and the outcome is observed in prospective studies. For example, if we are interested in the relationship between dog cancer and eating dog food only, we first collect 10 different breeds of dogs and feed half of the dogs with dog food only and the other half with mixed food. And then we track the health status of the dogs in five years from now. This type of study is a prospective study and it is very ideal but slow. However, a cheaper and faster way should be that we find a number of dogs with cancer, we check the record of feeding in the past five years, and we compare them with a group of healthy dogs in our binomial model. This type of study is a retrospective study. Assume α1 is the probability that a dog is included in the retrospective study if they do not have cancer, while α0 is the probability of inclusion if the dogs have cancer. We can always assume α1 = α0 in the prospective study because we have not seen the outcome yet. But it’s not the case in the retrospective studies where α1 is usually much larger than α0. Let’s use the Bayes theorem to describe the relationship between the conditional probability (p*)that a dog has cancer given that it is included in the study and the unconditional probability (p) that the dog has cancer. After applying the logit link function, we have This equation above shows clearly that the difference between the prospective and retrospective study is log(α1/α0) which only affects the intercept term of the binomial model. The advantage of the logit link function is that we don’t need to worry about the intercept term even in a retrospective study because we are focused on the relative effect of the independent variables on the odds. In other words, even though it is impossible to know log(α1/α0) (or adjustment on β0) in a retrospective study, it won’t disable us from estimating the logistic model’s coefficients (the other βs). This feature is not valid for the probit link function. Logistic regression is one of the binomial regression models, and it uses logit as its link function. It is preferred over the other link functions because of its easy interpretation and usefulness in the retrospective study. Are the other link functions useless? No, try the Challenger Disaster data using the code below, and you will find the cloglog model gains the smallest AIC among the binomial models with the link functions. # R codelibrary(faraway)data(orings)logit_m = glm(cbind(damage, 6-damage) ~ temp, family=binomial(link = logit), orings)probit_m = glm(cbind(damage, 6-damage) ~ temp, family=binomial(link=probit), orings)clog_m = glm(cbind(damage, 6-damage) ~ temp, family=binomial(link=cloglog), orings)summary(logit_m)summary(probit_m)summary(clog_m) I hope you enjoy reading this article. Faraway, Julian J. Extending the linear model with R: generalized linear, mixed effects and nonparametric regression models. CRC press, 2016.
[ { "code": null, "e": 205, "s": 47, "text": "A lot of events in our daily life follow the binomial distribution that describes the number of successes in a sequence of independent Bernoulli experiments." }, { "code": null, "e": 383, "s": 205, "text": "For example, assuming that the probability of James Harden making his shot is constant and each shot is independent, the number of field goals follows the binomial distribution." }, { "code": null, "e": 591, "s": 383, "text": "If we want to find the relationship between the success probability (p) of a binomially distributed variable Y with a list of independent variables xs, the binomial regression model is among our top choices." }, { "code": null, "e": 778, "s": 591, "text": "The link function is the major difference between a binomial regression and a linear regression model. Specifically, the linear regression model uses p directly as the response variable." }, { "code": null, "e": 947, "s": 778, "text": "The problem of the linear regression is that its response value is not bounded. However, the binomial regression uses a link function (l) of p as the response variable." }, { "code": null, "e": 1123, "s": 947, "text": "The link function maps the linear combination of xs to a value that is between 0 and 1 but never reaches 0 or 1. Based on such criteria, there are mainly three common choices:" }, { "code": null, "e": 1441, "s": 1123, "text": "When the link function is the logit function, the binomial regression becomes the well-known logistic regression. As one of the most first examples of classifiers in data science books, logistic regression undoubtedly has become the spokesperson of binomial regression models. There are mainly three reasons for that." }, { "code": null, "e": 1535, "s": 1441, "text": "1. Applicable to more general cases.2. Easy interpretation.3. Works in retrospective studies." }, { "code": null, "e": 1565, "s": 1535, "text": "Let’s go over them in detail." }, { "code": null, "e": 1724, "s": 1565, "text": "A major difference of the complementary log-log model is that probit and logit functions are symmetrical but the complementary log-log function is asymmetric." }, { "code": null, "e": 2094, "s": 1724, "text": "# R codeeq = function(x){log(x/(1-x))}curve(eq, xlab=\"probability\", ylab=\"l(probability)\",col=\"red\",lwd=2)curve(qnorm,add = T,lty=\"dashed\",col=\"blue\",lwd=2)curve(cloglog,add=T,lty=\"dotted\",col=\"green\",lwd=2)abline(v=0.5,lty=\"dashed\",col=\"grey\")legend(\"topleft\",legend=c(\"logit\",\"probit\",\"cloglog\"),lty = c(\"solid\",\"dashed\",\"dotted\"),col = c(\"red\",\"blue\",\"green\"),lwd=2)" }, { "code": null, "e": 2435, "s": 2094, "text": "Specifically, we can see that the symmetric functions (logit and probit) cross at the position of p=0.5. However, the cloglog function has a different rate of approaching 0 and 1 on the probability. With such a feature, the cloglog link function is always used on extreme events where the probability of the event is close to either 0 or 1." }, { "code": null, "e": 2668, "s": 2435, "text": "In reality, it’s nearly impossible for us to make the assumption of the extreme value distribution with a limited amount of data. Therefore, in most cases, the cloglog link function is not selected for the binomial regression model." }, { "code": null, "e": 2850, "s": 2668, "text": "In other words, the logit and probit model could be applied to more general cases than the cloglog model. Let’s next look at the advantages of the logit model over the probit model." }, { "code": null, "e": 2990, "s": 2850, "text": "Logistic regression is more widely used than probit regression because of its easy interpretation, which benefits from the concept of odds." }, { "code": null, "e": 3261, "s": 2990, "text": "Interestingly, odds are sometimes more frequently used than probability in our daily life because of its better scale to represent chance, eg. the NBA playoffs bet. The relationship between the odds (o) and the probability (p) can be described in the following equation." }, { "code": null, "e": 3312, "s": 3261, "text": "And the logistic regression could be rewritten as," }, { "code": null, "e": 3483, "s": 3312, "text": "It is super easy to interpret the model above. For example, with all the other independent variables fixed, a unit increase in x1 increases the log-odds of success by β1." }, { "code": null, "e": 3787, "s": 3483, "text": "However, the interpretation of the probit model is not straightforward. The probit link function calculates the Z-score of the probability. Therefore, the interpretation of the same example should be that with all the other independent variables fixed, a unit increase in x1 increases the Z-score by β1." }, { "code": null, "e": 3976, "s": 3787, "text": "If the playoff bet website says that “the Z-score that Lakers wins the semi-final series is 1.65!”, few basketball fans will praise the website runner for his/her profession in statistics." }, { "code": null, "e": 4262, "s": 3976, "text": "In most practical situations, the data comes from retrospective sampling instead of prospective sampling. In retrospective studies, the outcome is fixed and the predictors are observed and collected, however, the predictors are fixed and the outcome is observed in prospective studies." }, { "code": null, "e": 4632, "s": 4262, "text": "For example, if we are interested in the relationship between dog cancer and eating dog food only, we first collect 10 different breeds of dogs and feed half of the dogs with dog food only and the other half with mixed food. And then we track the health status of the dogs in five years from now. This type of study is a prospective study and it is very ideal but slow." }, { "code": null, "e": 4891, "s": 4632, "text": "However, a cheaper and faster way should be that we find a number of dogs with cancer, we check the record of feeding in the past five years, and we compare them with a group of healthy dogs in our binomial model. This type of study is a retrospective study." }, { "code": null, "e": 5160, "s": 4891, "text": "Assume α1 is the probability that a dog is included in the retrospective study if they do not have cancer, while α0 is the probability of inclusion if the dogs have cancer. We can always assume α1 = α0 in the prospective study because we have not seen the outcome yet." }, { "code": null, "e": 5252, "s": 5160, "text": "But it’s not the case in the retrospective studies where α1 is usually much larger than α0." }, { "code": null, "e": 5473, "s": 5252, "text": "Let’s use the Bayes theorem to describe the relationship between the conditional probability (p*)that a dog has cancer given that it is included in the study and the unconditional probability (p) that the dog has cancer." }, { "code": null, "e": 5521, "s": 5473, "text": "After applying the logit link function, we have" }, { "code": null, "e": 5698, "s": 5521, "text": "This equation above shows clearly that the difference between the prospective and retrospective study is log(α1/α0) which only affects the intercept term of the binomial model." }, { "code": null, "e": 5913, "s": 5698, "text": "The advantage of the logit link function is that we don’t need to worry about the intercept term even in a retrospective study because we are focused on the relative effect of the independent variables on the odds." }, { "code": null, "e": 6167, "s": 5913, "text": "In other words, even though it is impossible to know log(α1/α0) (or adjustment on β0) in a retrospective study, it won’t disable us from estimating the logistic model’s coefficients (the other βs). This feature is not valid for the probit link function." }, { "code": null, "e": 6393, "s": 6167, "text": "Logistic regression is one of the binomial regression models, and it uses logit as its link function. It is preferred over the other link functions because of its easy interpretation and usefulness in the retrospective study." }, { "code": null, "e": 6600, "s": 6393, "text": "Are the other link functions useless? No, try the Challenger Disaster data using the code below, and you will find the cloglog model gains the smallest AIC among the binomial models with the link functions." }, { "code": null, "e": 6936, "s": 6600, "text": "# R codelibrary(faraway)data(orings)logit_m = glm(cbind(damage, 6-damage) ~ temp, family=binomial(link = logit), orings)probit_m = glm(cbind(damage, 6-damage) ~ temp, family=binomial(link=probit), orings)clog_m = glm(cbind(damage, 6-damage) ~ temp, family=binomial(link=cloglog), orings)summary(logit_m)summary(probit_m)summary(clog_m)" }, { "code": null, "e": 6975, "s": 6936, "text": "I hope you enjoy reading this article." } ]
How to iterate through images in a folder Python?
03 Dec, 2021 In this article, we will learn how to iterate through images in a folder in Python. At first we imported the os module to interact with the operating system. Then we import listdir() function from os to get access to the folders given in quotes. Then with the help of os.listdir() function, we iterate through the images and printed the names in order. Here we have mentioned only .png files to be loaded using the endswith() function. Python3 # import the modulesimport osfrom os import listdir # get the path/directoryfolder_dir = "C:/Users/RIJUSHREE/Desktop/Gfg images"for images in os.listdir(folder_dir): # check if the image ends with png if (images.endswith(".png")): print(images) Output: Here we have mentioned .png, .jpg, .jpeg files to be loaded using the endswith() function. Python3 # import the modulesimport osfrom os import listdir # get the path or directoryfolder_dir = "C:/Users/RIJUSHREE/Desktop/Gfg images"for images in os.listdir(folder_dir): # check if the image end swith png or jpg or jpeg if (images.endswith(".png") or images.endswith(".jpg")\ or images.endswith(".jpeg")): # display print(images) Output: At first, we imported the pathlib module from Path. Then we pass the directory/folder inside Path() function and used it .glob(‘*.png’) function to iterate through all the images present in this folder. Python3 # import required modulefrom pathlib import Path # get the path/directoryfolder_dir = 'Gfg images' # iterate over files in# that directoryimages = Path(folder_dir).glob('*.png')for image in images: print(image) Output: At first we imported the glob module. Then with the help of glob.iglob() function we iterate through the images and print the names in order. Here we have mentioned .png files to be loaded using the endswith() function. Python3 # import required moduleimport glob # get the path/directoryfolder_dir = 'Gfg images' # iterate over files in# that directoryfor images in glob.iglob(f'{folder_dir}/*'): # check if the image ends with png if (images.endswith(".png")): print(images) Output: anikakapoor Picked Python directory-program Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2021" }, { "code": null, "e": 113, "s": 28, "text": "In this article, we will learn how to iterate through images in a folder in Python. " }, { "code": null, "e": 187, "s": 113, "text": "At first we imported the os module to interact with the operating system." }, { "code": null, "e": 275, "s": 187, "text": "Then we import listdir() function from os to get access to the folders given in quotes." }, { "code": null, "e": 382, "s": 275, "text": "Then with the help of os.listdir() function, we iterate through the images and printed the names in order." }, { "code": null, "e": 466, "s": 382, "text": "Here we have mentioned only .png files to be loaded using the endswith() function." }, { "code": null, "e": 474, "s": 466, "text": "Python3" }, { "code": "# import the modulesimport osfrom os import listdir # get the path/directoryfolder_dir = \"C:/Users/RIJUSHREE/Desktop/Gfg images\"for images in os.listdir(folder_dir): # check if the image ends with png if (images.endswith(\".png\")): print(images)", "e": 733, "s": 474, "text": null }, { "code": null, "e": 741, "s": 733, "text": "Output:" }, { "code": null, "e": 832, "s": 741, "text": "Here we have mentioned .png, .jpg, .jpeg files to be loaded using the endswith() function." }, { "code": null, "e": 840, "s": 832, "text": "Python3" }, { "code": "# import the modulesimport osfrom os import listdir # get the path or directoryfolder_dir = \"C:/Users/RIJUSHREE/Desktop/Gfg images\"for images in os.listdir(folder_dir): # check if the image end swith png or jpg or jpeg if (images.endswith(\".png\") or images.endswith(\".jpg\")\\ or images.endswith(\".jpeg\")): # display print(images)", "e": 1197, "s": 840, "text": null }, { "code": null, "e": 1205, "s": 1197, "text": "Output:" }, { "code": null, "e": 1257, "s": 1205, "text": "At first, we imported the pathlib module from Path." }, { "code": null, "e": 1408, "s": 1257, "text": "Then we pass the directory/folder inside Path() function and used it .glob(‘*.png’) function to iterate through all the images present in this folder." }, { "code": null, "e": 1416, "s": 1408, "text": "Python3" }, { "code": "# import required modulefrom pathlib import Path # get the path/directoryfolder_dir = 'Gfg images' # iterate over files in# that directoryimages = Path(folder_dir).glob('*.png')for image in images: print(image)", "e": 1630, "s": 1416, "text": null }, { "code": null, "e": 1638, "s": 1630, "text": "Output:" }, { "code": null, "e": 1676, "s": 1638, "text": "At first we imported the glob module." }, { "code": null, "e": 1780, "s": 1676, "text": "Then with the help of glob.iglob() function we iterate through the images and print the names in order." }, { "code": null, "e": 1858, "s": 1780, "text": "Here we have mentioned .png files to be loaded using the endswith() function." }, { "code": null, "e": 1866, "s": 1858, "text": "Python3" }, { "code": "# import required moduleimport glob # get the path/directoryfolder_dir = 'Gfg images' # iterate over files in# that directoryfor images in glob.iglob(f'{folder_dir}/*'): # check if the image ends with png if (images.endswith(\".png\")): print(images)", "e": 2131, "s": 1866, "text": null }, { "code": null, "e": 2139, "s": 2131, "text": "Output:" }, { "code": null, "e": 2151, "s": 2139, "text": "anikakapoor" }, { "code": null, "e": 2158, "s": 2151, "text": "Picked" }, { "code": null, "e": 2183, "s": 2158, "text": "Python directory-program" }, { "code": null, "e": 2190, "s": 2183, "text": "Python" } ]
Python Program for Check if all digits of a number divide it
12 Jun, 2022 Given a number n, find whether all digits of n divide it or not. Examples: Input : 128 Output : Yes 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130 Output : No We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128 % d == 0 for d = 1, 2, 8. To do that, we need to iterate over each digit of the number. python3 # Python 3 program to# check the number is# divisible by all# digits are not. # Function to check# the divisibility# of the number by# its digit.def checkDivisibility(n, digit) : # If the digit divides the # number then return true # else return false. return (digit != 0 and n % digit == 0) # Function to check if# all digits of n divide# it or notdef allDigitsDivide( n) : temp = n while (temp > 0) : # Taking the digit of # the number into digit # var. digit = temp % 10 if ((checkDivisibility(n, digit)) == False) : return False temp = temp // 10 return True # Driver functionn = 128 if (allDigitsDivide(n)) : print("Yes")else : print("No" ) # This code is contributed by Nikita Tiwari. Output: Yes Time Complexity: O(log10n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant. Please refer complete article on Check if all digits of a number divide it for more details! himanshujakhmola143 tamanna17122007 Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to interchange first and last elements in a list Appending to list in Python dictionary Differences and Applications of List, Tuple, Set and Dictionary in Python Python Program to check Armstrong Number Python | Difference between two dates (in minutes) using datetime.timedelta() method Appending a dictionary to a list in Python Python | Remove spaces from a string Python Program for Merge Sort Python Program for simple interest Python | Get the first key in dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2022" }, { "code": null, "e": 94, "s": 28, "text": "Given a number n, find whether all digits of n divide it or not. " }, { "code": null, "e": 105, "s": 94, "text": "Examples: " }, { "code": null, "e": 201, "s": 105, "text": "Input : 128\nOutput : Yes\n128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.\n\nInput : 130\nOutput : No" }, { "code": null, "e": 415, "s": 201, "text": "We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128 % d == 0 for d = 1, 2, 8. To do that, we need to iterate over each digit of the number. " }, { "code": null, "e": 423, "s": 415, "text": "python3" }, { "code": "# Python 3 program to# check the number is# divisible by all# digits are not. # Function to check# the divisibility# of the number by# its digit.def checkDivisibility(n, digit) : # If the digit divides the # number then return true # else return false. return (digit != 0 and n % digit == 0) # Function to check if# all digits of n divide# it or notdef allDigitsDivide( n) : temp = n while (temp > 0) : # Taking the digit of # the number into digit # var. digit = temp % 10 if ((checkDivisibility(n, digit)) == False) : return False temp = temp // 10 return True # Driver functionn = 128 if (allDigitsDivide(n)) : print(\"Yes\")else : print(\"No\" ) # This code is contributed by Nikita Tiwari.", "e": 1227, "s": 423, "text": null }, { "code": null, "e": 1237, "s": 1227, "text": "Output: " }, { "code": null, "e": 1241, "s": 1237, "text": "Yes" }, { "code": null, "e": 1378, "s": 1241, "text": "Time Complexity: O(log10n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 1471, "s": 1378, "text": "Please refer complete article on Check if all digits of a number divide it for more details!" }, { "code": null, "e": 1491, "s": 1471, "text": "himanshujakhmola143" }, { "code": null, "e": 1507, "s": 1491, "text": "tamanna17122007" }, { "code": null, "e": 1523, "s": 1507, "text": "Python Programs" }, { "code": null, "e": 1621, "s": 1523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1685, "s": 1621, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 1724, "s": 1685, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 1798, "s": 1724, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 1839, "s": 1798, "text": "Python Program to check Armstrong Number" }, { "code": null, "e": 1924, "s": 1839, "text": "Python | Difference between two dates (in minutes) using datetime.timedelta() method" }, { "code": null, "e": 1967, "s": 1924, "text": "Appending a dictionary to a list in Python" }, { "code": null, "e": 2004, "s": 1967, "text": "Python | Remove spaces from a string" }, { "code": null, "e": 2034, "s": 2004, "text": "Python Program for Merge Sort" }, { "code": null, "e": 2069, "s": 2034, "text": "Python Program for simple interest" } ]
Dynamic modelling in object oriented analysis and design
22 Apr, 2020 Dynamic Modelling describes those aspect of the system that are concerned with time and sequencing of the operations. It is used to specify and implement the control aspect of the system. Dynamic model is represented graphically with the help of state diagrams. It is also known as state modelling. State model consist of multiple state diagrams, one for each class with temporal behavior that is important to an application. State diagram relates with events and states. Events represents external functional activity and states represents values objects. Events:An event is something that happen at a particular point in particular time such as a person press button or train 15930 departs from Amritsar. Event conveys information from one object to another. The events are of three types: Signal event, Change event, and Time event.These are explained as following below. Signal event :A signal event is an particular occurrence in time. A signal is a explicit one-way transmission of information from one object to another.A signal event is the event of sending or receiving signal.When an object send signal to another object it await for acknowledgement but acknowledgement signal is the separate signal under the control of second object, which may or may not choose to send it.The UML notation is (<>) written inside the name at top of the box and in another section list all the signal attributes.Eg:Change event :It is caused by the satisfaction of a boolean expression.The intent of the change event is that the expression is tested continually whenever the expression changes from false to true.The UML notation for a change event is the keyword when followed by a parenthesized boolean expression.Eg:when(battery power < lower limit) when(room temperature < heating/cooling point ) Time event :It is caused by occurrence of an absolute or the elapse of time interval.The UML notation for absolute time is the keyword when followed by a parenthesized expression involving time and for the time interval is keyword after followed by a parenthesized expression that evaluates time duration.Eg:when(Date = mar 2, 2005) after(50 seconds) Signal event :A signal event is an particular occurrence in time. A signal is a explicit one-way transmission of information from one object to another.A signal event is the event of sending or receiving signal.When an object send signal to another object it await for acknowledgement but acknowledgement signal is the separate signal under the control of second object, which may or may not choose to send it.The UML notation is (<>) written inside the name at top of the box and in another section list all the signal attributes.Eg: Change event :It is caused by the satisfaction of a boolean expression.The intent of the change event is that the expression is tested continually whenever the expression changes from false to true.The UML notation for a change event is the keyword when followed by a parenthesized boolean expression.Eg:when(battery power < lower limit) when(room temperature < heating/cooling point ) when(battery power < lower limit) when(room temperature < heating/cooling point ) Time event :It is caused by occurrence of an absolute or the elapse of time interval.The UML notation for absolute time is the keyword when followed by a parenthesized expression involving time and for the time interval is keyword after followed by a parenthesized expression that evaluates time duration.Eg:when(Date = mar 2, 2005) after(50 seconds) when(Date = mar 2, 2005) after(50 seconds) State :A state is an abstraction of attribute values and links of an object. Values and links are combined together into a state according to their entire behavior. The response of object according to input event is called state. A state corresponds to the interval between two events received by an object. The state of the event depends on the past event. So basically, state represents intervals of time. The UML notation for the state is a round box containing an optional state name list, list the name in boldface, center the name near the top of the box, capitalize the first letter. Eg: The following are the important points needs to be remember about state. Ignore attributes that do not affect the behavior of object.The objects in the class have finite number of possible states.Each object can be in one state at a time.ALL events are ignored in a state, except those for which behavior is explicitly prescribed.Both events and states depend upon level of abstraction. Ignore attributes that do not affect the behavior of object. The objects in the class have finite number of possible states. Each object can be in one state at a time. ALL events are ignored in a state, except those for which behavior is explicitly prescribed. Both events and states depend upon level of abstraction. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functional vs Non Functional Requirements Differences between Verification and Validation Software Engineering | Classical Waterfall Model Software Requirement Specification (SRS) Format Unit Testing | Software Testing Difference between Spring and Spring Boot Software Engineering | Requirements Engineering Process Software Testing Life Cycle (STLC) Difference between IAAS, PAAS and SAAS Software Engineering | Architectural Design
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Apr, 2020" }, { "code": null, "e": 610, "s": 53, "text": "Dynamic Modelling describes those aspect of the system that are concerned with time and sequencing of the operations. It is used to specify and implement the control aspect of the system. Dynamic model is represented graphically with the help of state diagrams. It is also known as state modelling. State model consist of multiple state diagrams, one for each class with temporal behavior that is important to an application. State diagram relates with events and states. Events represents external functional activity and states represents values objects." }, { "code": null, "e": 814, "s": 610, "text": "Events:An event is something that happen at a particular point in particular time such as a person press button or train 15930 departs from Amritsar. Event conveys information from one object to another." }, { "code": null, "e": 928, "s": 814, "text": "The events are of three types: Signal event, Change event, and Time event.These are explained as following below." }, { "code": null, "e": 2200, "s": 928, "text": "Signal event :A signal event is an particular occurrence in time. A signal is a explicit one-way transmission of information from one object to another.A signal event is the event of sending or receiving signal.When an object send signal to another object it await for acknowledgement but acknowledgement signal is the separate signal under the control of second object, which may or may not choose to send it.The UML notation is (<>) written inside the name at top of the box and in another section list all the signal attributes.Eg:Change event :It is caused by the satisfaction of a boolean expression.The intent of the change event is that the expression is tested continually whenever the expression changes from false to true.The UML notation for a change event is the keyword when followed by a parenthesized boolean expression.Eg:when(battery power < lower limit)\nwhen(room temperature < heating/cooling point ) Time event :It is caused by occurrence of an absolute or the elapse of time interval.The UML notation for absolute time is the keyword when followed by a parenthesized expression involving time and for the time interval is keyword after followed by a parenthesized expression that evaluates time duration.Eg:when(Date = mar 2, 2005)\nafter(50 seconds) " }, { "code": null, "e": 2735, "s": 2200, "text": "Signal event :A signal event is an particular occurrence in time. A signal is a explicit one-way transmission of information from one object to another.A signal event is the event of sending or receiving signal.When an object send signal to another object it await for acknowledgement but acknowledgement signal is the separate signal under the control of second object, which may or may not choose to send it.The UML notation is (<>) written inside the name at top of the box and in another section list all the signal attributes.Eg:" }, { "code": null, "e": 3122, "s": 2735, "text": "Change event :It is caused by the satisfaction of a boolean expression.The intent of the change event is that the expression is tested continually whenever the expression changes from false to true.The UML notation for a change event is the keyword when followed by a parenthesized boolean expression.Eg:when(battery power < lower limit)\nwhen(room temperature < heating/cooling point ) " }, { "code": null, "e": 3205, "s": 3122, "text": "when(battery power < lower limit)\nwhen(room temperature < heating/cooling point ) " }, { "code": null, "e": 3557, "s": 3205, "text": "Time event :It is caused by occurrence of an absolute or the elapse of time interval.The UML notation for absolute time is the keyword when followed by a parenthesized expression involving time and for the time interval is keyword after followed by a parenthesized expression that evaluates time duration.Eg:when(Date = mar 2, 2005)\nafter(50 seconds) " }, { "code": null, "e": 3601, "s": 3557, "text": "when(Date = mar 2, 2005)\nafter(50 seconds) " }, { "code": null, "e": 4196, "s": 3601, "text": "State :A state is an abstraction of attribute values and links of an object. Values and links are combined together into a state according to their entire behavior. The response of object according to input event is called state. A state corresponds to the interval between two events received by an object. The state of the event depends on the past event. So basically, state represents intervals of time. The UML notation for the state is a round box containing an optional state name list, list the name in boldface, center the name near the top of the box, capitalize the first letter. Eg:" }, { "code": null, "e": 4269, "s": 4196, "text": "The following are the important points needs to be remember about state." }, { "code": null, "e": 4583, "s": 4269, "text": "Ignore attributes that do not affect the behavior of object.The objects in the class have finite number of possible states.Each object can be in one state at a time.ALL events are ignored in a state, except those for which behavior is explicitly prescribed.Both events and states depend upon level of abstraction." }, { "code": null, "e": 4644, "s": 4583, "text": "Ignore attributes that do not affect the behavior of object." }, { "code": null, "e": 4708, "s": 4644, "text": "The objects in the class have finite number of possible states." }, { "code": null, "e": 4751, "s": 4708, "text": "Each object can be in one state at a time." }, { "code": null, "e": 4844, "s": 4751, "text": "ALL events are ignored in a state, except those for which behavior is explicitly prescribed." }, { "code": null, "e": 4901, "s": 4844, "text": "Both events and states depend upon level of abstraction." }, { "code": null, "e": 4922, "s": 4901, "text": "Software Engineering" }, { "code": null, "e": 5020, "s": 4922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5062, "s": 5020, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 5110, "s": 5062, "text": "Differences between Verification and Validation" }, { "code": null, "e": 5159, "s": 5110, "text": "Software Engineering | Classical Waterfall Model" }, { "code": null, "e": 5207, "s": 5159, "text": "Software Requirement Specification (SRS) Format" }, { "code": null, "e": 5239, "s": 5207, "text": "Unit Testing | Software Testing" }, { "code": null, "e": 5281, "s": 5239, "text": "Difference between Spring and Spring Boot" }, { "code": null, "e": 5337, "s": 5281, "text": "Software Engineering | Requirements Engineering Process" }, { "code": null, "e": 5372, "s": 5337, "text": "Software Testing Life Cycle (STLC)" }, { "code": null, "e": 5411, "s": 5372, "text": "Difference between IAAS, PAAS and SAAS" } ]
WPF - StackPanel
Stack panel is a simple and useful layout panel in XAML. In stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the orientation property. It is often used whenever any kind of list is to be created. The hierarchical inheritance of StackPanel class is as follows − Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) Children Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) Height Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) ItemHeight Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. ItemWidth Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. LogicalChildren Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.) LogicalOrientation The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.) Margin Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) Name Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) Orientation Gets or sets a value that specifies the dimension in which child content is arranged. Parent Gets the logical parent element of this element. (Inherited from FrameworkElement.) Resources Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) Style Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) Width Gets or sets the width of the element. (Inherited from FrameworkElement.) The following example shows how to add child elements into a StackPanel. The following XAML implementation creates buttons inside a StackPanel with some properties. <Window x:Class = "WPFStackPanel.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFStackPanel" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Orientation = "Horizontal"> <Button x:Name = "button" Content = "Button" Margin = "10" Width = "120" Height = "30" /> <Button x:Name = "button1" Content = "Button" Margin = "10" Width = "120" Height = "30" /> <Button x:Name = "button2" Content = "Button" Margin = "10" Width = "120" Height = "30" /> <Button x:Name = "button3" Content = "Button" Margin = "10" Width = "120" Height = "30" /> </StackPanel> </Grid> </Window> When you compile and execute the above code, it will produce the following window. You can see that the child elements are arranged in horizontal order. Yan can change the arrangement by setting the orientation property to Horizontal. By default, child elements will be arranged in vertical order. We recommend that you execute the above example code and try the other properties of this class as well.
[ { "code": null, "e": 2472, "s": 2154, "text": "Stack panel is a simple and useful layout panel in XAML. In stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the orientation property. It is often used whenever any kind of list is to be created. The hierarchical inheritance of StackPanel class is as follows −" }, { "code": null, "e": 2483, "s": 2472, "text": "Background" }, { "code": null, "e": 2562, "s": 2483, "text": "Gets or sets a Brush that fills the panel content area. (Inherited from Panel)" }, { "code": null, "e": 2571, "s": 2562, "text": "Children" }, { "code": null, "e": 2655, "s": 2571, "text": "Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.)" }, { "code": null, "e": 2662, "s": 2655, "text": "Height" }, { "code": null, "e": 2747, "s": 2662, "text": "Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 2758, "s": 2747, "text": "ItemHeight" }, { "code": null, "e": 2857, "s": 2758, "text": "Gets or sets a value that specifies the height of all items that are contained within a WrapPanel." }, { "code": null, "e": 2867, "s": 2857, "text": "ItemWidth" }, { "code": null, "e": 2965, "s": 2867, "text": "Gets or sets a value that specifies the width of all items that are contained within a WrapPanel." }, { "code": null, "e": 2981, "s": 2965, "text": "LogicalChildren" }, { "code": null, "e": 3091, "s": 2981, "text": "Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.)" }, { "code": null, "e": 3110, "s": 3091, "text": "LogicalOrientation" }, { "code": null, "e": 3221, "s": 3110, "text": "The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.)" }, { "code": null, "e": 3228, "s": 3221, "text": "Margin" }, { "code": null, "e": 3308, "s": 3228, "text": "Gets or sets the outer margin of an element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3313, "s": 3308, "text": "Name" }, { "code": null, "e": 3570, "s": 3313, "text": "Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3582, "s": 3570, "text": "Orientation" }, { "code": null, "e": 3668, "s": 3582, "text": "Gets or sets a value that specifies the dimension in which child content is arranged." }, { "code": null, "e": 3675, "s": 3668, "text": "Parent" }, { "code": null, "e": 3759, "s": 3675, "text": "Gets the logical parent element of this element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3769, "s": 3759, "text": "Resources" }, { "code": null, "e": 3858, "s": 3769, "text": "Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3864, "s": 3858, "text": "Style" }, { "code": null, "e": 3964, "s": 3864, "text": "Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.)" }, { "code": null, "e": 3970, "s": 3964, "text": "Width" }, { "code": null, "e": 4044, "s": 3970, "text": "Gets or sets the width of the element. (Inherited from FrameworkElement.)" }, { "code": null, "e": 4209, "s": 4044, "text": "The following example shows how to add child elements into a StackPanel. The following XAML implementation creates buttons inside a StackPanel with some properties." }, { "code": null, "e": 5163, "s": 4209, "text": "<Window x:Class = \"WPFStackPanel.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFStackPanel\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid> \n <StackPanel Orientation = \"Horizontal\"> \n <Button x:Name = \"button\" Content = \"Button\" Margin = \"10\" Width = \"120\" Height = \"30\" /> \n <Button x:Name = \"button1\" Content = \"Button\" Margin = \"10\" Width = \"120\" Height = \"30\" /> \n <Button x:Name = \"button2\" Content = \"Button\" Margin = \"10\" Width = \"120\" Height = \"30\" /> \n <Button x:Name = \"button3\" Content = \"Button\" Margin = \"10\" Width = \"120\" Height = \"30\" /> \n </StackPanel> \n </Grid> \n\t\n</Window> " }, { "code": null, "e": 5461, "s": 5163, "text": "When you compile and execute the above code, it will produce the following window. You can see that the child elements are arranged in horizontal order. Yan can change the arrangement by setting the orientation property to Horizontal. By default, child elements will be arranged in vertical order." } ]
Implement Deep Autoencoder in PyTorch for Image Reconstruction
13 Jul, 2021 Since the availability of staggering amounts of data on the internet, researchers and scientists from industry and academia keep trying to develop more efficient and reliable data transfer modes than the current state-of-the-art methods. Autoencoders are one of the key elements found in recent times used for such a task with their simple and intuitive architecture. Broadly, once an autoencoder is trained, the encoder weights can be sent to the transmitter side and the decoder weights to the receiver side. This way, the transmitter side can send data in an encoded format(thus saving them time and money) while the receiver side can receive the data at much less overhaul. This article will explore an interesting application of autoencoder, which can be used for image reconstruction on the famous MNIST digits dataset using the Pytorch framework in Python. As shown in the figure below, a very basic autoencoder consists of two main parts: An Encoder and,A Decoder An Encoder and, A Decoder Through a series of layers, the encoder takes the input and takes the higher dimensional data to the latent low dimension representation of the same values. The decoder takes this latent representation and outputs the reconstructed data. For a deeper understanding of the theory, the reader is encouraged to go through the following article: ML | Auto-Encoders A basic 2 layer Autoencoder Aside from the usual libraries like Numpy and Matplotlib, we only need the torch and torchvision libraries from the Pytorch toolchain for this article. You can use the following command to get all these libraries. pip3 install torch torchvision torchaudio numpy matplotlib Now onto the most interesting part, the code. The article assumes a basic familiarity with the PyTorch workflow and its various utilities, like Dataloaders, Datasets and Tensor transforms. For a quick refresher of these concepts, the reader is encouraged to go through the following articles: Training Neural Networks with Validation using PyTorch Getting Started with PyTorch The code is divided into 5 different steps for a better flow of the material and is to be executed sequentially for proper work. Each step also has some points at its start, which can help the reader better understand that step’s code. Step 1: Loading data and printing some sample images from the training set. Initializing Transform: Firstly, we initialize the transform which would be applied to each entry in the attained dataset. Since Tensors are internal to Pytorch’s functioning, we first convert each item to a tensor and normalize them to limit the pixel values between 0 & 1. This is done to make the optimization process easier and faster. Downloading Dataset: Then, we download the dataset using the torchvision.datasets utility and store it on our local machine in the folder ./MNIST/train and ./MNIST/test for both training and testing sets. We also convert these datasets into data loaders with batch sizes equal to 256 for faster learning. The reader is encouraged to play around with these values and expect consistent results. Plotting Dataset: Lastly, we randomly print out 25 images from the dataset to better view the data we’re dealing with. Code: Python # Importing the necessary librariesimport numpy as npimport matplotlib.pyplot as pltimport torchvisionimport torchplt.rcParams['figure.figsize'] = 15, 10 # Initializing the transform for the datasettransform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize((0.5), (0.5))]) # Downloading the MNIST datasettrain_dataset = torchvision.datasets.MNIST( root="./MNIST/train", train=True, transform=torchvision.transforms.ToTensor(), download=True) test_dataset = torchvision.datasets.MNIST( root="./MNIST/test", train=False, transform=torchvision.transforms.ToTensor(), download=True) # Creating Dataloaders from the# training and testing datasettrain_loader = torch.utils.data.DataLoader( train_dataset, batch_size=256)test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=256) # Printing 25 random images from the training datasetrandom_samples = np.random.randint( 1, len(train_dataset), (25)) for idx in range(random_samples.shape[0]): plt.subplot(5, 5, idx + 1) plt.imshow(train_dataset[idx][0][0].numpy(), cmap='gray') plt.title(train_dataset[idx][1]) plt.axis('off') plt.tight_layout()plt.show() Output: Random samples from the training set Step 2: Initializing the Deep Autoencoder model and other hyperparameters In this step, we initialize our DeepAutoencoder class, a child class of the torch.nn.Module. This abstracts away a lot of boilerplate code for us, and now we can focus on building our model architecture which is as follows: Model Architecture As described above, the encoder layers form the first half of the network, i.e., from Linear-1 to Linear-7, and the decoder forms the other half from Linear-10 to Sigmoid-15. We’ve used the torch.nn.Sequential utility for separating the encoder and decoder from one another. This was done to give a better understanding of the model’s architecture. After that, we initialize some model hyperparameters such that the training is done for 100 epochs using the Mean Square Error loss and Adam optimizer for the learning process. Python # Creating a DeepAutoencoder classclass DeepAutoencoder(torch.nn.Module): def __init__(self): super().__init__() self.encoder = torch.nn.Sequential( torch.nn.Linear(28 * 28, 256), torch.nn.ReLU(), torch.nn.Linear(256, 128), torch.nn.ReLU(), torch.nn.Linear(128, 64), torch.nn.ReLU(), torch.nn.Linear(64, 10) ) self.decoder = torch.nn.Sequential( torch.nn.Linear(10, 64), torch.nn.ReLU(), torch.nn.Linear(64, 128), torch.nn.ReLU(), torch.nn.Linear(128, 256), torch.nn.ReLU(), torch.nn.Linear(256, 28 * 28), torch.nn.Sigmoid() ) def forward(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded # Instantiating the model and hyperparametersmodel = DeepAutoencoder()criterion = torch.nn.MSELoss()num_epochs = 100optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) Step 3: Training loop The training loop iterates for the 100 epochs and does the following things: Iterates over each batch and calculates loss between the outputted image and the original image(which is the output). Averages out the loss for each batch and stores images and their outputs for each epoch. After the loop ends, we plot out the training loss to better understand the training process. As we can see, that the loss decreases for each consecutive epoch, and thus the training can be deemed successful. Python # List that will store the training losstrain_loss = [] # Dictionary that will store the# different images and outputs for # various epochsoutputs = {} batch_size = len(train_loader) # Training loop startsfor epoch in range(num_epochs): # Initializing variable for storing # loss running_loss = 0 # Iterating over the training dataset for batch in train_loader: # Loading image(s) and # reshaping it into a 1-d vector img, _ = batch img = img.reshape(-1, 28*28) # Generating output out = model(img) # Calculating loss loss = criterion(out, img) # Updating weights according # to the calculated loss optimizer.zero_grad() loss.backward() optimizer.step() # Incrementing loss running_loss += loss.item() # Averaging out loss over entire batch running_loss /= batch_size train_loss.append(running_loss) # Storing useful images and # reconstructed outputs for the last batch outputs[epoch+1] = {'img': img, 'out': out} # Plotting the training lossplt.plot(range(1,num_epochs+1),train_loss)plt.xlabel("Number of epochs")plt.ylabel("Training Loss")plt.show() Output: Training loss vs. Epochs Step 4: Visualizing the reconstruction The best part of this project is that the reader can visualize the reconstruction of each epoch and understand the iterative learning of the model. We firstly plot out the first 5 reconstructed(or outputted images) for epochs = [1, 5, 10, 50, 100]. Then we also plot the corresponding original images on the bottom for comparison. We can see how the reconstruction improves for each epoch and gets very close to the original by the last epoch. Python # Plotting is done on a 7x5 subplot# Plotting the reconstructed images # Initializing subplot countercounter = 1 # Plotting reconstructions# for epochs = [1, 5, 10, 50, 100]epochs_list = [1, 5, 10, 50, 100] # Iterating over specified epochsfor val in epochs_list: # Extracting recorded information temp = outputs[val]['out'].detach().numpy() title_text = f"Epoch = {val}" # Plotting first five images of the last batch for idx in range(5): plt.subplot(7, 5, counter) plt.title(title_text) plt.imshow(temp[idx].reshape(28,28), cmap= 'gray') plt.axis('off') # Incrementing the subplot counter counter+=1 # Plotting original images # Iterating over first five# images of the last batchfor idx in range(5): # Obtaining image from the dictionary val = outputs[10]['img'] # Plotting image plt.subplot(7,5,counter) plt.imshow(val[idx].reshape(28, 28), cmap = 'gray') plt.title("Original Image") plt.axis('off') # Incrementing subplot counter counter+=1 plt.tight_layout()plt.show() Output: Visualizing the reconstruction from the data collected during the training process Step 5: Checking performance on the test set. Good practice in machine learning is to check the model’s performance on the test set also. To do that, we do the following steps: Generate outputs for the last batch of the test set. Plot the first 10 outputs and corresponding original images for comparison. As we can see, the reconstruction was excellent on this test set also, which completes the pipeline. Python # Dictionary that will store the different# images and outputs for various epochsoutputs = {} # Extracting the last batch from the test # datasetimg, _ = list(test_loader)[-1] # Reshaping into 1d vectorimg = img.reshape(-1, 28 * 28) # Generating output for the obtained# batchout = model(img) # Storing information in dictionaryoutputs['img'] = imgoutputs['out'] = out # Plotting reconstructed images# Initializing subplot countercounter = 1val = outputs['out'].detach().numpy() # Plotting first 10 images of the batchfor idx in range(10): plt.subplot(2, 10, counter) plt.title("Reconstructed \n image") plt.imshow(val[idx].reshape(28, 28), cmap='gray') plt.axis('off') # Incrementing subplot counter counter += 1 # Plotting original images # Plotting first 10 imagesfor idx in range(10): val = outputs['img'] plt.subplot(2, 10, counter) plt.imshow(val[idx].reshape(28, 28), cmap='gray') plt.title("Original Image") plt.axis('off') # Incrementing subplot counter counter += 1 plt.tight_layout()plt.show() Output: Verifying performance on the test set Autoencoders are fast becoming one of the most exciting areas of research in machine learning. This article covered the Pytorch implementation of a deep autoencoder for image reconstruction. The reader is encouraged to play around with the network architecture and hyperparameters to improve the reconstruction quality and the loss values. Deep-Learning Picked Python-PyTorch Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Support Vector Machine Algorithm Markov Decision Process DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jul, 2021" }, { "code": null, "e": 396, "s": 28, "text": "Since the availability of staggering amounts of data on the internet, researchers and scientists from industry and academia keep trying to develop more efficient and reliable data transfer modes than the current state-of-the-art methods. Autoencoders are one of the key elements found in recent times used for such a task with their simple and intuitive architecture." }, { "code": null, "e": 892, "s": 396, "text": "Broadly, once an autoencoder is trained, the encoder weights can be sent to the transmitter side and the decoder weights to the receiver side. This way, the transmitter side can send data in an encoded format(thus saving them time and money) while the receiver side can receive the data at much less overhaul. This article will explore an interesting application of autoencoder, which can be used for image reconstruction on the famous MNIST digits dataset using the Pytorch framework in Python." }, { "code": null, "e": 976, "s": 892, "text": "As shown in the figure below, a very basic autoencoder consists of two main parts: " }, { "code": null, "e": 1001, "s": 976, "text": "An Encoder and,A Decoder" }, { "code": null, "e": 1017, "s": 1001, "text": "An Encoder and," }, { "code": null, "e": 1027, "s": 1017, "text": "A Decoder" }, { "code": null, "e": 1266, "s": 1027, "text": "Through a series of layers, the encoder takes the input and takes the higher dimensional data to the latent low dimension representation of the same values. The decoder takes this latent representation and outputs the reconstructed data. " }, { "code": null, "e": 1389, "s": 1266, "text": "For a deeper understanding of the theory, the reader is encouraged to go through the following article: ML | Auto-Encoders" }, { "code": null, "e": 1417, "s": 1389, "text": "A basic 2 layer Autoencoder" }, { "code": null, "e": 1631, "s": 1417, "text": "Aside from the usual libraries like Numpy and Matplotlib, we only need the torch and torchvision libraries from the Pytorch toolchain for this article. You can use the following command to get all these libraries." }, { "code": null, "e": 1690, "s": 1631, "text": "pip3 install torch torchvision torchaudio numpy matplotlib" }, { "code": null, "e": 1983, "s": 1690, "text": "Now onto the most interesting part, the code. The article assumes a basic familiarity with the PyTorch workflow and its various utilities, like Dataloaders, Datasets and Tensor transforms. For a quick refresher of these concepts, the reader is encouraged to go through the following articles:" }, { "code": null, "e": 2038, "s": 1983, "text": "Training Neural Networks with Validation using PyTorch" }, { "code": null, "e": 2067, "s": 2038, "text": "Getting Started with PyTorch" }, { "code": null, "e": 2304, "s": 2067, "text": "The code is divided into 5 different steps for a better flow of the material and is to be executed sequentially for proper work. Each step also has some points at its start, which can help the reader better understand that step’s code. " }, { "code": null, "e": 2380, "s": 2304, "text": "Step 1: Loading data and printing some sample images from the training set." }, { "code": null, "e": 2720, "s": 2380, "text": "Initializing Transform: Firstly, we initialize the transform which would be applied to each entry in the attained dataset. Since Tensors are internal to Pytorch’s functioning, we first convert each item to a tensor and normalize them to limit the pixel values between 0 & 1. This is done to make the optimization process easier and faster." }, { "code": null, "e": 3114, "s": 2720, "text": "Downloading Dataset: Then, we download the dataset using the torchvision.datasets utility and store it on our local machine in the folder ./MNIST/train and ./MNIST/test for both training and testing sets. We also convert these datasets into data loaders with batch sizes equal to 256 for faster learning. The reader is encouraged to play around with these values and expect consistent results." }, { "code": null, "e": 3233, "s": 3114, "text": "Plotting Dataset: Lastly, we randomly print out 25 images from the dataset to better view the data we’re dealing with." }, { "code": null, "e": 3239, "s": 3233, "text": "Code:" }, { "code": null, "e": 3246, "s": 3239, "text": "Python" }, { "code": "# Importing the necessary librariesimport numpy as npimport matplotlib.pyplot as pltimport torchvisionimport torchplt.rcParams['figure.figsize'] = 15, 10 # Initializing the transform for the datasettransform = torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize((0.5), (0.5))]) # Downloading the MNIST datasettrain_dataset = torchvision.datasets.MNIST( root=\"./MNIST/train\", train=True, transform=torchvision.transforms.ToTensor(), download=True) test_dataset = torchvision.datasets.MNIST( root=\"./MNIST/test\", train=False, transform=torchvision.transforms.ToTensor(), download=True) # Creating Dataloaders from the# training and testing datasettrain_loader = torch.utils.data.DataLoader( train_dataset, batch_size=256)test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=256) # Printing 25 random images from the training datasetrandom_samples = np.random.randint( 1, len(train_dataset), (25)) for idx in range(random_samples.shape[0]): plt.subplot(5, 5, idx + 1) plt.imshow(train_dataset[idx][0][0].numpy(), cmap='gray') plt.title(train_dataset[idx][1]) plt.axis('off') plt.tight_layout()plt.show()", "e": 4463, "s": 3246, "text": null }, { "code": null, "e": 4471, "s": 4463, "text": "Output:" }, { "code": null, "e": 4508, "s": 4471, "text": "Random samples from the training set" }, { "code": null, "e": 4582, "s": 4508, "text": "Step 2: Initializing the Deep Autoencoder model and other hyperparameters" }, { "code": null, "e": 4806, "s": 4582, "text": "In this step, we initialize our DeepAutoencoder class, a child class of the torch.nn.Module. This abstracts away a lot of boilerplate code for us, and now we can focus on building our model architecture which is as follows:" }, { "code": null, "e": 4825, "s": 4806, "text": "Model Architecture" }, { "code": null, "e": 5351, "s": 4825, "text": "As described above, the encoder layers form the first half of the network, i.e., from Linear-1 to Linear-7, and the decoder forms the other half from Linear-10 to Sigmoid-15. We’ve used the torch.nn.Sequential utility for separating the encoder and decoder from one another. This was done to give a better understanding of the model’s architecture. After that, we initialize some model hyperparameters such that the training is done for 100 epochs using the Mean Square Error loss and Adam optimizer for the learning process." }, { "code": null, "e": 5358, "s": 5351, "text": "Python" }, { "code": "# Creating a DeepAutoencoder classclass DeepAutoencoder(torch.nn.Module): def __init__(self): super().__init__() self.encoder = torch.nn.Sequential( torch.nn.Linear(28 * 28, 256), torch.nn.ReLU(), torch.nn.Linear(256, 128), torch.nn.ReLU(), torch.nn.Linear(128, 64), torch.nn.ReLU(), torch.nn.Linear(64, 10) ) self.decoder = torch.nn.Sequential( torch.nn.Linear(10, 64), torch.nn.ReLU(), torch.nn.Linear(64, 128), torch.nn.ReLU(), torch.nn.Linear(128, 256), torch.nn.ReLU(), torch.nn.Linear(256, 28 * 28), torch.nn.Sigmoid() ) def forward(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded # Instantiating the model and hyperparametersmodel = DeepAutoencoder()criterion = torch.nn.MSELoss()num_epochs = 100optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)", "e": 6402, "s": 5358, "text": null }, { "code": null, "e": 6424, "s": 6402, "text": "Step 3: Training loop" }, { "code": null, "e": 6501, "s": 6424, "text": "The training loop iterates for the 100 epochs and does the following things:" }, { "code": null, "e": 6619, "s": 6501, "text": "Iterates over each batch and calculates loss between the outputted image and the original image(which is the output)." }, { "code": null, "e": 6708, "s": 6619, "text": "Averages out the loss for each batch and stores images and their outputs for each epoch." }, { "code": null, "e": 6917, "s": 6708, "text": "After the loop ends, we plot out the training loss to better understand the training process. As we can see, that the loss decreases for each consecutive epoch, and thus the training can be deemed successful." }, { "code": null, "e": 6924, "s": 6917, "text": "Python" }, { "code": "# List that will store the training losstrain_loss = [] # Dictionary that will store the# different images and outputs for # various epochsoutputs = {} batch_size = len(train_loader) # Training loop startsfor epoch in range(num_epochs): # Initializing variable for storing # loss running_loss = 0 # Iterating over the training dataset for batch in train_loader: # Loading image(s) and # reshaping it into a 1-d vector img, _ = batch img = img.reshape(-1, 28*28) # Generating output out = model(img) # Calculating loss loss = criterion(out, img) # Updating weights according # to the calculated loss optimizer.zero_grad() loss.backward() optimizer.step() # Incrementing loss running_loss += loss.item() # Averaging out loss over entire batch running_loss /= batch_size train_loss.append(running_loss) # Storing useful images and # reconstructed outputs for the last batch outputs[epoch+1] = {'img': img, 'out': out} # Plotting the training lossplt.plot(range(1,num_epochs+1),train_loss)plt.xlabel(\"Number of epochs\")plt.ylabel(\"Training Loss\")plt.show()", "e": 8202, "s": 6924, "text": null }, { "code": null, "e": 8210, "s": 8202, "text": "Output:" }, { "code": null, "e": 8235, "s": 8210, "text": "Training loss vs. Epochs" }, { "code": null, "e": 8274, "s": 8235, "text": "Step 4: Visualizing the reconstruction" }, { "code": null, "e": 8422, "s": 8274, "text": "The best part of this project is that the reader can visualize the reconstruction of each epoch and understand the iterative learning of the model." }, { "code": null, "e": 8523, "s": 8422, "text": "We firstly plot out the first 5 reconstructed(or outputted images) for epochs = [1, 5, 10, 50, 100]." }, { "code": null, "e": 8605, "s": 8523, "text": "Then we also plot the corresponding original images on the bottom for comparison." }, { "code": null, "e": 8718, "s": 8605, "text": "We can see how the reconstruction improves for each epoch and gets very close to the original by the last epoch." }, { "code": null, "e": 8725, "s": 8718, "text": "Python" }, { "code": "# Plotting is done on a 7x5 subplot# Plotting the reconstructed images # Initializing subplot countercounter = 1 # Plotting reconstructions# for epochs = [1, 5, 10, 50, 100]epochs_list = [1, 5, 10, 50, 100] # Iterating over specified epochsfor val in epochs_list: # Extracting recorded information temp = outputs[val]['out'].detach().numpy() title_text = f\"Epoch = {val}\" # Plotting first five images of the last batch for idx in range(5): plt.subplot(7, 5, counter) plt.title(title_text) plt.imshow(temp[idx].reshape(28,28), cmap= 'gray') plt.axis('off') # Incrementing the subplot counter counter+=1 # Plotting original images # Iterating over first five# images of the last batchfor idx in range(5): # Obtaining image from the dictionary val = outputs[10]['img'] # Plotting image plt.subplot(7,5,counter) plt.imshow(val[idx].reshape(28, 28), cmap = 'gray') plt.title(\"Original Image\") plt.axis('off') # Incrementing subplot counter counter+=1 plt.tight_layout()plt.show()", "e": 9844, "s": 8725, "text": null }, { "code": null, "e": 9852, "s": 9844, "text": "Output:" }, { "code": null, "e": 9935, "s": 9852, "text": "Visualizing the reconstruction from the data collected during the training process" }, { "code": null, "e": 9981, "s": 9935, "text": "Step 5: Checking performance on the test set." }, { "code": null, "e": 10112, "s": 9981, "text": "Good practice in machine learning is to check the model’s performance on the test set also. To do that, we do the following steps:" }, { "code": null, "e": 10165, "s": 10112, "text": "Generate outputs for the last batch of the test set." }, { "code": null, "e": 10241, "s": 10165, "text": "Plot the first 10 outputs and corresponding original images for comparison." }, { "code": null, "e": 10342, "s": 10241, "text": "As we can see, the reconstruction was excellent on this test set also, which completes the pipeline." }, { "code": null, "e": 10349, "s": 10342, "text": "Python" }, { "code": "# Dictionary that will store the different# images and outputs for various epochsoutputs = {} # Extracting the last batch from the test # datasetimg, _ = list(test_loader)[-1] # Reshaping into 1d vectorimg = img.reshape(-1, 28 * 28) # Generating output for the obtained# batchout = model(img) # Storing information in dictionaryoutputs['img'] = imgoutputs['out'] = out # Plotting reconstructed images# Initializing subplot countercounter = 1val = outputs['out'].detach().numpy() # Plotting first 10 images of the batchfor idx in range(10): plt.subplot(2, 10, counter) plt.title(\"Reconstructed \\n image\") plt.imshow(val[idx].reshape(28, 28), cmap='gray') plt.axis('off') # Incrementing subplot counter counter += 1 # Plotting original images # Plotting first 10 imagesfor idx in range(10): val = outputs['img'] plt.subplot(2, 10, counter) plt.imshow(val[idx].reshape(28, 28), cmap='gray') plt.title(\"Original Image\") plt.axis('off') # Incrementing subplot counter counter += 1 plt.tight_layout()plt.show()", "e": 11406, "s": 10349, "text": null }, { "code": null, "e": 11414, "s": 11406, "text": "Output:" }, { "code": null, "e": 11452, "s": 11414, "text": "Verifying performance on the test set" }, { "code": null, "e": 11792, "s": 11452, "text": "Autoencoders are fast becoming one of the most exciting areas of research in machine learning. This article covered the Pytorch implementation of a deep autoencoder for image reconstruction. The reader is encouraged to play around with the network architecture and hyperparameters to improve the reconstruction quality and the loss values." }, { "code": null, "e": 11806, "s": 11792, "text": "Deep-Learning" }, { "code": null, "e": 11813, "s": 11806, "text": "Picked" }, { "code": null, "e": 11828, "s": 11813, "text": "Python-PyTorch" }, { "code": null, "e": 11845, "s": 11828, "text": "Machine Learning" }, { "code": null, "e": 11852, "s": 11845, "text": "Python" }, { "code": null, "e": 11869, "s": 11852, "text": "Machine Learning" }, { "code": null, "e": 11967, "s": 11869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12008, "s": 11967, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 12044, "s": 12008, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 12077, "s": 12044, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 12101, "s": 12077, "text": "Markov Decision Process" }, { "code": null, "e": 12152, "s": 12101, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 12180, "s": 12152, "text": "Read JSON file using Python" }, { "code": null, "e": 12230, "s": 12180, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 12252, "s": 12230, "text": "Python map() function" } ]
Python | re.search() vs re.match()
09 Aug, 2021 Prerequisite: Regex in Python The re.search() and re.match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. The function searches for some substring in a string and returns a match object if found, else it returns none. There is a difference between the use of both functions. Both return the first match of a substring found in the string, but re.match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none. While re.search() searches for the whole string even if the string contains multi-lines and tries to find a match of the substring in all the lines of string. Example : Python3 # import re moduleimport re Substring ='string' String1 ='''We are learning regex with geeksforgeeks regex is very useful for string matching. It is fast too.'''String2 ='''string We are learning regex with geeksforgeeks regex is very useful for string matching. It is fast too.''' # Use of re.search() Methodprint(re.search(Substring, String1, re.IGNORECASE))# Use of re.match() Methodprint(re.match(Substring, String1, re.IGNORECASE)) # Use of re.search() Methodprint(re.search(Substring, String2, re.IGNORECASE))# Use of re.match() Methodprint(re.match(Substring, String2, re.IGNORECASE)) Output : <re.Match object; span=(75, 81), match='string'> None <re.Match object; span=(0, 6), match='string'> <re.Match object; span=(0, 6), match='string'> Conclusion : re.search() is returning match object and implies that first match found at index 69.re.match() is returning none because match exists in the second line of the string and re.match() only works if the match is found at the beginning of the string. re.IGNORECASE is used to ignore the case sensitivity in the strings. Both re.search() and re.match() returns only the first occurrence of a substring in the string and ignore others. re.search() is returning match object and implies that first match found at index 69. re.match() is returning none because match exists in the second line of the string and re.match() only works if the match is found at the beginning of the string. re.IGNORECASE is used to ignore the case sensitivity in the strings. Both re.search() and re.match() returns only the first occurrence of a substring in the string and ignore others. narendradodwaria ajwan92 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Aug, 2021" }, { "code": null, "e": 82, "s": 52, "text": "Prerequisite: Regex in Python" }, { "code": null, "e": 338, "s": 82, "text": "The re.search() and re.match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. The function searches for some substring in a string and returns a match object if found, else it returns none." }, { "code": null, "e": 808, "s": 338, "text": "There is a difference between the use of both functions. Both return the first match of a substring found in the string, but re.match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none. While re.search() searches for the whole string even if the string contains multi-lines and tries to find a match of the substring in all the lines of string. " }, { "code": null, "e": 819, "s": 808, "text": "Example : " }, { "code": null, "e": 827, "s": 819, "text": "Python3" }, { "code": "# import re moduleimport re Substring ='string' String1 ='''We are learning regex with geeksforgeeks regex is very useful for string matching. It is fast too.'''String2 ='''string We are learning regex with geeksforgeeks regex is very useful for string matching. It is fast too.''' # Use of re.search() Methodprint(re.search(Substring, String1, re.IGNORECASE))# Use of re.match() Methodprint(re.match(Substring, String1, re.IGNORECASE)) # Use of re.search() Methodprint(re.search(Substring, String2, re.IGNORECASE))# Use of re.match() Methodprint(re.match(Substring, String2, re.IGNORECASE))", "e": 1454, "s": 827, "text": null }, { "code": null, "e": 1464, "s": 1454, "text": "Output : " }, { "code": null, "e": 1612, "s": 1464, "text": "<re.Match object; span=(75, 81), match='string'>\nNone\n<re.Match object; span=(0, 6), match='string'>\n<re.Match object; span=(0, 6), match='string'>" }, { "code": null, "e": 1626, "s": 1612, "text": "Conclusion : " }, { "code": null, "e": 2058, "s": 1626, "text": "re.search() is returning match object and implies that first match found at index 69.re.match() is returning none because match exists in the second line of the string and re.match() only works if the match is found at the beginning of the string. re.IGNORECASE is used to ignore the case sensitivity in the strings. Both re.search() and re.match() returns only the first occurrence of a substring in the string and ignore others. " }, { "code": null, "e": 2144, "s": 2058, "text": "re.search() is returning match object and implies that first match found at index 69." }, { "code": null, "e": 2308, "s": 2144, "text": "re.match() is returning none because match exists in the second line of the string and re.match() only works if the match is found at the beginning of the string. " }, { "code": null, "e": 2378, "s": 2308, "text": "re.IGNORECASE is used to ignore the case sensitivity in the strings. " }, { "code": null, "e": 2493, "s": 2378, "text": "Both re.search() and re.match() returns only the first occurrence of a substring in the string and ignore others. " }, { "code": null, "e": 2510, "s": 2493, "text": "narendradodwaria" }, { "code": null, "e": 2518, "s": 2510, "text": "ajwan92" }, { "code": null, "e": 2525, "s": 2518, "text": "Python" }, { "code": null, "e": 2623, "s": 2525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2655, "s": 2623, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2682, "s": 2655, "text": "Python Classes and Objects" }, { "code": null, "e": 2703, "s": 2682, "text": "Python OOPs Concepts" }, { "code": null, "e": 2726, "s": 2703, "text": "Introduction To PYTHON" }, { "code": null, "e": 2757, "s": 2726, "text": "Python | os.path.join() method" }, { "code": null, "e": 2813, "s": 2757, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2855, "s": 2813, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2897, "s": 2855, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2936, "s": 2897, "text": "Python | Get unique values from a list" } ]
Surd and indices in Mathematics
15 Jun, 2021 Surds :Let x is a rational number(i.e. can be expressed in p/q form where q ≠ 0) and n is any positive integer such that x1/n = n √x is irrational(i.e. can’t be expressed in p/q form where q ≠ 0), then that n √x is known as surd of nth order. Example – √2, √29, etc. √2 = 1.414213562..., which is non-terminating and non-repeating, therefore √2 is an irrational number. And √2= 21/2, where n=2, therefore √2 is a surd. In simple words, surd is a number whose power is an infraction and can not be solved completely(i.e. we can not get a rational number). Indices : It is also known as power or exponent. X p, where x is a base and p is power(or index)of x. where p, x can be any decimal number. Example – Let a number 23= 2×2×2= 8, then 2 is the base and 3 is indices. An exponent of a number represents how many times a number is multiplied by itself. They are used to representing roots, fractions. Rules of surds :When a surd is multiplied by a rational number then it is known as a mixed surd. Example – 2√2, where 2 is a rational number and √2 is a surd. Here x, y used in the rules are decimal numbers as follows. Rules of indices : Other Rules :Some other rules are used in solving surds and indices problems as follows. // From 1 to 6 rules covered in table. 7) x m = x n then m=n and a≠ 0,1,-1. 8) x m = y m then x = y if m is even x= y, if m is odd Basic problems based on surds and indices : Question-1 : Which of the following is a surd? a) 2√36 b) 5√32 c) 6√729 d) 3√25 Solution – An answer is an option (d) Explanation - 3√25= (25)1/3 = 2.92401773821... which is irrational So it is surd. Question-2 :Find √√√3 a) 31/3 b) 31/4 c) 31/6 d) 31/8 Solution – An answer is an option (d) Explanation - ((3 1/2)1/2) 1/2) = 31/2 × 1/2 ×1/2 = 3 1/8 according to rule number 5 in indices. Question-3 : If (4/5)3 (4/5)-6= (4/5)2x-1, the value of x is a) -2 b)2 c) -1 d)1 Solution – The answer is option (c) Explanation - LHS = (4/5)3 (4/5)-6= (4/5)3-6 = (4/5)-3 RHS = (4/5)2x-1 According to question LHS = RHS ⇒ (4/5)-3 = (4/5)2x-1 ⇒ 2x-1 = -3 ⇒ 2x = -2 ⇒ x = -1 Question-4 : 34x+1 = 1/27, then x is Solution – 34x+1 = (1/3)3 ⇒34x+1 = 3-3 ⇒4x+1 = -3 ⇒4x= -4 ⇒x = -1 Question-5 : Find the smallest among 2 1/12, 3 1/72, 41/24,61/36. Solution – The answer is 31/72 Explanation – As the exponents of all numbers are infractions, therefore multiply each exponent by LCM of all the exponents. The LCM of all numbers is 72. 2(1/12 × 72) = 26 = 64 3(1/72 ×72) = 3 4(1/24 ×72) = 43 = 64 6 (1/36 ×72) = 62 = 36 Question-6 :The greatest among 2400, 3300,5200,6200. a) 2400 b)3300 c)5200 d)6200 Solution – An answer is an option (d) Explanation –As the power of each number is large, and it is very difficult to compare them, therefore we will divide each exponent by a common factor(i.e. take HCF of each exponent). The HCF of all exponents is 100. 2400/100 = 24 = 8. 3300/100 = 33 = 27 5200/100 = 52 = 25 6200/100= 62 = 36 So 6200 is largest among all. Picked Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Propositional Logic and Predicate Logic Activation Functions Logic Notations in LaTeX Modular Arithmetic Mathematics | Introduction of Set theory Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jun, 2021" }, { "code": null, "e": 298, "s": 53, "text": "Surds :Let x is a rational number(i.e. can be expressed in p/q form where q ≠ 0) and n is any positive integer such that x1/n = n √x is irrational(i.e. can’t be expressed in p/q form where q ≠ 0), then that n √x is known as surd of nth order." }, { "code": null, "e": 308, "s": 298, "text": "Example –" }, { "code": null, "e": 322, "s": 308, "text": "√2, √29, etc." }, { "code": null, "e": 610, "s": 322, "text": "√2 = 1.414213562..., which is non-terminating and non-repeating, therefore √2 is an irrational number. And √2= 21/2, where n=2, therefore √2 is a surd. In simple words, surd is a number whose power is an infraction and can not be solved completely(i.e. we can not get a rational number)." }, { "code": null, "e": 620, "s": 610, "text": "Indices :" }, { "code": null, "e": 659, "s": 620, "text": "It is also known as power or exponent." }, { "code": null, "e": 750, "s": 659, "text": "X p, where x is a base and p is power(or index)of x. where p, x can be any decimal number." }, { "code": null, "e": 824, "s": 750, "text": "Example – Let a number 23= 2×2×2= 8, then 2 is the base and 3 is indices." }, { "code": null, "e": 908, "s": 824, "text": "An exponent of a number represents how many times a number is multiplied by itself." }, { "code": null, "e": 956, "s": 908, "text": "They are used to representing roots, fractions." }, { "code": null, "e": 1053, "s": 956, "text": "Rules of surds :When a surd is multiplied by a rational number then it is known as a mixed surd." }, { "code": null, "e": 1183, "s": 1053, "text": "Example – 2√2, where 2 is a rational number and √2 is a surd. Here x, y used in the rules are decimal numbers as follows. " }, { "code": null, "e": 1209, "s": 1183, "text": "Rules of indices : " }, { "code": null, "e": 1298, "s": 1209, "text": "Other Rules :Some other rules are used in solving surds and indices problems as follows." }, { "code": null, "e": 1439, "s": 1298, "text": "// From 1 to 6 rules covered in table.\n7) x m = x n then m=n and a≠ 0,1,-1.\n8) x m = y m then \n x = y if m is even \n x= y, if m is odd" }, { "code": null, "e": 1483, "s": 1439, "text": "Basic problems based on surds and indices :" }, { "code": null, "e": 1530, "s": 1483, "text": "Question-1 : Which of the following is a surd?" }, { "code": null, "e": 1593, "s": 1530, "text": "a) 2√36 b) 5√32 c) 6√729 d) 3√25" }, { "code": null, "e": 1631, "s": 1593, "text": "Solution – An answer is an option (d)" }, { "code": null, "e": 1713, "s": 1631, "text": "Explanation -\n3√25= (25)1/3 = 2.92401773821... which is irrational So it is surd." }, { "code": null, "e": 1735, "s": 1713, "text": "Question-2 :Find √√√3" }, { "code": null, "e": 1779, "s": 1735, "text": "a) 31/3 b) 31/4 c) 31/6 d) 31/8 " }, { "code": null, "e": 1818, "s": 1779, "text": "Solution – An answer is an option (d) " }, { "code": null, "e": 1917, "s": 1818, "text": "Explanation -\n ((3 1/2)1/2) 1/2) = 31/2 × 1/2 ×1/2 = 3 1/8 according to rule number 5 in indices." }, { "code": null, "e": 1978, "s": 1917, "text": "Question-3 : If (4/5)3 (4/5)-6= (4/5)2x-1, the value of x is" }, { "code": null, "e": 2024, "s": 1978, "text": "a) -2 b)2 c) -1 d)1" }, { "code": null, "e": 2060, "s": 2024, "text": "Solution – The answer is option (c)" }, { "code": null, "e": 2223, "s": 2060, "text": "Explanation - \nLHS = (4/5)3 (4/5)-6= (4/5)3-6 = (4/5)-3 \nRHS = (4/5)2x-1\nAccording to question LHS = RHS \n⇒ (4/5)-3 = (4/5)2x-1\n⇒ 2x-1 = -3\n⇒ 2x = -2\n⇒ x = -1" }, { "code": null, "e": 2237, "s": 2223, "text": "Question-4 : " }, { "code": null, "e": 2261, "s": 2237, "text": "34x+1 = 1/27, then x is" }, { "code": null, "e": 2272, "s": 2261, "text": "Solution –" }, { "code": null, "e": 2329, "s": 2272, "text": "34x+1 = (1/3)3\n⇒34x+1 = 3-3\n⇒4x+1 = -3\n⇒4x= -4 \n⇒x = -1" }, { "code": null, "e": 2395, "s": 2329, "text": "Question-5 : Find the smallest among 2 1/12, 3 1/72, 41/24,61/36." }, { "code": null, "e": 2426, "s": 2395, "text": "Solution – The answer is 31/72" }, { "code": null, "e": 2581, "s": 2426, "text": "Explanation – As the exponents of all numbers are infractions, therefore multiply each exponent by LCM of all the exponents. The LCM of all numbers is 72." }, { "code": null, "e": 2665, "s": 2581, "text": "2(1/12 × 72) = 26 = 64\n3(1/72 ×72) = 3\n4(1/24 ×72) = 43 = 64\n6 (1/36 ×72) = 62 = 36" }, { "code": null, "e": 2718, "s": 2665, "text": "Question-6 :The greatest among 2400, 3300,5200,6200." }, { "code": null, "e": 2759, "s": 2718, "text": "a) 2400 b)3300 c)5200 d)6200 " }, { "code": null, "e": 2797, "s": 2759, "text": "Solution – An answer is an option (d)" }, { "code": null, "e": 2983, "s": 2797, "text": "Explanation –As the power of each number is large, and it is very difficult to compare them, therefore we will divide each exponent by a common factor(i.e. take HCF of each exponent). " }, { "code": null, "e": 3124, "s": 2983, "text": "The HCF of all exponents is 100.\n2400/100 = 24 = 8.\n3300/100 = 33 = 27 \n5200/100 = 52 = 25\n6200/100= 62 = 36\nSo 6200 is largest among all." }, { "code": null, "e": 3131, "s": 3124, "text": "Picked" }, { "code": null, "e": 3155, "s": 3131, "text": "Engineering Mathematics" }, { "code": null, "e": 3163, "s": 3155, "text": "GATE CS" }, { "code": null, "e": 3261, "s": 3163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3320, "s": 3261, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 3341, "s": 3320, "text": "Activation Functions" }, { "code": null, "e": 3366, "s": 3341, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 3385, "s": 3366, "text": "Modular Arithmetic" }, { "code": null, "e": 3426, "s": 3385, "text": "Mathematics | Introduction of Set theory" }, { "code": null, "e": 3446, "s": 3426, "text": "Layers of OSI Model" }, { "code": null, "e": 3470, "s": 3446, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3483, "s": 3470, "text": "TCP/IP Model" }, { "code": null, "e": 3510, "s": 3483, "text": "Types of Operating Systems" } ]
How to create a navbar in Bootstrap ?
06 Aug, 2021 Bootstrap Navbar is a navigation header that is located at the top of the webpage which can be extended or collapsed, depending on the screen size. Bootstrap Navbar is used to create responsive navigation for our website. We can create standard navigation bar with <nav class=”navbar navbar-default”>. We can also create different navbar variations such as navbars with drop-down menus and search boxes and a fixed navbar with minimal effort. Below is the procedure to implement a simple static navbar with navigation links. Step by Step Guide to implement Navbar in Bootstrap Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js”></script> Step 2: Add <nav> tag with .navbar and .navbar-default class in <body> tag. <nav class="navbar navbar-default"> <!-- Navbar content goes here --> </nav> Step 3: Add <div> tag with class container-fluid and also add another <div> with class .navbar-header to give name to header and add navigation list after closing <div> tag. Note: The class .navbar-header is optional. <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> </div> We have successfully implemented Navbar in Bootstrap. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap NavBar Example</title> <meta charset="utf-8" /> <!-- Include bootstrap, CSS and jQuery CDN --> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script></head> <body> <!-- Add <nav> tag with .navbar and .navbar-default class --> <nav class="navbar navbar-default"> <!-- Add navbar content --> <div class="container-fluid"> <!-- Include .navbar-header class in <div> (optional)--> <div class="navbar-header"> <a class="navbar-brand" href="#"> GeeksforGeeks </a> </div> <!-- Include navbar list --> <ul class="nav navbar-nav"> <li class="active"><a href="#"> Home </a></li> <li><a href="#">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> </div> </nav> <!-- Sample page content --> <div class="container"> <h3>Bootstrap Navbar Example</h3> <p> A navigation bar is a navigation header placed at the top of the page. </p> </div></body> </html> Output: Bootstrap-4 Bootstrap-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Aug, 2021" }, { "code": null, "e": 276, "s": 53, "text": "Bootstrap Navbar is a navigation header that is located at the top of the webpage which can be extended or collapsed, depending on the screen size. Bootstrap Navbar is used to create responsive navigation for our website. " }, { "code": null, "e": 580, "s": 276, "text": "We can create standard navigation bar with <nav class=”navbar navbar-default”>. We can also create different navbar variations such as navbars with drop-down menus and search boxes and a fixed navbar with minimal effort. Below is the procedure to implement a simple static navbar with navigation links." }, { "code": null, "e": 632, "s": 580, "text": "Step by Step Guide to implement Navbar in Bootstrap" }, { "code": null, "e": 739, "s": 632, "text": "Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 1021, "s": 741, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js”></script>" }, { "code": null, "e": 1097, "s": 1021, "text": "Step 2: Add <nav> tag with .navbar and .navbar-default class in <body> tag." }, { "code": null, "e": 1178, "s": 1097, "text": "<nav class=\"navbar navbar-default\">\n <!-- Navbar content goes here -->\n</nav>" }, { "code": null, "e": 1352, "s": 1178, "text": "Step 3: Add <div> tag with class container-fluid and also add another <div> with class .navbar-header to give name to header and add navigation list after closing <div> tag." }, { "code": null, "e": 1396, "s": 1352, "text": "Note: The class .navbar-header is optional." }, { "code": null, "e": 1721, "s": 1396, "text": "<div class=\"container-fluid\">\n <div class=\"navbar-header\">\n <a class=\"navbar-brand\" href=\"#\">WebSiteName</a>\n </div>\n\n <ul class=\"nav navbar-nav\">\n <li class=\"active\"><a href=\"#\">Home</a></li>\n <li><a href=\"#\">Page 1</a></li>\n <li><a href=\"#\">Page 2</a></li>\n <li><a href=\"#\">Page 3</a></li>\n </ul>\n</div>" }, { "code": null, "e": 1775, "s": 1721, "text": "We have successfully implemented Navbar in Bootstrap." }, { "code": null, "e": 1784, "s": 1775, "text": "Example:" }, { "code": null, "e": 1789, "s": 1784, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap NavBar Example</title> <meta charset=\"utf-8\" /> <!-- Include bootstrap, CSS and jQuery CDN --> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script></head> <body> <!-- Add <nav> tag with .navbar and .navbar-default class --> <nav class=\"navbar navbar-default\"> <!-- Add navbar content --> <div class=\"container-fluid\"> <!-- Include .navbar-header class in <div> (optional)--> <div class=\"navbar-header\"> <a class=\"navbar-brand\" href=\"#\"> GeeksforGeeks </a> </div> <!-- Include navbar list --> <ul class=\"nav navbar-nav\"> <li class=\"active\"><a href=\"#\"> Home </a></li> <li><a href=\"#\">Page 1</a></li> <li><a href=\"#\">Page 2</a></li> <li><a href=\"#\">Page 3</a></li> </ul> </div> </nav> <!-- Sample page content --> <div class=\"container\"> <h3>Bootstrap Navbar Example</h3> <p> A navigation bar is a navigation header placed at the top of the page. </p> </div></body> </html>", "e": 3387, "s": 1789, "text": null }, { "code": null, "e": 3395, "s": 3387, "text": "Output:" }, { "code": null, "e": 3407, "s": 3395, "text": "Bootstrap-4" }, { "code": null, "e": 3427, "s": 3407, "text": "Bootstrap-Questions" }, { "code": null, "e": 3434, "s": 3427, "text": "Picked" }, { "code": null, "e": 3444, "s": 3434, "text": "Bootstrap" }, { "code": null, "e": 3449, "s": 3444, "text": "HTML" }, { "code": null, "e": 3466, "s": 3449, "text": "Web Technologies" }, { "code": null, "e": 3471, "s": 3466, "text": "HTML" } ]
How to auto-save data when application is offline in Angular 8?
27 Jun, 2020 Auto-saving the data comes into action when your application needs to work offline and the CDN(content delivery network) will fail. In this article, we are going to access the required steps that are intended to save your application locally when offline and submit it once a connection has prevailed. Environment Setup: Before comprising the libraries which make your app work offline make sure to download the actual file (example: angular.js). For instance, we’ll have a basic file named app.js that contains our Angular code, and a html document which is index.html which contains all our html code. <!DOCTYPE html> <html lang="en"><head> <meta charset="UTF-8"> <title>Offline AutoSave data in Angular 8</title></head><body data-ng-app="app"> <div data-ng-controller="MainController"> <!-- Main Form --> </div> <script src="angular.js"></script><script src="./app.js"></script> </body></html> Hence, let us take an example of data entry application and build a form which collects data about dogs. if you’re studying about the respective breed of the dog, your application may go offline occasionally depending on your situated location. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Offline AutoSave data in Angular 8</title></head><body data-ng-app="app"> <div data-ng-controller="MainController"> <form name="form.DogBreedForm" novalidate data-ng-submit="save()"> <label for="commonIdentity"> Common Identity</label> <input id="commonIdentity" type="text" data-ng-model="formData.commonIdentity"> <label for="breedName">Breed</label> <select name="breedName" id="breedName" data-ng-model="formData.breedName"> <option value="first">First</option> <option value="second">Second</option> <option value="third">Third</option> </select> <label for="BreedFeatures"> Breed Features</label> <input id="BreedFeatures" type="text" data-ng-model="formData.BreedFeatures"> <button type="submit">Save Locally</button> <button type="button" data-ng-click="sync()">Sync</button> </form> </div> <script src="./angular.js"></script><script src="./app.js"></script> </body></html> Note that, we have added a new term data-ng-model for all the inputs. Lets create a parent object called $scope.formData for our input data models. $scope.save function will handle the data saving instance to the local storage and $scope.sync will handle the submitting operation when the application goes online. The Output(When Offline): Page Output (Enter the Values) Now, we are offline hence it will show us the below. Let’s now deep-dive into performing the functions and storing the data offline once the user enters the data in the form. Save function– LocalStorage will save our data in string key-value pairs. The data which is being stored in the localStorage will accept the Strings. Below in save function, we declare a stringCopy variable, and a lcKey property on $scope.formData. We use timestamp which is a unique identifier. JSON File JSON format file is often used for imparting structured data over a network connection. It primarily transmits the data between a server and a web application. Hence while parsing the stringed JSON, if it is not valid, it throws an exception. In order to avoid these exceptions let’s make use of tr-catch block for handling it. JSON stands for JavaScript Object Notation is an independent language and json is a format of data which agreeably permits us to share data with any platform. It distributes the data to any kind of medium and linking JSON is uncomplicated. stringCopy = JSON.stringify($scope.formData); Parsing localStorage and saving to server- Saving your data to the local storage when you are offline using JSON.stringify. Now we use JSON.parse to sync the data to the database when your application goes online. Note–We Included a button to our html document to save and submit your data to the local storage inside the form section. app.js File App.js represents your main javascript file to design your NodeJs applications. The file have to be stored in the main app root directory. The file can also contain a different name(ex: main.js ). It builds an interface between nodejs functionalities and html code over your web application. angular.module('app', []) .controller('MainController', ['$scope', function ($scope) { var fetchAll = function () { var finds = []; if (localStorage.length === 0) { return []; } for (var i=0;i<localStorage.length;i++) { try { finds.push(JSON.parse(localStorage.getItem(localStorage.key(i)))); } catch (err) { console.log(err); } } return finds; }; $scope.formData = {}; $scope.save = function () { var stringCopy = ''; $scope.formData.lcKey = Date.now().toString(); try { stringCopy = JSON.stringify($scope.formData); } catch (err) { console.debug(err); return; } localStorage[$scope.formData.lcKey] = stringCopy; }; $scope.sync = function () { var records = fetchAll(); if (navigator && navigator.onLine && records.length) { records.forEach(function (find, idx) $http({ url: '/api/finds', method: 'POST', data: find }).then(function (res) { localStorage.removeItem(find.lcKey.toString()); ecords.splice(idx); //remove from records array }, function (err) { //error handling - service call failures }); }); } else { //error handling - Alert the user for patience } }; }]); Finally after syncing the data, The Output(When online): We used the fetchAll function to automatically detect the connection and save your data and sync it to the database. We’ll call this in the in the submit function. Once the connection is established the data which is being stored in the localStorage will be synced by looping through the records stored one-by-one and submit them to the database. Hence this article helps you to store your data locally to the localStorage when your application is offline and sync the data to the database when it gets online using $scope functions for the input and parsing them. AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jun, 2020" }, { "code": null, "e": 330, "s": 28, "text": "Auto-saving the data comes into action when your application needs to work offline and the CDN(content delivery network) will fail. In this article, we are going to access the required steps that are intended to save your application locally when offline and submit it once a connection has prevailed." }, { "code": null, "e": 349, "s": 330, "text": "Environment Setup:" }, { "code": null, "e": 475, "s": 349, "text": "Before comprising the libraries which make your app work offline make sure to download the actual file (example: angular.js)." }, { "code": null, "e": 632, "s": 475, "text": "For instance, we’ll have a basic file named app.js that contains our Angular code, and a html document which is index.html which contains all our html code." }, { "code": "<!DOCTYPE html> <html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Offline AutoSave data in Angular 8</title></head><body data-ng-app=\"app\"> <div data-ng-controller=\"MainController\"> <!-- Main Form --> </div> <script src=\"angular.js\"></script><script src=\"./app.js\"></script> </body></html>", "e": 973, "s": 632, "text": null }, { "code": null, "e": 1218, "s": 973, "text": "Hence, let us take an example of data entry application and build a form which collects data about dogs. if you’re studying about the respective breed of the dog, your application may go offline occasionally depending on your situated location." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Offline AutoSave data in Angular 8</title></head><body data-ng-app=\"app\"> <div data-ng-controller=\"MainController\"> <form name=\"form.DogBreedForm\" novalidate data-ng-submit=\"save()\"> <label for=\"commonIdentity\"> Common Identity</label> <input id=\"commonIdentity\" type=\"text\" data-ng-model=\"formData.commonIdentity\"> <label for=\"breedName\">Breed</label> <select name=\"breedName\" id=\"breedName\" data-ng-model=\"formData.breedName\"> <option value=\"first\">First</option> <option value=\"second\">Second</option> <option value=\"third\">Third</option> </select> <label for=\"BreedFeatures\"> Breed Features</label> <input id=\"BreedFeatures\" type=\"text\" data-ng-model=\"formData.BreedFeatures\"> <button type=\"submit\">Save Locally</button> <button type=\"button\" data-ng-click=\"sync()\">Sync</button> </form> </div> <script src=\"./angular.js\"></script><script src=\"./app.js\"></script> </body></html>", "e": 2555, "s": 1218, "text": null }, { "code": null, "e": 2704, "s": 2555, "text": "Note that, we have added a new term data-ng-model for all the inputs. Lets create a parent object called $scope.formData for our input data models. " }, { "code": null, "e": 2870, "s": 2704, "text": "$scope.save function will handle the data saving instance to the local storage and $scope.sync will handle the submitting operation when the application goes online." }, { "code": null, "e": 2896, "s": 2870, "text": "The Output(When Offline):" }, { "code": null, "e": 2927, "s": 2896, "text": "Page Output (Enter the Values)" }, { "code": null, "e": 2980, "s": 2927, "text": "Now, we are offline hence it will show us the below." }, { "code": null, "e": 3102, "s": 2980, "text": "Let’s now deep-dive into performing the functions and storing the data offline once the user enters the data in the form." }, { "code": null, "e": 3177, "s": 3102, "text": "Save function– LocalStorage will save our data in string key-value pairs. " }, { "code": null, "e": 3399, "s": 3177, "text": "The data which is being stored in the localStorage will accept the Strings. Below in save function, we declare a stringCopy variable, and a lcKey property on $scope.formData. We use timestamp which is a unique identifier." }, { "code": null, "e": 3409, "s": 3399, "text": "JSON File" }, { "code": null, "e": 3737, "s": 3409, "text": "JSON format file is often used for imparting structured data over a network connection. It primarily transmits the data between a server and a web application. Hence while parsing the stringed JSON, if it is not valid, it throws an exception. In order to avoid these exceptions let’s make use of tr-catch block for handling it." }, { "code": null, "e": 3977, "s": 3737, "text": "JSON stands for JavaScript Object Notation is an independent language and json is a format of data which agreeably permits us to share data with any platform. It distributes the data to any kind of medium and linking JSON is uncomplicated." }, { "code": null, "e": 4024, "s": 3977, "text": "stringCopy = JSON.stringify($scope.formData);\n" }, { "code": null, "e": 4241, "s": 4024, "text": " Parsing localStorage and saving to server- Saving your data to the local storage when you are offline using JSON.stringify. Now we use JSON.parse to sync the data to the database when your application goes online. " }, { "code": null, "e": 4363, "s": 4241, "text": "Note–We Included a button to our html document to save and submit your data to the local storage inside the form section." }, { "code": null, "e": 4375, "s": 4363, "text": "app.js File" }, { "code": null, "e": 4667, "s": 4375, "text": "App.js represents your main javascript file to design your NodeJs applications. The file have to be stored in the main app root directory. The file can also contain a different name(ex: main.js ). It builds an interface between nodejs functionalities and html code over your web application." }, { "code": "angular.module('app', []) .controller('MainController', ['$scope', function ($scope) { var fetchAll = function () { var finds = []; if (localStorage.length === 0) { return []; } for (var i=0;i<localStorage.length;i++) { try { finds.push(JSON.parse(localStorage.getItem(localStorage.key(i)))); } catch (err) { console.log(err); } } return finds; }; $scope.formData = {}; $scope.save = function () { var stringCopy = ''; $scope.formData.lcKey = Date.now().toString(); try { stringCopy = JSON.stringify($scope.formData); } catch (err) { console.debug(err); return; } localStorage[$scope.formData.lcKey] = stringCopy; }; $scope.sync = function () { var records = fetchAll(); if (navigator && navigator.onLine && records.length) { records.forEach(function (find, idx) $http({ url: '/api/finds', method: 'POST', data: find }).then(function (res) { localStorage.removeItem(find.lcKey.toString()); ecords.splice(idx); //remove from records array }, function (err) { //error handling - service call failures }); }); } else { //error handling - Alert the user for patience } }; }]);", "e": 6626, "s": 4667, "text": null }, { "code": null, "e": 6683, "s": 6626, "text": "Finally after syncing the data, The Output(When online):" }, { "code": null, "e": 7030, "s": 6683, "text": "We used the fetchAll function to automatically detect the connection and save your data and sync it to the database. We’ll call this in the in the submit function. Once the connection is established the data which is being stored in the localStorage will be synced by looping through the records stored one-by-one and submit them to the database." }, { "code": null, "e": 7248, "s": 7030, "text": "Hence this article helps you to store your data locally to the localStorage when your application is offline and sync the data to the database when it gets online using $scope functions for the input and parsing them." }, { "code": null, "e": 7263, "s": 7248, "text": "AngularJS-Misc" }, { "code": null, "e": 7270, "s": 7263, "text": "Picked" }, { "code": null, "e": 7280, "s": 7270, "text": "AngularJS" }, { "code": null, "e": 7297, "s": 7280, "text": "Web Technologies" }, { "code": null, "e": 7395, "s": 7297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7419, "s": 7395, "text": "Routing in Angular 9/10" }, { "code": null, "e": 7454, "s": 7419, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 7478, "s": 7454, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 7531, "s": 7478, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 7580, "s": 7531, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 7613, "s": 7580, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7675, "s": 7613, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7736, "s": 7675, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7786, "s": 7736, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
YAML - Introduction
YAML Ain't Markup Language is a data serialization language that matches user’s expectations about data. It designed to be human friendly and works perfectly with other programming languages. It is useful to manage data and includes Unicode printable characters. This chapter will give you an introduction to YAML and gives you an idea about its features. Consider the text shown below − Quick brown fox jumped over the lazy dog. The YAML text for this will be represented as shown below − yaml.load(Quick brown fox jumped over the lazy dog.) >>'Quick brown fox jumped over the lazy dog.' Note that YAML takes the value in string format and represents the output as mentioned above. Let us understand the formats in YAML with the help of the following examples − Consider the following point number of “pi”, which has a value of 3.1415926. In YAML, it is represented as a floating number as shown below − >>> yaml.load('3.1415926536') 3.1415926536 Suppose, multiple values are to be loaded in specific data structure as mentioned below − eggs ham spam French basil salmon terrine When you load this into YAML, the values are taken in an array data structure which is a form of list. The output is as shown below − >>> yaml.load(''' - eggs - ham - spam - French basil salmon terrine ''') ['eggs', 'ham', 'spam', 'French basil salmon terrine'] YAML includes a markup language with important construct, to distinguish data-oriented language with the document markup. The design goals and features of YAML are given below − Matches native data structures of agile methodology and its languages such as Perl, Python, PHP, Ruby and JavaScript Matches native data structures of agile methodology and its languages such as Perl, Python, PHP, Ruby and JavaScript YAML data is portable between programming languages YAML data is portable between programming languages Includes data consistent data model Includes data consistent data model Easily readable by humans Easily readable by humans Supports one-direction processing Supports one-direction processing Ease of implementation and usage Ease of implementation and usage
[ { "code": null, "e": 2538, "s": 2182, "text": "YAML Ain't Markup Language is a data serialization language that matches user’s expectations about data. It designed to be human friendly and works perfectly with other programming languages. It is useful to manage data and includes Unicode printable characters. This chapter will give you an introduction to YAML and gives you an idea about its features." }, { "code": null, "e": 2570, "s": 2538, "text": "Consider the text shown below −" }, { "code": null, "e": 2613, "s": 2570, "text": "Quick brown fox jumped over the lazy dog.\n" }, { "code": null, "e": 2673, "s": 2613, "text": "The YAML text for this will be represented as shown below −" }, { "code": null, "e": 2772, "s": 2673, "text": "yaml.load(Quick brown fox jumped over the lazy dog.)\n>>'Quick brown fox jumped over the lazy dog.'" }, { "code": null, "e": 2866, "s": 2772, "text": "Note that YAML takes the value in string format and represents the output as mentioned above." }, { "code": null, "e": 2946, "s": 2866, "text": "Let us understand the formats in YAML with the help of the following examples −" }, { "code": null, "e": 3088, "s": 2946, "text": "Consider the following point number of “pi”, which has a value of 3.1415926. In YAML, it is represented as a floating number as shown below −" }, { "code": null, "e": 3131, "s": 3088, "text": ">>> yaml.load('3.1415926536')\n3.1415926536" }, { "code": null, "e": 3221, "s": 3131, "text": "Suppose, multiple values are to be loaded in specific data structure as mentioned below −" }, { "code": null, "e": 3264, "s": 3221, "text": "eggs\nham\nspam\nFrench basil salmon terrine\n" }, { "code": null, "e": 3398, "s": 3264, "text": "When you load this into YAML, the values are taken in an array data structure which is a form of list. The output is as shown below −" }, { "code": null, "e": 3542, "s": 3398, "text": ">>> yaml.load('''\n - eggs\n - ham\n - spam\n - French basil salmon terrine\n ''')\n['eggs', 'ham', 'spam', 'French basil salmon terrine']\n" }, { "code": null, "e": 3720, "s": 3542, "text": "YAML includes a markup language with important construct, to distinguish data-oriented language with the document markup. The design goals and features of YAML are given below −" }, { "code": null, "e": 3837, "s": 3720, "text": "Matches native data structures of agile methodology and its languages such as Perl, Python, PHP, Ruby and JavaScript" }, { "code": null, "e": 3954, "s": 3837, "text": "Matches native data structures of agile methodology and its languages such as Perl, Python, PHP, Ruby and JavaScript" }, { "code": null, "e": 4006, "s": 3954, "text": "YAML data is portable between programming languages" }, { "code": null, "e": 4058, "s": 4006, "text": "YAML data is portable between programming languages" }, { "code": null, "e": 4094, "s": 4058, "text": "Includes data consistent data model" }, { "code": null, "e": 4130, "s": 4094, "text": "Includes data consistent data model" }, { "code": null, "e": 4156, "s": 4130, "text": "Easily readable by humans" }, { "code": null, "e": 4182, "s": 4156, "text": "Easily readable by humans" }, { "code": null, "e": 4216, "s": 4182, "text": "Supports one-direction processing" }, { "code": null, "e": 4250, "s": 4216, "text": "Supports one-direction processing" }, { "code": null, "e": 4283, "s": 4250, "text": "Ease of implementation and usage" } ]
Spring ApplicationContext Container
The Application Context is Spring's advanced container. Similar to BeanFactory, it can load bean definitions, wire beans together, and dispense beans upon request. Additionally, it adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by org.springframework.context.ApplicationContext interface. The ApplicationContext includes all functionality of the BeanFactory, It is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications. The most commonly used ApplicationContext implementations are − FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor. FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor. ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH. ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH. WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application. WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application. We already have seen an example on ClassPathXmlApplicationContext container in Spring Hello World Example, and we will talk more about XmlWebApplicationContext in a separate chapter when we will discuss web-based Spring applications. So let us see one example on FileSystemXmlApplicationContext. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application − Here is the content of HelloWorld.java file − package com.tutorialspoint; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } } Following is the content of the second file MainApp.java − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Users/ZARA/workspace/HelloSpring/src/Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); } } Following two important points should be noted about the main program − The first step is to create factory object where we used framework APIFileSystemXmlApplicationContext to create the factory bean after loading the bean configuration file from the given path. TheFileSystemXmlApplicationContext() API takes care of creating and initializing all the objects ie. beans mentioned in the XML bean configuration file. The first step is to create factory object where we used framework APIFileSystemXmlApplicationContext to create the factory bean after loading the bean configuration file from the given path. TheFileSystemXmlApplicationContext() API takes care of creating and initializing all the objects ie. beans mentioned in the XML bean configuration file. The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method. The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method. Following is the content of the bean configuration file Beans.xml <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"> <property name = "message" value = "Hello World!"/> </bean> </beans> Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Your Message : Hello World!
[ { "code": null, "e": 2886, "s": 2426, "text": "The Application Context is Spring's advanced container. Similar to BeanFactory, it can load bean definitions, wire beans together, and dispense beans upon request. Additionally, it adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by org.springframework.context.ApplicationContext interface." }, { "code": null, "e": 3111, "s": 2886, "text": "The ApplicationContext includes all functionality of the BeanFactory, It is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications." }, { "code": null, "e": 3175, "s": 3111, "text": "The most commonly used ApplicationContext implementations are −" }, { "code": null, "e": 3371, "s": 3175, "text": "FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor." }, { "code": null, "e": 3567, "s": 3371, "text": "FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor." }, { "code": null, "e": 3849, "s": 3567, "text": "ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH." }, { "code": null, "e": 4131, "s": 3849, "text": "ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH." }, { "code": null, "e": 4253, "s": 4131, "text": "WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application." }, { "code": null, "e": 4375, "s": 4253, "text": "WebXmlApplicationContext − This container loads the XML file with definitions of all beans from within a web application." }, { "code": null, "e": 4671, "s": 4375, "text": "We already have seen an example on ClassPathXmlApplicationContext container in Spring Hello World Example, and we will talk more about XmlWebApplicationContext in a separate chapter when we will discuss web-based Spring applications. So let us see one example on FileSystemXmlApplicationContext." }, { "code": null, "e": 4776, "s": 4671, "text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 4822, "s": 4776, "text": "Here is the content of HelloWorld.java file −" }, { "code": null, "e": 5075, "s": 4822, "text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n}" }, { "code": null, "e": 5134, "s": 5075, "text": "Following is the content of the second file MainApp.java −" }, { "code": null, "e": 5602, "s": 5134, "text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.FileSystemXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new FileSystemXmlApplicationContext\n (\"C:/Users/ZARA/workspace/HelloSpring/src/Beans.xml\");\n \n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n }\n}" }, { "code": null, "e": 5674, "s": 5602, "text": "Following two important points should be noted about the main program −" }, { "code": null, "e": 6019, "s": 5674, "text": "The first step is to create factory object where we used framework APIFileSystemXmlApplicationContext to create the factory bean after loading the bean configuration file from the given path. TheFileSystemXmlApplicationContext() API takes care of creating and initializing all the objects ie. beans mentioned in the XML bean configuration file." }, { "code": null, "e": 6364, "s": 6019, "text": "The first step is to create factory object where we used framework APIFileSystemXmlApplicationContext to create the factory bean after loading the bean configuration file from the given path. TheFileSystemXmlApplicationContext() API takes care of creating and initializing all the objects ie. beans mentioned in the XML bean configuration file." }, { "code": null, "e": 6638, "s": 6364, "text": "The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method." }, { "code": null, "e": 6912, "s": 6638, "text": "The second step is used to get the required bean using getBean() method of the created context. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have an object, you can use this object to call any class method." }, { "code": null, "e": 6978, "s": 6912, "text": "Following is the content of the bean configuration file Beans.xml" }, { "code": null, "e": 7429, "s": 6978, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>" }, { "code": null, "e": 7613, "s": 7429, "text": "Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −" } ]
Java Program to Count Inversions in an array | Set 1 (Using Merge Sort)
07 Dec, 2021 Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example: Input: arr[] = {8, 4, 2, 1} Output: 6 Explanation: Given array has six inversions: (8, 4), (4, 2), (8, 2), (8, 1), (4, 1), (2, 1). Input: arr[] = {3, 1, 2} Output: 2 Explanation: Given array has two inversions: (3, 1), (3, 2) METHOD 1 (Simple): Approach: Traverse through the array, and for every index, find the number of smaller elements on its right side of the array. This can be done using a nested loop. Sum up the counts for all index in the array and print the sum. Algorithm: Traverse through the array from start to endFor every element, find the count of elements smaller than the current number up to that index using another loop.Sum up the count of inversion for every index.Print the count of inversions. Traverse through the array from start to end For every element, find the count of elements smaller than the current number up to that index using another loop. Sum up the count of inversion for every index. Print the count of inversions. Implementation: Java // Java program to count inversions // in an arrayclass Test { static int arr[] = new int[] {1, 20, 6, 4, 5}; static int getInvCount(int n) { int inv_count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] > arr[j]) inv_count++; return inv_count; } // Driver code public static void main(String[] args) { System.out.println("Number of inversions are " + getInvCount(arr.length)); }} Output: Number of inversions are 5 Complexity Analysis: Time Complexity: O(n^2), Two nested loops are needed to traverse the array from start to end, so the Time complexity is O(n^2) Space Complexity:O(1), No extra space is required. METHOD 2(Enhance Merge Sort): Approach: Suppose the number of inversions in the left half and right half of the array (let be inv1 and inv2); what kinds of inversions are not accounted for in Inv1 + Inv2? The answer is – the inversions that need to be counted during the merge step. Therefore, to get the total number of inversions that needs to be added are the number of inversions in the left subarray, right subarray, and merge(). How to get the number of inversions in merge()? In merge process, let i is used for indexing left sub-array and j for right sub-array. At any step in merge(), if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j] The complete picture: Algorithm: The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached.Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j].Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two.The base case of recursion is when there is only one element in the given half.Print the answer The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached. Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j]. Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two. The base case of recursion is when there is only one element in the given half. Print the answer Implementation: Java // Java implementation of the approachimport java.util.Arrays; public class GFG { // Function to count the number of inversions // during the merge process private static int mergeAndCount(int[] arr, int l, int m, int r) { // Left subarray int[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l, swaps = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(int[] arr, int l, int r) { // Keeps track of the inversion count at a // particular node of the recursion tree int count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left // subarray count + right subarray // count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } // Driver code public static void main(String[] args) { int[] arr = {1, 20, 6, 4, 5}; System.out.println( mergeSortAndCount(arr, 0, arr.length - 1)); }}// This code is contributed by Pradip Basak Output: Number of inversions are 5 Complexity Analysis: Time Complexity: O(n log n), The algorithm used is divide and conquer, So in each level, one full array traversal is needed, and there are log n levels, so the time complexity is O(n log n). Space Complexity: O(n), Temporary array. Note that the above code modifies (or sorts) the input array. If we want to count only inversions, we need to create a copy of the original array and call mergeSort() on the copy to preserve the original array’s order. Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Convert Char to String in Java? How to Get Elements By Index from HashSet in Java? Java Program to Write into a File How to Write Data into Excel Sheet using Java? Java Program to Read a File to String Comparing two ArrayList In Java SHA-1 Hash Java Program to Find Sum of Array Elements Java Program to Convert File to a Byte Array
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Dec, 2021" }, { "code": null, "e": 391, "s": 52, "text": "Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example: " }, { "code": null, "e": 619, "s": 391, "text": "Input: arr[] = {8, 4, 2, 1}\nOutput: 6\nExplanation: Given array has six inversions:\n(8, 4), (4, 2), (8, 2), (8, 1), (4, 1), (2, 1).\n\nInput: arr[] = {3, 1, 2}\nOutput: 2\nExplanation: Given array has two inversions:\n(3, 1), (3, 2) " }, { "code": null, "e": 640, "s": 619, "text": "METHOD 1 (Simple): " }, { "code": null, "e": 869, "s": 640, "text": "Approach: Traverse through the array, and for every index, find the number of smaller elements on its right side of the array. This can be done using a nested loop. Sum up the counts for all index in the array and print the sum." }, { "code": null, "e": 880, "s": 869, "text": "Algorithm:" }, { "code": null, "e": 1115, "s": 880, "text": "Traverse through the array from start to endFor every element, find the count of elements smaller than the current number up to that index using another loop.Sum up the count of inversion for every index.Print the count of inversions." }, { "code": null, "e": 1160, "s": 1115, "text": "Traverse through the array from start to end" }, { "code": null, "e": 1275, "s": 1160, "text": "For every element, find the count of elements smaller than the current number up to that index using another loop." }, { "code": null, "e": 1322, "s": 1275, "text": "Sum up the count of inversion for every index." }, { "code": null, "e": 1353, "s": 1322, "text": "Print the count of inversions." }, { "code": null, "e": 1369, "s": 1353, "text": "Implementation:" }, { "code": null, "e": 1374, "s": 1369, "text": "Java" }, { "code": "// Java program to count inversions // in an arrayclass Test { static int arr[] = new int[] {1, 20, 6, 4, 5}; static int getInvCount(int n) { int inv_count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] > arr[j]) inv_count++; return inv_count; } // Driver code public static void main(String[] args) { System.out.println(\"Number of inversions are \" + getInvCount(arr.length)); }}", "e": 1928, "s": 1374, "text": null }, { "code": null, "e": 1936, "s": 1928, "text": "Output:" }, { "code": null, "e": 1964, "s": 1936, "text": " Number of inversions are 5" }, { "code": null, "e": 1986, "s": 1964, "text": "Complexity Analysis: " }, { "code": null, "e": 2113, "s": 1986, "text": "Time Complexity: O(n^2), Two nested loops are needed to traverse the array from start to end, so the Time complexity is O(n^2)" }, { "code": null, "e": 2164, "s": 2113, "text": "Space Complexity:O(1), No extra space is required." }, { "code": null, "e": 2195, "s": 2164, "text": "METHOD 2(Enhance Merge Sort): " }, { "code": null, "e": 2600, "s": 2195, "text": "Approach: Suppose the number of inversions in the left half and right half of the array (let be inv1 and inv2); what kinds of inversions are not accounted for in Inv1 + Inv2? The answer is – the inversions that need to be counted during the merge step. Therefore, to get the total number of inversions that needs to be added are the number of inversions in the left subarray, right subarray, and merge()." }, { "code": null, "e": 2972, "s": 2600, "text": "How to get the number of inversions in merge()? In merge process, let i is used for indexing left sub-array and j for right sub-array. At any step in merge(), if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j]" }, { "code": null, "e": 2994, "s": 2972, "text": "The complete picture:" }, { "code": null, "e": 3006, "s": 2994, "text": "Algorithm: " }, { "code": null, "e": 3878, "s": 3006, "text": "The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached.Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j].Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two.The base case of recursion is when there is only one element in the given half.Print the answer" }, { "code": null, "e": 4013, "s": 3878, "text": "The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached." }, { "code": null, "e": 4430, "s": 4013, "text": "Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j]." }, { "code": null, "e": 4657, "s": 4430, "text": "Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two." }, { "code": null, "e": 4737, "s": 4657, "text": "The base case of recursion is when there is only one element in the given half." }, { "code": null, "e": 4754, "s": 4737, "text": "Print the answer" }, { "code": null, "e": 4770, "s": 4754, "text": "Implementation:" }, { "code": null, "e": 4775, "s": 4770, "text": "Java" }, { "code": "// Java implementation of the approachimport java.util.Arrays; public class GFG { // Function to count the number of inversions // during the merge process private static int mergeAndCount(int[] arr, int l, int m, int r) { // Left subarray int[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l, swaps = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(int[] arr, int l, int r) { // Keeps track of the inversion count at a // particular node of the recursion tree int count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left // subarray count + right subarray // count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } // Driver code public static void main(String[] args) { int[] arr = {1, 20, 6, 4, 5}; System.out.println( mergeSortAndCount(arr, 0, arr.length - 1)); }}// This code is contributed by Pradip Basak", "e": 6772, "s": 4775, "text": null }, { "code": null, "e": 6780, "s": 6772, "text": "Output:" }, { "code": null, "e": 6807, "s": 6780, "text": "Number of inversions are 5" }, { "code": null, "e": 6828, "s": 6807, "text": "Complexity Analysis:" }, { "code": null, "e": 7019, "s": 6828, "text": "Time Complexity: O(n log n), The algorithm used is divide and conquer, So in each level, one full array traversal is needed, and there are log n levels, so the time complexity is O(n log n)." }, { "code": null, "e": 7060, "s": 7019, "text": "Space Complexity: O(n), Temporary array." }, { "code": null, "e": 7280, "s": 7060, "text": "Note that the above code modifies (or sorts) the input array. If we want to count only inversions, we need to create a copy of the original array and call mergeSort() on the copy to preserve the original array’s order. " }, { "code": null, "e": 7294, "s": 7280, "text": "Java Programs" }, { "code": null, "e": 7392, "s": 7294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7440, "s": 7392, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 7479, "s": 7440, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 7530, "s": 7479, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 7564, "s": 7530, "text": "Java Program to Write into a File" }, { "code": null, "e": 7611, "s": 7564, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 7649, "s": 7611, "text": "Java Program to Read a File to String" }, { "code": null, "e": 7681, "s": 7649, "text": "Comparing two ArrayList In Java" }, { "code": null, "e": 7692, "s": 7681, "text": "SHA-1 Hash" }, { "code": null, "e": 7735, "s": 7692, "text": "Java Program to Find Sum of Array Elements" } ]
p5.js | changed() Function
17 Jan, 2020 The changed() function is fired whenever the value of an element gets changed. It can be used to detect changes in checkbox elements or select elements. It can also be used to attach an event listener to an element. Syntax: changed(fxn) Parameters: This function accepts a single parameter as mentioned above and described below. fxn: This is the callback function that would be called whenever a change is detected. It can be passed ‘false’, which would prevent the previous firing function to stop firing. Below examples illustrates the changed() function in p5.js: Example 1: Detecting changes in a checkbox element let red = 0;let green = 0;let blue = 0; function setup() { createCanvas(600, 300); // create input boxes redCheckbox = createCheckbox('Red', false); redCheckbox.position(20, 40) redCheckbox.changed(redChanged); greenCheckbox = createCheckbox('Green', false); greenCheckbox.position(100, 40) greenCheckbox.changed(greenChanged); blueCheckbox = createCheckbox('Blue', false); blueCheckbox.position(180, 40) blueCheckbox.changed(blueChanged);} function draw() { clear() // change the fill color based // on current rgb the values fill(red, green, blue); rect(20, 80, 300, 300); textSize(20); text("Check the boxes to change the fill color", 10, 20);} // functions for each of the colorsfunction redChanged() { if (this.checked()) red = 128; else red = 0;} function greenChanged() { if (this.checked()) green = 128; else green = 0;} function blueChanged() { if (this.checked()) blue = 128; else blue = 0;} Output: Example 2: Detecting changes in a select element let red = 0;let green = 0;let blue = 0; function setup() { createCanvas(350, 300); textSize(18) text("Select the color to change the background color", 10, 20); // create select element selectElem = createSelect(); selectElem.position(20, 40); selectElem.option('Slecet'); selectElem.option('Red'); selectElem.option('Green'); selectElem.option('Blue'); selectElem.changed(changeColor);} function changeColor() { clear(); colorVal = this.value(); if (colorVal == "Red") { background("red"); } else if (colorVal == "Green") { background("green"); } else if (colorVal == "Blue") { background("blue"); } else background(128); text("Select the color to change the background color", 10, 20);} Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/changed JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2020" }, { "code": null, "e": 244, "s": 28, "text": "The changed() function is fired whenever the value of an element gets changed. It can be used to detect changes in checkbox elements or select elements. It can also be used to attach an event listener to an element." }, { "code": null, "e": 252, "s": 244, "text": "Syntax:" }, { "code": null, "e": 265, "s": 252, "text": "changed(fxn)" }, { "code": null, "e": 358, "s": 265, "text": "Parameters: This function accepts a single parameter as mentioned above and described below." }, { "code": null, "e": 536, "s": 358, "text": "fxn: This is the callback function that would be called whenever a change is detected. It can be passed ‘false’, which would prevent the previous firing function to stop firing." }, { "code": null, "e": 596, "s": 536, "text": "Below examples illustrates the changed() function in p5.js:" }, { "code": null, "e": 647, "s": 596, "text": "Example 1: Detecting changes in a checkbox element" }, { "code": "let red = 0;let green = 0;let blue = 0; function setup() { createCanvas(600, 300); // create input boxes redCheckbox = createCheckbox('Red', false); redCheckbox.position(20, 40) redCheckbox.changed(redChanged); greenCheckbox = createCheckbox('Green', false); greenCheckbox.position(100, 40) greenCheckbox.changed(greenChanged); blueCheckbox = createCheckbox('Blue', false); blueCheckbox.position(180, 40) blueCheckbox.changed(blueChanged);} function draw() { clear() // change the fill color based // on current rgb the values fill(red, green, blue); rect(20, 80, 300, 300); textSize(20); text(\"Check the boxes to change the fill color\", 10, 20);} // functions for each of the colorsfunction redChanged() { if (this.checked()) red = 128; else red = 0;} function greenChanged() { if (this.checked()) green = 128; else green = 0;} function blueChanged() { if (this.checked()) blue = 128; else blue = 0;}", "e": 1608, "s": 647, "text": null }, { "code": null, "e": 1616, "s": 1608, "text": "Output:" }, { "code": null, "e": 1665, "s": 1616, "text": "Example 2: Detecting changes in a select element" }, { "code": "let red = 0;let green = 0;let blue = 0; function setup() { createCanvas(350, 300); textSize(18) text(\"Select the color to change the background color\", 10, 20); // create select element selectElem = createSelect(); selectElem.position(20, 40); selectElem.option('Slecet'); selectElem.option('Red'); selectElem.option('Green'); selectElem.option('Blue'); selectElem.changed(changeColor);} function changeColor() { clear(); colorVal = this.value(); if (colorVal == \"Red\") { background(\"red\"); } else if (colorVal == \"Green\") { background(\"green\"); } else if (colorVal == \"Blue\") { background(\"blue\"); } else background(128); text(\"Select the color to change the background color\", 10, 20);}", "e": 2403, "s": 1665, "text": null }, { "code": null, "e": 2411, "s": 2403, "text": "Output:" }, { "code": null, "e": 2548, "s": 2411, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 2599, "s": 2548, "text": "Reference: https://p5js.org/reference/#/p5/changed" }, { "code": null, "e": 2616, "s": 2599, "text": "JavaScript-p5.js" }, { "code": null, "e": 2627, "s": 2616, "text": "JavaScript" }, { "code": null, "e": 2644, "s": 2627, "text": "Web Technologies" }, { "code": null, "e": 2742, "s": 2644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2803, "s": 2742, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2875, "s": 2803, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2915, "s": 2875, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2968, "s": 2915, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3009, "s": 2968, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3042, "s": 3009, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3104, "s": 3042, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3165, "s": 3104, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3215, "s": 3165, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Implementation of lower_bound() and upper_bound() on Map of Pairs in C++
31 May, 2020 Prerequisite: map lower_bound() function in C++ STL, map upper_bound() function in C++ STL In this article, we will discuss the implementation of the lower_bound() and upper_bound() in the Map of pairs. lower_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in Map of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the pair whose first value is greater than or equals x and second value is greater than equals to y.If the above-mentioned criteria are not met, then it returns an iterator which points to the pair {Map.size(), 0}.Syntax:mp.lower_bound({a, b}) where, mp is the map of pairs and {a, b} whose lower_bound is to be found Syntax: mp.lower_bound({a, b}) where, mp is the map of pairs and {a, b} whose lower_bound is to be found upper_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in Map of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the pair whose first value is greater than x and second value is greater than y.If the above-mentioned criteria are not met, then it returns an iterator which points to the pair {Map.size(), 0}.Syntax:mp.upper_bound({a, b}) where, mp is the map of pairs and {a, b} whose upper_bound is to be found Syntax: mp.upper_bound({a, b}) where, mp is the map of pairs and {a, b} whose upper_bound is to be found Below is the program to demonstrate lower_bound() and upper_bound() in Map of pairs: Program 1: // C++ program to demonstrate lower_bound()// and upper_bound() in Map of Pairs #include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound( map<pair<int, int>, int>& mp, pair<int, int>& p){ // This iterator points to the // lower_bound() of given pair auto low = mp.lower_bound(p); cout << "lower_bound() for {2, 5}" << " is: {" << (*low).first.first << ", " << (*low).first.second << "}" << endl;} // Function to implement upper_bound()void findUpperBound( map<pair<int, int>, int>& mp, pair<int, int>& p){ // This iterator points to the // upper_bound() of given pair auto up = mp.upper_bound(p); cout << "upper_bound() for {2, 5}" << " is: {" << (*up).first.first << ", " << (*up).first.second << "}" << endl;} // Driver Codeint main(){ // Declare map of Pairs map<pair<int, int>, int> mp; // Insert Pairs in Map mp.insert({ { 2, 3 }, 8 }); mp.insert({ { 4, 1 }, 5 }); mp.insert({ { 7, 1 }, 3 }); mp.insert({ { 9, 3 }, 1 }); mp.insert({ { 5, 0 }, 3 }); // Given pair {2, 5} pair<int, int> p = { 2, 5 }; // Function Call to find lower_bound // of pair p in map mp findLowerBound(mp, p); // Function Call to find upper_bound // of pair p in map mp findUpperBound(mp, p); return 0;} lower_bound() for {2, 5} is: {4, 1} upper_bound() for {2, 5} is: {4, 1} cpp-map cpp-pair C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2020" }, { "code": null, "e": 119, "s": 28, "text": "Prerequisite: map lower_bound() function in C++ STL, map upper_bound() function in C++ STL" }, { "code": null, "e": 231, "s": 119, "text": "In this article, we will discuss the implementation of the lower_bound() and upper_bound() in the Map of pairs." }, { "code": null, "e": 798, "s": 231, "text": "lower_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value “val”. But in Map of Pairs lower_bound() for pair(x, y) will return an iterator pointing to the pair whose first value is greater than or equals x and second value is greater than equals to y.If the above-mentioned criteria are not met, then it returns an iterator which points to the pair {Map.size(), 0}.Syntax:mp.lower_bound({a, b})\n\nwhere,\nmp is the map of pairs\nand {a, b} whose lower_bound\nis to be found\n" }, { "code": null, "e": 806, "s": 798, "text": "Syntax:" }, { "code": null, "e": 905, "s": 806, "text": "mp.lower_bound({a, b})\n\nwhere,\nmp is the map of pairs\nand {a, b} whose lower_bound\nis to be found\n" }, { "code": null, "e": 1439, "s": 905, "text": "upper_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than the given value “val”. But in Map of Pairs upper_bound() for pair(x, y) will return an iterator pointing to the pair whose first value is greater than x and second value is greater than y.If the above-mentioned criteria are not met, then it returns an iterator which points to the pair {Map.size(), 0}.Syntax:mp.upper_bound({a, b})\n\nwhere,\nmp is the map of pairs\nand {a, b} whose upper_bound\nis to be found\n" }, { "code": null, "e": 1447, "s": 1439, "text": "Syntax:" }, { "code": null, "e": 1546, "s": 1447, "text": "mp.upper_bound({a, b})\n\nwhere,\nmp is the map of pairs\nand {a, b} whose upper_bound\nis to be found\n" }, { "code": null, "e": 1631, "s": 1546, "text": "Below is the program to demonstrate lower_bound() and upper_bound() in Map of pairs:" }, { "code": null, "e": 1642, "s": 1631, "text": "Program 1:" }, { "code": "// C++ program to demonstrate lower_bound()// and upper_bound() in Map of Pairs #include <bits/stdc++.h>using namespace std; // Function to implement lower_bound()void findLowerBound( map<pair<int, int>, int>& mp, pair<int, int>& p){ // This iterator points to the // lower_bound() of given pair auto low = mp.lower_bound(p); cout << \"lower_bound() for {2, 5}\" << \" is: {\" << (*low).first.first << \", \" << (*low).first.second << \"}\" << endl;} // Function to implement upper_bound()void findUpperBound( map<pair<int, int>, int>& mp, pair<int, int>& p){ // This iterator points to the // upper_bound() of given pair auto up = mp.upper_bound(p); cout << \"upper_bound() for {2, 5}\" << \" is: {\" << (*up).first.first << \", \" << (*up).first.second << \"}\" << endl;} // Driver Codeint main(){ // Declare map of Pairs map<pair<int, int>, int> mp; // Insert Pairs in Map mp.insert({ { 2, 3 }, 8 }); mp.insert({ { 4, 1 }, 5 }); mp.insert({ { 7, 1 }, 3 }); mp.insert({ { 9, 3 }, 1 }); mp.insert({ { 5, 0 }, 3 }); // Given pair {2, 5} pair<int, int> p = { 2, 5 }; // Function Call to find lower_bound // of pair p in map mp findLowerBound(mp, p); // Function Call to find upper_bound // of pair p in map mp findUpperBound(mp, p); return 0;}", "e": 3042, "s": 1642, "text": null }, { "code": null, "e": 3115, "s": 3042, "text": "lower_bound() for {2, 5} is: {4, 1}\nupper_bound() for {2, 5} is: {4, 1}\n" }, { "code": null, "e": 3123, "s": 3115, "text": "cpp-map" }, { "code": null, "e": 3132, "s": 3123, "text": "cpp-pair" }, { "code": null, "e": 3136, "s": 3132, "text": "C++" }, { "code": null, "e": 3149, "s": 3136, "text": "C++ Programs" }, { "code": null, "e": 3153, "s": 3149, "text": "CPP" }, { "code": null, "e": 3251, "s": 3153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3275, "s": 3251, "text": "Sorting a vector in C++" }, { "code": null, "e": 3295, "s": 3275, "text": "Polymorphism in C++" }, { "code": null, "e": 3339, "s": 3295, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3372, "s": 3339, "text": "Friend class and function in C++" }, { "code": null, "e": 3397, "s": 3372, "text": "std::string class in C++" }, { "code": null, "e": 3432, "s": 3397, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 3466, "s": 3432, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 3510, "s": 3466, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 3569, "s": 3510, "text": "How to return multiple values from a function in C or C++?" } ]
Java ZipFile getInputStream() function with examples
06 Mar, 2019 The getInputStream() function is a part of java.util.zip package. The function returns the InputStream of a specific ZipEntry passed as parameter.Closing the Zip File will also close all the InputStream generated by this function.Function Signature : public InputStream getInputStream(ZipEntry e) Syntax : zip_file.getInputStream(entry); Parameters : The function takes a ZipEntry object as parameter.Return value : The function returns a InputStream Object to read the contents of the ZipFile Entry.Exceptions : The function throws IllegalStateException if the zip file has been closed The function throws ZipException if a ZIP format error has occurred The function throws IOException if an I/O error has occurred Below programs illustrates the use of getInputStream() function Example 1: We will create a file named zip_file and get the zip file entry using getEntry() function and then get the Input Stream object to read the contents of the file.”file.zip” is a zip file present in f: directory. // Java program to demonstrate the// use of getInputStream() function import java.util.zip.*;import java.util.Enumeration;import java.util.*;import java.io.*; public class solution { public static void main(String args[]) { try { // Create a Zip File ZipFile zip_file = new ZipFile("f:\\file.zip"); // get the Zip Entry using // the getEntry() function ZipEntry entry = zip_file.getEntry("file1.cpp"); // get the Input Stream // using the getInputStream() // function InputStream input = zip_file.getInputStream(entry); // Create a scanner object Scanner sc = new Scanner(input); System.out.println("Contents:"); // Display the contents Zip Entry while (sc.hasNext()) { System.out.println(sc.nextLine()); } // Close the scanner sc.close(); } catch (Exception e) { System.out.println(e.getMessage()); } }} Contents: This is a file in ZIP file. Example 2: We will create a file named zip_file and get the zip file entry using getEntry() function and then get the Input Stream object to read the contents of the file.”file4.cpp” is not present in the zip file. // Java program to demonstrate the// use of getInputStream() function import java.util.zip.*;import java.util.Enumeration;import java.util.*;import java.io.*; public class solution { public static void main(String args[]) { try { // Create a Zip File ZipFile zip_file = new ZipFile("f:\\file.zip"); // get the Zip Entry using // the getEntry() function ZipEntry entry = zip_file.getEntry("file4.cpp"); // Get the Input Stream // using the getInputStream() // function InputStream input = zip_file.getInputStream(entry); // Create a scanner object Scanner sc = new Scanner(input); System.out.println("Contents:"); // Display the contents Zip Entry while (sc.hasNext()) { System.out.println(sc.nextLine()); } // Close the scanner sc.close(); } catch (Exception e) { System.out.println(e.getMessage()); } }} null Error is thrown by the function. Reference: https://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipFile.html#getInputStream(java.util.zip.ZipEntry) Java - util package Java-Functions Java-ZipFile Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Mar, 2019" }, { "code": null, "e": 279, "s": 28, "text": "The getInputStream() function is a part of java.util.zip package. The function returns the InputStream of a specific ZipEntry passed as parameter.Closing the Zip File will also close all the InputStream generated by this function.Function Signature :" }, { "code": null, "e": 325, "s": 279, "text": "public InputStream getInputStream(ZipEntry e)" }, { "code": null, "e": 334, "s": 325, "text": "Syntax :" }, { "code": null, "e": 366, "s": 334, "text": "zip_file.getInputStream(entry);" }, { "code": null, "e": 541, "s": 366, "text": "Parameters : The function takes a ZipEntry object as parameter.Return value : The function returns a InputStream Object to read the contents of the ZipFile Entry.Exceptions :" }, { "code": null, "e": 615, "s": 541, "text": "The function throws IllegalStateException if the zip file has been closed" }, { "code": null, "e": 683, "s": 615, "text": "The function throws ZipException if a ZIP format error has occurred" }, { "code": null, "e": 744, "s": 683, "text": "The function throws IOException if an I/O error has occurred" }, { "code": null, "e": 808, "s": 744, "text": "Below programs illustrates the use of getInputStream() function" }, { "code": null, "e": 1029, "s": 808, "text": "Example 1: We will create a file named zip_file and get the zip file entry using getEntry() function and then get the Input Stream object to read the contents of the file.”file.zip” is a zip file present in f: directory." }, { "code": "// Java program to demonstrate the// use of getInputStream() function import java.util.zip.*;import java.util.Enumeration;import java.util.*;import java.io.*; public class solution { public static void main(String args[]) { try { // Create a Zip File ZipFile zip_file = new ZipFile(\"f:\\\\file.zip\"); // get the Zip Entry using // the getEntry() function ZipEntry entry = zip_file.getEntry(\"file1.cpp\"); // get the Input Stream // using the getInputStream() // function InputStream input = zip_file.getInputStream(entry); // Create a scanner object Scanner sc = new Scanner(input); System.out.println(\"Contents:\"); // Display the contents Zip Entry while (sc.hasNext()) { System.out.println(sc.nextLine()); } // Close the scanner sc.close(); } catch (Exception e) { System.out.println(e.getMessage()); } }}", "e": 2098, "s": 1029, "text": null }, { "code": null, "e": 2137, "s": 2098, "text": "Contents:\nThis is a file in ZIP file.\n" }, { "code": null, "e": 2352, "s": 2137, "text": "Example 2: We will create a file named zip_file and get the zip file entry using getEntry() function and then get the Input Stream object to read the contents of the file.”file4.cpp” is not present in the zip file." }, { "code": "// Java program to demonstrate the// use of getInputStream() function import java.util.zip.*;import java.util.Enumeration;import java.util.*;import java.io.*; public class solution { public static void main(String args[]) { try { // Create a Zip File ZipFile zip_file = new ZipFile(\"f:\\\\file.zip\"); // get the Zip Entry using // the getEntry() function ZipEntry entry = zip_file.getEntry(\"file4.cpp\"); // Get the Input Stream // using the getInputStream() // function InputStream input = zip_file.getInputStream(entry); // Create a scanner object Scanner sc = new Scanner(input); System.out.println(\"Contents:\"); // Display the contents Zip Entry while (sc.hasNext()) { System.out.println(sc.nextLine()); } // Close the scanner sc.close(); } catch (Exception e) { System.out.println(e.getMessage()); } }}", "e": 3421, "s": 2352, "text": null }, { "code": null, "e": 3427, "s": 3421, "text": "null\n" }, { "code": null, "e": 3460, "s": 3427, "text": "Error is thrown by the function." }, { "code": null, "e": 3579, "s": 3460, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/zip/ZipFile.html#getInputStream(java.util.zip.ZipEntry)" }, { "code": null, "e": 3599, "s": 3579, "text": "Java - util package" }, { "code": null, "e": 3614, "s": 3599, "text": "Java-Functions" }, { "code": null, "e": 3627, "s": 3614, "text": "Java-ZipFile" }, { "code": null, "e": 3632, "s": 3627, "text": "Java" }, { "code": null, "e": 3637, "s": 3632, "text": "Java" } ]
HTML Forms
22 Jun, 2022 HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. It is a combination of Hypertext and Markup language. HTML uses predefined tags and elements that tell the browser how to properly display the content on the screen, and form is one of them. So, in this article, we will learn what is exactly HTML form, what are the elements of forms and how can we use HTML form in our webpage. <form> is a HTML element to collect input data with containing interactive controls. It provides facilities to input text, number, values, email, password, and control fields such as checkboxes, radio buttons, submit buttons, etc., or in other words, form is a container that contains input elements like text, email, number, radio buttons, checkboxes, submit buttons, etc. Forms are generally used when you want to collect data from the user. For example, a user wants to buy a bag online, so he/she has to first enter their shipping address in the address form and then add their payment details in the payment form to place an order. Forms are created by placing input fields within paragraphs, preformatted text, lists and tables. This gives considerable flexibility in designing the layout of forms. Syntax: <form> <!--form elements--> </form> These are the following HTML <form> elements: <label>: It defines label for <form> elements. <input>: It is used to get input data from the form in various types such as text, password, email, etc by changing its type. <button>: It defines a clickable button to control other elements or execute a functionality. <select>: It is used to create a drop-down list. <textarea>: It is used to get input long text content. <fieldset>: It is used to draw a box around other form elements and group the related data. <legend>: It defines caption for fieldset elements. <datalist>: It is used to specify pre-defined list options for input controls. <output>: It displays the output of performed calculations. <option>: It is used to define options in a drop-down list. <optgroup>: It is used to define group-related options in a drop-down list. In an HTML form, we use the <input> tag by assigning type attribute value to text to input single line input. To define type attribute see the below syntax. Tip: The default value of the type attribute is “text”. Syntax: <input type="text" /> Or shorthand for “text” type: <input /> We can change type value text to password to get the input password Example: HTML <!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Welcome To GFG</h2> <form> <p> <label>Username : <input type="text" /></label> </p> <p> <label>Password : <input type="password" /></label> </p> <p> <button type="submit">Submit</button> </p> </form></body></html> Output: In the above example, we can see the difference between type text and type password. The username will be visible but the password will not be visible. To create a radio button, we use the <input> tag following by radio type to provide users to choose a limited number of choices. Syntax: <input type="radio" name="radio_button_name" value="radio_button_value" /> Note: The radio button must have shared the same name to be treated as a group. Note: The value attribute defines the unique value associated with each radio button. The value is not shown to the user, but is the value that is sent to the server on “submit” to identify which radio button that was selected. Example: In this example, we will create a radio button to choose your gender. HTML <!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Select your gender</h2> <form> <label>Male<input type="radio" name="gender" value="male" /></label> <label>Female<input type="radio" name="gender" value="female" /></label> </form></body></html> Output: To create a checkbox in an HTML form, we use the <input> tag followed by the input type checkbox. It is a square box to tick to activate this. It used to choose more options at a time. Syntax: <input type="checkbox" name="select_box_name" value="select_box_value" /> Note: the “name” and “value” attributes are used to send the checkbox data to the server. Example: In this example, we use checkboxes to select language. HTML <!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Choose Language</h2> <form> <ul style="list-style-type:none;"> <li><input type="checkbox" name="language" value="hindi" />Hindi</li> <li><input type="checkbox" name="language" value="english" />English</li> <li><input type="checkbox" name="language" value="sanskrite" />Sanskrit</li> </ul> </form></body></html> Output: Combobox is used to create a drop-down menu in your form which contains multiple options. So, to create an Combobox in an HTML form, we use the <select> tag with <option> tag. It is also known as a drop-down menu. Syntax: <select name="select_box_name"> <option value="value1">option1</option> <option value="value2">option2</option> <option value="value3">option3</option> </select> Note: the “name” and “value” attributes are used to send the Combobox data to the server. Example: In this example, we will create a dropdown menu to select Nationality. HTML <!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Select Your Nationality</h2> <form> <select name="language"> <option value="indian">Indian</option> <option value="nepali">Nepali</option> <option value="others">Others</option> </select> </form></body></html> Output: In the HTML form, submit button is used to submit the details of the form to the form handler. A form handler is a file on the server with a script that is used to process input data. Syntax: <button type="submit">submit</button> Example: HTML <!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Welcome To GeeksforGeeks</h2> <form> <p> <label>Username: <input type="text" /></label> <p> <label>Password: <input type="password" /></label> </p> <p> <button type="submit">submit</button> </p> </form></body></html> Output: In the HTML form, a text area is used to add comments or reviews, or addresses to the form, in other words, the text area is a multi-line text input control. It contains an unlimited number of characters, the text renders in a fixed-width font, and the size of the text area is given by the <rows> and <cols> attributes. To create a text area in the form use the <textarea> tag. Syntax: <textarea name="textarea_name">content</textarea> Note: the name attribute is used to reference the textarea data after it is send to a server. Example: HTML <!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Welcome To GeeksforGeeks</h2> <form> <textarea name="welcomeMessage" rows="3" cols="40">GeeksforGeeks is a online portal</textarea> </form></body></html> Output: In this example, we will take input such as Salutation, First Name, Last Name, Email, Phone, Gender, Date of Birth, and Address. To create this form, we need to use the <legend> tag to defined caption, <select> tag for Salutation, <option> tag to define elements of Salutation, <input> tag for First Name, Last Name, Email, Phone, Date of Birth by changing <input> tag type attribute, <textarea> to input address, radio button for gender. After defining all these stuffs, we will use a <button> to submit this form data. 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"> <title>GfG</title></head><body> <form> <fieldset> <legend>Personal Details</legend> <p> <label> Salutation <br /> <select name="salutation"> <option>--None--</option> <option>Mr.</option> <option>Ms.</option> <option>Mrs.</option> <option>Dr.</option> <option>Prof.</option> </select> </label> </p> <p> <label>First name: <input name="firstName" /></label> </p> <p> <label>Last name: <input name="lastName" /></label> </p> <p> Gender : <label><input type="radio" name="gender" value="male" /> Male</label> <label><input type="radio" name="gender" value="female" /> Female</label> </p> <p> <label>Email:<input type="email" name="email" /></label> </p> <p> <label>Date of Birth:<input type="date" name="birthDate"></label> </p> <p> <label> Address : <br /> <textarea name="address" cols="30" rows="3"></textarea> </label> </p> <p> <button type="submit">Submit</button> </p> </fieldset> </form></body></html> Output: sagar0719kumar jochenhansoul omkarkhairmode99 Picked Class 10 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 457, "s": 28, "text": "HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. It is a combination of Hypertext and Markup language. HTML uses predefined tags and elements that tell the browser how to properly display the content on the screen, and form is one of them. So, in this article, we will learn what is exactly HTML form, what are the elements of forms and how can we use HTML form in our webpage. " }, { "code": null, "e": 1094, "s": 457, "text": "<form> is a HTML element to collect input data with containing interactive controls. It provides facilities to input text, number, values, email, password, and control fields such as checkboxes, radio buttons, submit buttons, etc., or in other words, form is a container that contains input elements like text, email, number, radio buttons, checkboxes, submit buttons, etc. Forms are generally used when you want to collect data from the user. For example, a user wants to buy a bag online, so he/she has to first enter their shipping address in the address form and then add their payment details in the payment form to place an order." }, { "code": null, "e": 1263, "s": 1094, "text": "Forms are created by placing input fields within paragraphs, preformatted text, lists and tables. This gives considerable flexibility in designing the layout of forms. " }, { "code": null, "e": 1271, "s": 1263, "text": "Syntax:" }, { "code": null, "e": 1309, "s": 1271, "text": "<form>\n <!--form elements-->\n</form>" }, { "code": null, "e": 1355, "s": 1309, "text": "These are the following HTML <form> elements:" }, { "code": null, "e": 1402, "s": 1355, "text": "<label>: It defines label for <form> elements." }, { "code": null, "e": 1528, "s": 1402, "text": "<input>: It is used to get input data from the form in various types such as text, password, email, etc by changing its type." }, { "code": null, "e": 1622, "s": 1528, "text": "<button>: It defines a clickable button to control other elements or execute a functionality." }, { "code": null, "e": 1671, "s": 1622, "text": "<select>: It is used to create a drop-down list." }, { "code": null, "e": 1726, "s": 1671, "text": "<textarea>: It is used to get input long text content." }, { "code": null, "e": 1818, "s": 1726, "text": "<fieldset>: It is used to draw a box around other form elements and group the related data." }, { "code": null, "e": 1870, "s": 1818, "text": "<legend>: It defines caption for fieldset elements." }, { "code": null, "e": 1949, "s": 1870, "text": "<datalist>: It is used to specify pre-defined list options for input controls." }, { "code": null, "e": 2009, "s": 1949, "text": "<output>: It displays the output of performed calculations." }, { "code": null, "e": 2069, "s": 2009, "text": "<option>: It is used to define options in a drop-down list." }, { "code": null, "e": 2145, "s": 2069, "text": "<optgroup>: It is used to define group-related options in a drop-down list." }, { "code": null, "e": 2303, "s": 2145, "text": "In an HTML form, we use the <input> tag by assigning type attribute value to text to input single line input. To define type attribute see the below syntax. " }, { "code": null, "e": 2359, "s": 2303, "text": "Tip: The default value of the type attribute is “text”." }, { "code": null, "e": 2367, "s": 2359, "text": "Syntax:" }, { "code": null, "e": 2389, "s": 2367, "text": "<input type=\"text\" />" }, { "code": null, "e": 2419, "s": 2389, "text": "Or shorthand for “text” type:" }, { "code": null, "e": 2429, "s": 2419, "text": "<input />" }, { "code": null, "e": 2498, "s": 2429, "text": "We can change type value text to password to get the input password " }, { "code": null, "e": 2507, "s": 2498, "text": "Example:" }, { "code": null, "e": 2512, "s": 2507, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Welcome To GFG</h2> <form> <p> <label>Username : <input type=\"text\" /></label> </p> <p> <label>Password : <input type=\"password\" /></label> </p> <p> <button type=\"submit\">Submit</button> </p> </form></body></html>", "e": 2847, "s": 2512, "text": null }, { "code": null, "e": 2855, "s": 2847, "text": "Output:" }, { "code": null, "e": 3008, "s": 2855, "text": "In the above example, we can see the difference between type text and type password. The username will be visible but the password will not be visible. " }, { "code": null, "e": 3137, "s": 3008, "text": "To create a radio button, we use the <input> tag following by radio type to provide users to choose a limited number of choices." }, { "code": null, "e": 3146, "s": 3137, "text": " Syntax:" }, { "code": null, "e": 3221, "s": 3146, "text": "<input type=\"radio\" name=\"radio_button_name\" value=\"radio_button_value\" />" }, { "code": null, "e": 3302, "s": 3221, "text": "Note: The radio button must have shared the same name to be treated as a group. " }, { "code": null, "e": 3530, "s": 3302, "text": "Note: The value attribute defines the unique value associated with each radio button. The value is not shown to the user, but is the value that is sent to the server on “submit” to identify which radio button that was selected." }, { "code": null, "e": 3539, "s": 3530, "text": "Example:" }, { "code": null, "e": 3610, "s": 3539, "text": "In this example, we will create a radio button to choose your gender. " }, { "code": null, "e": 3615, "s": 3610, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Select your gender</h2> <form> <label>Male<input type=\"radio\" name=\"gender\" value=\"male\" /></label> <label>Female<input type=\"radio\" name=\"gender\" value=\"female\" /></label> </form></body></html>", "e": 3891, "s": 3615, "text": null }, { "code": null, "e": 3899, "s": 3891, "text": "Output:" }, { "code": null, "e": 4085, "s": 3899, "text": "To create a checkbox in an HTML form, we use the <input> tag followed by the input type checkbox. It is a square box to tick to activate this. It used to choose more options at a time. " }, { "code": null, "e": 4093, "s": 4085, "text": "Syntax:" }, { "code": null, "e": 4167, "s": 4093, "text": "<input type=\"checkbox\" name=\"select_box_name\" value=\"select_box_value\" />" }, { "code": null, "e": 4257, "s": 4167, "text": "Note: the “name” and “value” attributes are used to send the checkbox data to the server." }, { "code": null, "e": 4266, "s": 4257, "text": "Example:" }, { "code": null, "e": 4322, "s": 4266, "text": "In this example, we use checkboxes to select language. " }, { "code": null, "e": 4327, "s": 4322, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Choose Language</h2> <form> <ul style=\"list-style-type:none;\"> <li><input type=\"checkbox\" name=\"language\" value=\"hindi\" />Hindi</li> <li><input type=\"checkbox\" name=\"language\" value=\"english\" />English</li> <li><input type=\"checkbox\" name=\"language\" value=\"sanskrite\" />Sanskrit</li> </ul> </form></body></html>", "e": 4736, "s": 4327, "text": null }, { "code": null, "e": 4744, "s": 4736, "text": "Output:" }, { "code": null, "e": 4959, "s": 4744, "text": "Combobox is used to create a drop-down menu in your form which contains multiple options. So, to create an Combobox in an HTML form, we use the <select> tag with <option> tag. It is also known as a drop-down menu. " }, { "code": null, "e": 4967, "s": 4959, "text": "Syntax:" }, { "code": null, "e": 5135, "s": 4967, "text": "<select name=\"select_box_name\">\n <option value=\"value1\">option1</option>\n <option value=\"value2\">option2</option>\n <option value=\"value3\">option3</option>\n</select>" }, { "code": null, "e": 5225, "s": 5135, "text": "Note: the “name” and “value” attributes are used to send the Combobox data to the server." }, { "code": null, "e": 5234, "s": 5225, "text": "Example:" }, { "code": null, "e": 5306, "s": 5234, "text": "In this example, we will create a dropdown menu to select Nationality. " }, { "code": null, "e": 5311, "s": 5306, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Select Your Nationality</h2> <form> <select name=\"language\"> <option value=\"indian\">Indian</option> <option value=\"nepali\">Nepali</option> <option value=\"others\">Others</option> </select> </form></body></html>", "e": 5612, "s": 5311, "text": null }, { "code": null, "e": 5620, "s": 5612, "text": "Output:" }, { "code": null, "e": 5806, "s": 5620, "text": "In the HTML form, submit button is used to submit the details of the form to the form handler. A form handler is a file on the server with a script that is used to process input data. " }, { "code": null, "e": 5814, "s": 5806, "text": "Syntax:" }, { "code": null, "e": 5853, "s": 5814, "text": " <button type=\"submit\">submit</button>" }, { "code": null, "e": 5863, "s": 5853, "text": "Example: " }, { "code": null, "e": 5868, "s": 5863, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Welcome To GeeksforGeeks</h2> <form> <p> <label>Username: <input type=\"text\" /></label> <p> <label>Password: <input type=\"password\" /></label> </p> <p> <button type=\"submit\">submit</button> </p> </form></body></html>", "e": 6200, "s": 5868, "text": null }, { "code": null, "e": 6209, "s": 6200, "text": "Output: " }, { "code": null, "e": 6588, "s": 6209, "text": "In the HTML form, a text area is used to add comments or reviews, or addresses to the form, in other words, the text area is a multi-line text input control. It contains an unlimited number of characters, the text renders in a fixed-width font, and the size of the text area is given by the <rows> and <cols> attributes. To create a text area in the form use the <textarea> tag." }, { "code": null, "e": 6596, "s": 6588, "text": "Syntax:" }, { "code": null, "e": 6646, "s": 6596, "text": "<textarea name=\"textarea_name\">content</textarea>" }, { "code": null, "e": 6740, "s": 6646, "text": "Note: the name attribute is used to reference the textarea data after it is send to a server." }, { "code": null, "e": 6749, "s": 6740, "text": "Example:" }, { "code": null, "e": 6754, "s": 6749, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Page Title</title></head><body> <h2>Welcome To GeeksforGeeks</h2> <form> <textarea name=\"welcomeMessage\" rows=\"3\" cols=\"40\">GeeksforGeeks is a online portal</textarea> </form></body></html>", "e": 6986, "s": 6754, "text": null }, { "code": null, "e": 6994, "s": 6986, "text": "Output:" }, { "code": null, "e": 7124, "s": 6994, "text": "In this example, we will take input such as Salutation, First Name, Last Name, Email, Phone, Gender, Date of Birth, and Address. " }, { "code": null, "e": 7517, "s": 7124, "text": "To create this form, we need to use the <legend> tag to defined caption, <select> tag for Salutation, <option> tag to define elements of Salutation, <input> tag for First Name, Last Name, Email, Phone, Date of Birth by changing <input> tag type attribute, <textarea> to input address, radio button for gender. After defining all these stuffs, we will use a <button> to submit this form data. " }, { "code": null, "e": 7522, "s": 7517, "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\"> <title>GfG</title></head><body> <form> <fieldset> <legend>Personal Details</legend> <p> <label> Salutation <br /> <select name=\"salutation\"> <option>--None--</option> <option>Mr.</option> <option>Ms.</option> <option>Mrs.</option> <option>Dr.</option> <option>Prof.</option> </select> </label> </p> <p> <label>First name: <input name=\"firstName\" /></label> </p> <p> <label>Last name: <input name=\"lastName\" /></label> </p> <p> Gender : <label><input type=\"radio\" name=\"gender\" value=\"male\" /> Male</label> <label><input type=\"radio\" name=\"gender\" value=\"female\" /> Female</label> </p> <p> <label>Email:<input type=\"email\" name=\"email\" /></label> </p> <p> <label>Date of Birth:<input type=\"date\" name=\"birthDate\"></label> </p> <p> <label> Address : <br /> <textarea name=\"address\" cols=\"30\" rows=\"3\"></textarea> </label> </p> <p> <button type=\"submit\">Submit</button> </p> </fieldset> </form></body></html>", "e": 8957, "s": 7522, "text": null }, { "code": null, "e": 8965, "s": 8957, "text": "Output:" }, { "code": null, "e": 8980, "s": 8965, "text": "sagar0719kumar" }, { "code": null, "e": 8994, "s": 8980, "text": "jochenhansoul" }, { "code": null, "e": 9011, "s": 8994, "text": "omkarkhairmode99" }, { "code": null, "e": 9018, "s": 9011, "text": "Picked" }, { "code": null, "e": 9027, "s": 9018, "text": "Class 10" }, { "code": null, "e": 9043, "s": 9027, "text": "School Learning" }, { "code": null, "e": 9062, "s": 9043, "text": "School Programming" } ]
How to use Badge Component in ReactJS?
05 Mar, 2021 Badge generates a small badge to the top-right of its children component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Badge Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core npm install @material-ui/icons Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import MailIcon from '@material-ui/icons/Mail';import Badge from '@material-ui/core/Badge'; export default function App() { return ( <div style={{display: 'block', padding: 30}}> <h4>How to use Badge Component in ReactJS?</h4> <Badge badgeContent={4} color="primary"> <MailIcon /> </Badge> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/badges/ Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to Use Bootstrap with React? How to install bootstrap in React.js ? How to create a multi-page website using React.js ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Mar, 2021" }, { "code": null, "e": 267, "s": 28, "text": "Badge generates a small badge to the top-right of its children component. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Badge Component in ReactJS using the following approach." }, { "code": null, "e": 317, "s": 267, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 381, "s": 317, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 413, "s": 381, "text": "npx create-react-app foldername" }, { "code": null, "e": 513, "s": 413, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 527, "s": 513, "text": "cd foldername" }, { "code": null, "e": 636, "s": 527, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 697, "s": 636, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 749, "s": 697, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 767, "s": 749, "text": "Project Structure" }, { "code": null, "e": 897, "s": 767, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 904, "s": 897, "text": "App.js" }, { "code": "import React from 'react';import MailIcon from '@material-ui/icons/Mail';import Badge from '@material-ui/core/Badge'; export default function App() { return ( <div style={{display: 'block', padding: 30}}> <h4>How to use Badge Component in ReactJS?</h4> <Badge badgeContent={4} color=\"primary\"> <MailIcon /> </Badge> </div> );}", "e": 1271, "s": 904, "text": null }, { "code": null, "e": 1384, "s": 1271, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 1394, "s": 1384, "text": "npm start" }, { "code": null, "e": 1493, "s": 1394, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 1547, "s": 1493, "text": "Reference: https://material-ui.com/components/badges/" }, { "code": null, "e": 1559, "s": 1547, "text": "Material-UI" }, { "code": null, "e": 1575, "s": 1559, "text": "React-Questions" }, { "code": null, "e": 1583, "s": 1575, "text": "ReactJS" }, { "code": null, "e": 1600, "s": 1583, "text": "Web Technologies" }, { "code": null, "e": 1698, "s": 1600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1736, "s": 1698, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 1763, "s": 1736, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 1796, "s": 1763, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 1835, "s": 1796, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 1887, "s": 1835, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 1920, "s": 1887, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1982, "s": 1920, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2043, "s": 1982, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2093, "s": 2043, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to load a TSV file into a Pandas DataFrame? - GeeksforGeeks
18 Oct, 2021 In this article, we will discuss how to load a TSV file into a Pandas Dataframe. The idea is extremely simple we only have to first import all the required libraries and then load the data set by the use of read_csv() method. To this method simply the path of the dataframe is passed. This is enough to get the job done. Syntax : pandas.read_csv(path, sep=’\t’) Given below are some implementations for the same. Example 1: Loading a TSV dataset into pandas dataframe Dataset Used: data.tsv Python3 import pandas as pd # Data.tsv is stored locally in the # same directory as of this python filedf = pd.read_csv('data.tsv',sep = '\t') df Output: Example 2: Loading a TSV dataset into pandas dataframe Dataset used: babynames.tsv Python3 import pandas as pd df = pd.read_csv('babynames.tsv', sep = '\t')df Output: Picked Python pandas-dataFrame Python pandas-io Python-pandas TrueGeek-2021 Python TrueGeek Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Pandas DataFrame from Lists Python Dictionary Bar Plot in Matplotlib Enumerate() in Python Python | Get dictionary keys as a list How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? Types of Internet Protocols Basics of API Testing Using Postman SQL Statement to Remove Part of a String
[ { "code": null, "e": 24545, "s": 24517, "text": "\n18 Oct, 2021" }, { "code": null, "e": 24626, "s": 24545, "text": "In this article, we will discuss how to load a TSV file into a Pandas Dataframe." }, { "code": null, "e": 24866, "s": 24626, "text": "The idea is extremely simple we only have to first import all the required libraries and then load the data set by the use of read_csv() method. To this method simply the path of the dataframe is passed. This is enough to get the job done." }, { "code": null, "e": 24875, "s": 24866, "text": "Syntax :" }, { "code": null, "e": 24907, "s": 24875, "text": "pandas.read_csv(path, sep=’\\t’)" }, { "code": null, "e": 24958, "s": 24907, "text": "Given below are some implementations for the same." }, { "code": null, "e": 25013, "s": 24958, "text": "Example 1: Loading a TSV dataset into pandas dataframe" }, { "code": null, "e": 25037, "s": 25013, "text": "Dataset Used: data.tsv" }, { "code": null, "e": 25045, "s": 25037, "text": "Python3" }, { "code": "import pandas as pd # Data.tsv is stored locally in the # same directory as of this python filedf = pd.read_csv('data.tsv',sep = '\\t') df", "e": 25184, "s": 25045, "text": null }, { "code": null, "e": 25192, "s": 25184, "text": "Output:" }, { "code": null, "e": 25247, "s": 25192, "text": "Example 2: Loading a TSV dataset into pandas dataframe" }, { "code": null, "e": 25275, "s": 25247, "text": "Dataset used: babynames.tsv" }, { "code": null, "e": 25283, "s": 25275, "text": "Python3" }, { "code": "import pandas as pd df = pd.read_csv('babynames.tsv', sep = '\\t')df", "e": 25352, "s": 25283, "text": null }, { "code": null, "e": 25360, "s": 25352, "text": "Output:" }, { "code": null, "e": 25367, "s": 25360, "text": "Picked" }, { "code": null, "e": 25391, "s": 25367, "text": "Python pandas-dataFrame" }, { "code": null, "e": 25408, "s": 25391, "text": "Python pandas-io" }, { "code": null, "e": 25422, "s": 25408, "text": "Python-pandas" }, { "code": null, "e": 25436, "s": 25422, "text": "TrueGeek-2021" }, { "code": null, "e": 25443, "s": 25436, "text": "Python" }, { "code": null, "e": 25452, "s": 25443, "text": "TrueGeek" }, { "code": null, "e": 25550, "s": 25452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25559, "s": 25550, "text": "Comments" }, { "code": null, "e": 25572, "s": 25559, "text": "Old Comments" }, { "code": null, "e": 25609, "s": 25572, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25627, "s": 25609, "text": "Python Dictionary" }, { "code": null, "e": 25650, "s": 25627, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25672, "s": 25650, "text": "Enumerate() in Python" }, { "code": null, "e": 25711, "s": 25672, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25756, "s": 25711, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 25813, "s": 25756, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 25841, "s": 25813, "text": "Types of Internet Protocols" }, { "code": null, "e": 25877, "s": 25841, "text": "Basics of API Testing Using Postman" } ]
Deploying AWS Lamba Function & Layer with Serverless Framework | by Fernando López | Towards Data Science
Serverless environments have emerged as a disruptive alternative for the deployment of applications in cloud instances without the need to configure, manage, operate and maintain a traditional server. In this tutorial, we will see an example about how to develop, configure, integrate and deploy a Lambda Function [1] that extends the functionalities of a Lambda Layer [2] through the Serverless Framework [3]. This blog will be divided as follows: AWS Lambda Function & Layer Serverless Framework What we are going to do Installing Serverless Framework Deploying AWS Lambda Layer Deploying AWS Lambda Function If you’re already familiar with AWS Lambda and the Serverless Framework, feel free to skip the next two sections and go straight to the examples. Let’s get our cup of coffee and enjoy ☕️! AWS Lambda is a computing service that allows you to run code without the need to configure and manage a server. To use AWS Lambda, you just need to package your code as well as the dependencies you will need (as a .zip file or a docker image) and organize them in a Lambda function. In Figure 2 we see a representative description of the organization of the elements within a Lambda function. As we can see in the figure above, each Lambda function is an isolated environment, that is, by nature they cannot share or extend functionality directly with another Lambda function. And this is one of the reasons why Lambda Layer emerged. Lambda Layer is an AWS Lambda extension that works directly with Lambda functions. The aim of Lambda Layer is to contain applications, requirements, dependencies, and even custom runtime components that can be extended from a Lambda Function. In figure 3 we see a description of the integration of a Lambda layer with a pair of Lambda functions. As we can see from the previous figure, the implementation of a Lambda layer favors the organization of components that can be shared and extended through Lambda functions. Also, the use of Lambda layer helps on reducing the size of Lambda functions because it would not be necessary to pack dependencies multiple times (as seen in Figure 2). However, in practice, defining and configuring one or more Lambda functions, as well as integrating with one or more Lambda layers, can be a laborious and tedious process, since AWS Lambda is commonly integrated with different services such as Amazon API Gateway, Amazon S3, Amazon SQS, Amazon SNS and many more. This is where Serverless Framework takes center stage. Serverless Framework is a tool that facilitates the definition and configuration of AWS Lambda as well as its integration with other AWS services. In a nutshell, Serverless Framework streamlines your AWS Lambda development, integration, and deployment process. Serverless is a cloud-agnostic framework, that is, it allows the development and deployment of services through the definition of a YAML file and the use of a CLI, to different cloud providers such as AWS, Azure, Google Cloud, Knative, and more. Once we are clear on the relationship between AWS Lambda Function & Layer as well as the relevance of Serverless Framework in the development and deployment of cloud services, let’s go straight to the tutorial. Don’t forget to fill up your cup of coffee ☕️! We are going to create a Lambda function and a Lambda Layer. The Lambda layer will contain only the numpy library. The lambda function will extend the numpy library from the Lambda layer and implement it in its main method. The entire development and deployment process will be through the Serverless Framework. Once the context is defined, let’s go for it! To install Serverless, we first need to have node.js. To install node.js on macOS: $ brew install node For installing node.js on Ubuntu: $ sudo apt install nodejs$ sudo apt install npm Or if you prefer, you can go directly to the official node site to download it. Once node.js is installed and the npm manager is enabled, we proceed to install Serverless: $ npm install -g serverless If you have any problems with the installation through the npm manager, you can follow the official Serverless installation guide for installing the standalone binary. Since we are going to develop and deploy to AWS in this example, you need to add the credentials of an AWS account, as follows: $ serverless config credentials --provider aws \ --key <access_key> \ --secret <secret_key> Once Serverless is installed and the credentials configured, we are ready to start with the fun part, let’s go for it! First, let’s create a template for our Lambda layer with the serverless CLI, which we will call lambda-layer. (venv) $ serverless create --template aws-python3 \ --name layer-numpy \ --path layer-numpy The above command will generate a directory called lambda-layer which will contain the handler.py and serverless.yml files. (venv) $ tree.└── layer-numpy ├── handler.py └── serverless.yml In essence, the handler.py file contains the code that will run on AWS Lambda. The serverless.yml file contains the definition of the Lambda function or layer as well as all the necessary configurations for the deployment of the service. Nervertheless, since in this case we want to deploy a Lambda layer that only contains a library, the handler.py file is not necessary. On the contrary, the file we require is requirements.txt which will contain the library that Lambda layer will host. So, removing the handler.py file and adding the requirements.txt file, our directory looks like this: (venv) $ tree.└── layer-numpy ├── requirements.txt └── serverless.yml where the requirements.txt file only contains a reference to the numpy library: (venv) $ cat requirements.txt numpy==1.21.0 To deploy the content of the requirements.txt file via serverless, we are going to require the serverless-python-requirements plugin which allows serverless to access the content of the requirements.txt file and prepare it for deployment. To install the serverless-python-requirements plugin we type: (venv) $ sls plugin install -n serverless-python-requirements When installing the plugin, the serverless.yml file is updated by adding the definition of the installed plugin. The default content of our serverless.yml is like the one shown in the following code snippet. As we can see, in line 10 we have the definition for a Lambda function created by default, however for the Lambda layer deployment we do not need it. On the other hand, in line 14 we have the reference to the plugin installed in the previous step. Our serverless.yml file, after the modifications for the deployment of our Lambda layer, is as follows: As we can see, from line 13 the definition of our Lambda layer begins, which is of type pythonRequirements whose content will be dockerized . Our Lambda layer is called python-numpy and is compatible with python 3.8 runtime. It is important to mention that, since we enable the dockerization of the requirements, it is necessary to have docker installed on our local machine from where we will perform the deployment. Great, once we have the requirements.txt file, customized the serverless.yml file and installed the plugin , we are ready to deploy. For the deployment, we only type: (venv) $ sls deploy And that’s it! our Lambda layer should be visible from our AWS console as shown in the following figure: Once our Lambda layer is deployed, it is necessary to identify the associated ARN since it will be necessary to reference from the definition of our Lambda function. Great, we have deployed our Lambda layer. Now let’s see how to deploy a Lambda function that extends dependencies of the Lambda layer. Let’s go for it! First, we are going to generate an aws-python3 template for our Lambda function which we will name test-function. (venv) $ serverless create --template aws-python3 \ --name test-function \ --path test-function The above command will generate a directory called test-function which contains two files, handler.py and serverless.yml. The handler.py file will contain the code that AWS Lambda will run. The serverless.yml file will contain the definition of the deployment. (venv) $ tree.└── test-function ├── handler.py └── serverless.yml First, let’s modify the handler.py file. Since we assume that we will extend the numpy library from the Lambda layer created in the previous section, all we have to do here is import numpy and declare some basic functionality. Finally, our handler.py file would look like this: Now we will update the serverless.yml file. Basically, we will define 3 main things: the Lambda function, the Lambda layer extension and an API Gateway method (which we will use to make requests to our Lambda function). Finally, the serverless.yml file looks like this: In line 12 we define the name of our function ( hello ), in line 13 we define the method that will be executed from the handler.py file. In line 15 we define the extension to Lambda layer (this is where we use the ARN of our Lambda layer created in the previous section) and finally in line 19 we define a GET method to make requests to our Lambda function. And that’s it, we are ready to deploy! (venv) $ sls deploy Once our Lambda function is deployed, we could already see it in our AWS console. In the following figure we see the characteristics of our AWS Lambda function deployed from the console. As we can see, our Lambda function has a Lambda layer attached and it has an API Gateway as a trigger. Finally, to test our Lambda function, we use the serverless CLI as follows: (venv) $ sls invoke -f hello { "statusCode": 200, "body": "\"Random number: 17. Numpy version: 1.21.0\""} And that’s it! our AWS Lambda function extends the numpy library from a Lambda layer and the entire development and deployment process has been through the Serverless Framework. [1] AWS Lambda Function [2] AWS Lambda Layer [3] Serverless Framework
[ { "code": null, "e": 373, "s": 172, "text": "Serverless environments have emerged as a disruptive alternative for the deployment of applications in cloud instances without the need to configure, manage, operate and maintain a traditional server." }, { "code": null, "e": 583, "s": 373, "text": "In this tutorial, we will see an example about how to develop, configure, integrate and deploy a Lambda Function [1] that extends the functionalities of a Lambda Layer [2] through the Serverless Framework [3]." }, { "code": null, "e": 621, "s": 583, "text": "This blog will be divided as follows:" }, { "code": null, "e": 649, "s": 621, "text": "AWS Lambda Function & Layer" }, { "code": null, "e": 670, "s": 649, "text": "Serverless Framework" }, { "code": null, "e": 694, "s": 670, "text": "What we are going to do" }, { "code": null, "e": 726, "s": 694, "text": "Installing Serverless Framework" }, { "code": null, "e": 753, "s": 726, "text": "Deploying AWS Lambda Layer" }, { "code": null, "e": 783, "s": 753, "text": "Deploying AWS Lambda Function" }, { "code": null, "e": 929, "s": 783, "text": "If you’re already familiar with AWS Lambda and the Serverless Framework, feel free to skip the next two sections and go straight to the examples." }, { "code": null, "e": 971, "s": 929, "text": "Let’s get our cup of coffee and enjoy ☕️!" }, { "code": null, "e": 1255, "s": 971, "text": "AWS Lambda is a computing service that allows you to run code without the need to configure and manage a server. To use AWS Lambda, you just need to package your code as well as the dependencies you will need (as a .zip file or a docker image) and organize them in a Lambda function." }, { "code": null, "e": 1365, "s": 1255, "text": "In Figure 2 we see a representative description of the organization of the elements within a Lambda function." }, { "code": null, "e": 1606, "s": 1365, "text": "As we can see in the figure above, each Lambda function is an isolated environment, that is, by nature they cannot share or extend functionality directly with another Lambda function. And this is one of the reasons why Lambda Layer emerged." }, { "code": null, "e": 1849, "s": 1606, "text": "Lambda Layer is an AWS Lambda extension that works directly with Lambda functions. The aim of Lambda Layer is to contain applications, requirements, dependencies, and even custom runtime components that can be extended from a Lambda Function." }, { "code": null, "e": 1952, "s": 1849, "text": "In figure 3 we see a description of the integration of a Lambda layer with a pair of Lambda functions." }, { "code": null, "e": 2295, "s": 1952, "text": "As we can see from the previous figure, the implementation of a Lambda layer favors the organization of components that can be shared and extended through Lambda functions. Also, the use of Lambda layer helps on reducing the size of Lambda functions because it would not be necessary to pack dependencies multiple times (as seen in Figure 2)." }, { "code": null, "e": 2663, "s": 2295, "text": "However, in practice, defining and configuring one or more Lambda functions, as well as integrating with one or more Lambda layers, can be a laborious and tedious process, since AWS Lambda is commonly integrated with different services such as Amazon API Gateway, Amazon S3, Amazon SQS, Amazon SNS and many more. This is where Serverless Framework takes center stage." }, { "code": null, "e": 2924, "s": 2663, "text": "Serverless Framework is a tool that facilitates the definition and configuration of AWS Lambda as well as its integration with other AWS services. In a nutshell, Serverless Framework streamlines your AWS Lambda development, integration, and deployment process." }, { "code": null, "e": 3170, "s": 2924, "text": "Serverless is a cloud-agnostic framework, that is, it allows the development and deployment of services through the definition of a YAML file and the use of a CLI, to different cloud providers such as AWS, Azure, Google Cloud, Knative, and more." }, { "code": null, "e": 3381, "s": 3170, "text": "Once we are clear on the relationship between AWS Lambda Function & Layer as well as the relevance of Serverless Framework in the development and deployment of cloud services, let’s go straight to the tutorial." }, { "code": null, "e": 3428, "s": 3381, "text": "Don’t forget to fill up your cup of coffee ☕️!" }, { "code": null, "e": 3740, "s": 3428, "text": "We are going to create a Lambda function and a Lambda Layer. The Lambda layer will contain only the numpy library. The lambda function will extend the numpy library from the Lambda layer and implement it in its main method. The entire development and deployment process will be through the Serverless Framework." }, { "code": null, "e": 3786, "s": 3740, "text": "Once the context is defined, let’s go for it!" }, { "code": null, "e": 3869, "s": 3786, "text": "To install Serverless, we first need to have node.js. To install node.js on macOS:" }, { "code": null, "e": 3889, "s": 3869, "text": "$ brew install node" }, { "code": null, "e": 3923, "s": 3889, "text": "For installing node.js on Ubuntu:" }, { "code": null, "e": 3971, "s": 3923, "text": "$ sudo apt install nodejs$ sudo apt install npm" }, { "code": null, "e": 4143, "s": 3971, "text": "Or if you prefer, you can go directly to the official node site to download it. Once node.js is installed and the npm manager is enabled, we proceed to install Serverless:" }, { "code": null, "e": 4171, "s": 4143, "text": "$ npm install -g serverless" }, { "code": null, "e": 4339, "s": 4171, "text": "If you have any problems with the installation through the npm manager, you can follow the official Serverless installation guide for installing the standalone binary." }, { "code": null, "e": 4467, "s": 4339, "text": "Since we are going to develop and deploy to AWS in this example, you need to add the credentials of an AWS account, as follows:" }, { "code": null, "e": 4621, "s": 4467, "text": "$ serverless config credentials --provider aws \\ --key <access_key> \\ --secret <secret_key>" }, { "code": null, "e": 4740, "s": 4621, "text": "Once Serverless is installed and the credentials configured, we are ready to start with the fun part, let’s go for it!" }, { "code": null, "e": 4850, "s": 4740, "text": "First, let’s create a template for our Lambda layer with the serverless CLI, which we will call lambda-layer." }, { "code": null, "e": 4994, "s": 4850, "text": "(venv) $ serverless create --template aws-python3 \\ --name layer-numpy \\ --path layer-numpy" }, { "code": null, "e": 5118, "s": 4994, "text": "The above command will generate a directory called lambda-layer which will contain the handler.py and serverless.yml files." }, { "code": null, "e": 5188, "s": 5118, "text": "(venv) $ tree.└── layer-numpy ├── handler.py └── serverless.yml" }, { "code": null, "e": 5426, "s": 5188, "text": "In essence, the handler.py file contains the code that will run on AWS Lambda. The serverless.yml file contains the definition of the Lambda function or layer as well as all the necessary configurations for the deployment of the service." }, { "code": null, "e": 5678, "s": 5426, "text": "Nervertheless, since in this case we want to deploy a Lambda layer that only contains a library, the handler.py file is not necessary. On the contrary, the file we require is requirements.txt which will contain the library that Lambda layer will host." }, { "code": null, "e": 5780, "s": 5678, "text": "So, removing the handler.py file and adding the requirements.txt file, our directory looks like this:" }, { "code": null, "e": 5856, "s": 5780, "text": "(venv) $ tree.└── layer-numpy ├── requirements.txt └── serverless.yml" }, { "code": null, "e": 5936, "s": 5856, "text": "where the requirements.txt file only contains a reference to the numpy library:" }, { "code": null, "e": 5980, "s": 5936, "text": "(venv) $ cat requirements.txt numpy==1.21.0" }, { "code": null, "e": 6219, "s": 5980, "text": "To deploy the content of the requirements.txt file via serverless, we are going to require the serverless-python-requirements plugin which allows serverless to access the content of the requirements.txt file and prepare it for deployment." }, { "code": null, "e": 6281, "s": 6219, "text": "To install the serverless-python-requirements plugin we type:" }, { "code": null, "e": 6343, "s": 6281, "text": "(venv) $ sls plugin install -n serverless-python-requirements" }, { "code": null, "e": 6551, "s": 6343, "text": "When installing the plugin, the serverless.yml file is updated by adding the definition of the installed plugin. The default content of our serverless.yml is like the one shown in the following code snippet." }, { "code": null, "e": 6799, "s": 6551, "text": "As we can see, in line 10 we have the definition for a Lambda function created by default, however for the Lambda layer deployment we do not need it. On the other hand, in line 14 we have the reference to the plugin installed in the previous step." }, { "code": null, "e": 6903, "s": 6799, "text": "Our serverless.yml file, after the modifications for the deployment of our Lambda layer, is as follows:" }, { "code": null, "e": 7128, "s": 6903, "text": "As we can see, from line 13 the definition of our Lambda layer begins, which is of type pythonRequirements whose content will be dockerized . Our Lambda layer is called python-numpy and is compatible with python 3.8 runtime." }, { "code": null, "e": 7321, "s": 7128, "text": "It is important to mention that, since we enable the dockerization of the requirements, it is necessary to have docker installed on our local machine from where we will perform the deployment." }, { "code": null, "e": 7488, "s": 7321, "text": "Great, once we have the requirements.txt file, customized the serverless.yml file and installed the plugin , we are ready to deploy. For the deployment, we only type:" }, { "code": null, "e": 7508, "s": 7488, "text": "(venv) $ sls deploy" }, { "code": null, "e": 7613, "s": 7508, "text": "And that’s it! our Lambda layer should be visible from our AWS console as shown in the following figure:" }, { "code": null, "e": 7779, "s": 7613, "text": "Once our Lambda layer is deployed, it is necessary to identify the associated ARN since it will be necessary to reference from the definition of our Lambda function." }, { "code": null, "e": 7914, "s": 7779, "text": "Great, we have deployed our Lambda layer. Now let’s see how to deploy a Lambda function that extends dependencies of the Lambda layer." }, { "code": null, "e": 7931, "s": 7914, "text": "Let’s go for it!" }, { "code": null, "e": 8045, "s": 7931, "text": "First, we are going to generate an aws-python3 template for our Lambda function which we will name test-function." }, { "code": null, "e": 8193, "s": 8045, "text": "(venv) $ serverless create --template aws-python3 \\ --name test-function \\ --path test-function" }, { "code": null, "e": 8454, "s": 8193, "text": "The above command will generate a directory called test-function which contains two files, handler.py and serverless.yml. The handler.py file will contain the code that AWS Lambda will run. The serverless.yml file will contain the definition of the deployment." }, { "code": null, "e": 8526, "s": 8454, "text": "(venv) $ tree.└── test-function ├── handler.py └── serverless.yml" }, { "code": null, "e": 8804, "s": 8526, "text": "First, let’s modify the handler.py file. Since we assume that we will extend the numpy library from the Lambda layer created in the previous section, all we have to do here is import numpy and declare some basic functionality. Finally, our handler.py file would look like this:" }, { "code": null, "e": 9074, "s": 8804, "text": "Now we will update the serverless.yml file. Basically, we will define 3 main things: the Lambda function, the Lambda layer extension and an API Gateway method (which we will use to make requests to our Lambda function). Finally, the serverless.yml file looks like this:" }, { "code": null, "e": 9432, "s": 9074, "text": "In line 12 we define the name of our function ( hello ), in line 13 we define the method that will be executed from the handler.py file. In line 15 we define the extension to Lambda layer (this is where we use the ARN of our Lambda layer created in the previous section) and finally in line 19 we define a GET method to make requests to our Lambda function." }, { "code": null, "e": 9471, "s": 9432, "text": "And that’s it, we are ready to deploy!" }, { "code": null, "e": 9491, "s": 9471, "text": "(venv) $ sls deploy" }, { "code": null, "e": 9678, "s": 9491, "text": "Once our Lambda function is deployed, we could already see it in our AWS console. In the following figure we see the characteristics of our AWS Lambda function deployed from the console." }, { "code": null, "e": 9781, "s": 9678, "text": "As we can see, our Lambda function has a Lambda layer attached and it has an API Gateway as a trigger." }, { "code": null, "e": 9857, "s": 9781, "text": "Finally, to test our Lambda function, we use the serverless CLI as follows:" }, { "code": null, "e": 9969, "s": 9857, "text": "(venv) $ sls invoke -f hello { \"statusCode\": 200, \"body\": \"\\\"Random number: 17. Numpy version: 1.21.0\\\"\"}" }, { "code": null, "e": 10147, "s": 9969, "text": "And that’s it! our AWS Lambda function extends the numpy library from a Lambda layer and the entire development and deployment process has been through the Serverless Framework." }, { "code": null, "e": 10171, "s": 10147, "text": "[1] AWS Lambda Function" }, { "code": null, "e": 10192, "s": 10171, "text": "[2] AWS Lambda Layer" } ]
Add all greater values to every node in a BST | Practice | GeeksforGeeks
Given a BST, modify it so that all greater values in the given BST are added to every node. Example 1: Input: 50 / \ 30 70 / \ / \ 20 40 60 80 Output: 350 330 300 260 210 150 80 Explanation:The tree should be modified to following: 260 / \ 330 150 / \ / \ 350 300 210 80 Example 2: Input: 2 / \ 1 5 / \ 4 7 Output: 19 18 16 12 7 Your Task: You don't need to read input or print anything. Your task is to complete the function modify() which takes one argument: root of the BST. The function should contain the logic to modify the BST so that in the modified BST, every node has a value equal to the sum of its value in the original BST and values of all the elements larger than it in the original BST. Return the root of the modified BST. The driver code will print the inorder traversal of the returned BST/ Expected Time Complexity: O(N) Expected Auxiliary Space: O(Height of the BST). Constraints: 1<=N<=100000 Note: The Input/Output format and Example is given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code. 0 pushkarcoding101 month ago python solution (0.2/1.0) def modify(root): ar=inor(root,[]) ar=ar[::-1] su=ar[0] arr=[] arr.append(su) for i in range(1,len(ar)): su=su+ar[i] arr.append(su) arr=arr[::-1] ans=tree(0,len(arr)-1,arr) return ansdef inor(root,a): if(root==None): return inor(root.left,a) a.append(root.data) inor(root.right,a) return a def tree(s,e,arr): if(s>e): return None mid=(s+e)//2 root=Node(arr[mid]) root.left=tree(s,mid-1,arr) root.right=tree(mid+1,e,arr) return root 0 forcer This comment was deleted. +1 badgujarsachin832 months ago void solve(Node* root,int& sum){ if(root==NULL){ return ; } solve(root->right,sum); sum+=(root->data); root->data=sum; solve(root->left,sum); } // modify the BST and return its root Node* modify(Node *root) { // Your code here int sum=0; solve(root,sum); return root; } 0 madhukartemba2 months ago JAVA SOLUTION: class Solution { int sum = 0; public void rec(Node root) { if(root==null) return; rec(root.right); root.data += sum; sum = root.data; rec(root.left); } // modify the BST and return its root public Node modify(Node root) { sum = 0; rec(root); return root; } } 0 sohamdas86972 months ago void solve(Node* root, int& sum) { if(root == NULL) return; solve(root->right, sum); sum += (root->data); root->data = sum; solve(root->left, sum); } Node* modify(Node *root) { int sum = 0; solve(root, sum); return root; } 0 hamidnourashraf2 months ago def _inorder(root, res): if root is None: return _inorder(root.left, res) res.append(root) _inorder(root.right, res) def modify(root): res = [] _inorder(root, res) for i in range(len(res)-2, -1, -1): res[i].data += res[i+1].data return root +2 himanshukug19cs2 months ago java solution int sum=0; void sol(Node root){ if(root==null) return; sol(root.right); sum=root.data+sum; root.data=sum; sol(root.left); } public Node modify(Node root) { //Write your code here sol(root); return root; } +1 shyamprakash8072 months ago Simple Python solution: def modify(root): x = [0] help(root, x) return root def help(root, x): if root == None: return help(root.right, x) root.data = root.data + x[0] x[0] = root.data help(root.left, x) 0 yanoop2382 months ago void tree(Node* & root , int & a){ if(root==NULL){ return ; } tree(root->right,a); root->data+=a; a=root->data; tree(root->left,a);} Node* modify(Node *root){ int a=0; tree(root,a); return root;// Your code here} 0 sanisettymanoj2 months ago O(n) recursive static int sum = 0; public Node modify(Node root) { sum = 0; sumEach(root); return root; } public static void sumEach(Node root){ if(root == null) return; sumEach(root.right); sum +=root.data; root.data = sum; sumEach(root.left); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 330, "s": 238, "text": "Given a BST, modify it so that all greater values in the given BST are added to every node." }, { "code": null, "e": 341, "s": 330, "text": "Example 1:" }, { "code": null, "e": 630, "s": 341, "text": "Input:\n 50\n / \\\n 30 70\n / \\ / \\ \n 20 40 60 80\nOutput: 350 330 300 260 210 150 80\nExplanation:The tree should be modified to\nfollowing:\n 260\n / \\\n 330 150\n / \\ / \\\n 350 300 210 80\n" }, { "code": null, "e": 641, "s": 630, "text": "Example 2:" }, { "code": null, "e": 746, "s": 641, "text": "Input:\n 2\n / \\\n 1 5\n / \\\n 4 7\nOutput: 19 18 16 12 7" }, { "code": null, "e": 1307, "s": 746, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function modify() which takes one argument: root of the BST. The function should contain the logic to modify the BST so that in the modified BST, every node has a value equal to the sum of its value in the original BST and values of all the elements larger than it in the original BST. Return the root of the modified BST. The driver code will print the inorder traversal of the returned BST/\n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(Height of the BST)." }, { "code": null, "e": 1333, "s": 1307, "text": "Constraints:\n1<=N<=100000" }, { "code": null, "e": 1656, "s": 1333, "text": "\nNote: The Input/Output format and Example is given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1658, "s": 1656, "text": "0" }, { "code": null, "e": 1685, "s": 1658, "text": "pushkarcoding101 month ago" }, { "code": null, "e": 1711, "s": 1685, "text": "python solution (0.2/1.0)" }, { "code": null, "e": 2214, "s": 1713, "text": "def modify(root): ar=inor(root,[]) ar=ar[::-1] su=ar[0] arr=[] arr.append(su) for i in range(1,len(ar)): su=su+ar[i] arr.append(su) arr=arr[::-1] ans=tree(0,len(arr)-1,arr) return ansdef inor(root,a): if(root==None): return inor(root.left,a) a.append(root.data) inor(root.right,a) return a def tree(s,e,arr): if(s>e): return None mid=(s+e)//2 root=Node(arr[mid]) root.left=tree(s,mid-1,arr) root.right=tree(mid+1,e,arr) return root " }, { "code": null, "e": 2216, "s": 2214, "text": "0" }, { "code": null, "e": 2223, "s": 2216, "text": "forcer" }, { "code": null, "e": 2249, "s": 2223, "text": "This comment was deleted." }, { "code": null, "e": 2252, "s": 2249, "text": "+1" }, { "code": null, "e": 2281, "s": 2252, "text": "badgujarsachin832 months ago" }, { "code": null, "e": 2599, "s": 2281, "text": "void solve(Node* root,int& sum){\n if(root==NULL){\n return ;\n }\n solve(root->right,sum);\n sum+=(root->data);\n root->data=sum;\n solve(root->left,sum);\n}\n// modify the BST and return its root\nNode* modify(Node *root)\n{\n // Your code here\n int sum=0;\n solve(root,sum);\n return root;\n}" }, { "code": null, "e": 2601, "s": 2599, "text": "0" }, { "code": null, "e": 2627, "s": 2601, "text": "madhukartemba2 months ago" }, { "code": null, "e": 2642, "s": 2627, "text": "JAVA SOLUTION:" }, { "code": null, "e": 3084, "s": 2642, "text": "class Solution\n{\n int sum = 0;\n public void rec(Node root)\n {\n if(root==null) return;\n \n rec(root.right);\n \n root.data += sum;\n sum = root.data;\n \n rec(root.left);\n \n \n }\n \n \n // modify the BST and return its root\n public Node modify(Node root)\n {\n sum = 0;\n \n rec(root);\n \n return root;\n \n }\n \n}" }, { "code": null, "e": 3086, "s": 3084, "text": "0" }, { "code": null, "e": 3111, "s": 3086, "text": "sohamdas86972 months ago" }, { "code": null, "e": 3374, "s": 3111, "text": "void solve(Node* root, int& sum)\n{\n if(root == NULL)\n return;\n solve(root->right, sum);\n sum += (root->data);\n root->data = sum;\n solve(root->left, sum);\n}\nNode* modify(Node *root)\n{\n int sum = 0;\n solve(root, sum);\n return root;\n}" }, { "code": null, "e": 3376, "s": 3374, "text": "0" }, { "code": null, "e": 3404, "s": 3376, "text": "hamidnourashraf2 months ago" }, { "code": null, "e": 3698, "s": 3404, "text": "def _inorder(root, res):\n if root is None:\n return\n _inorder(root.left, res)\n res.append(root)\n _inorder(root.right, res)\n \ndef modify(root):\n res = []\n _inorder(root, res)\n for i in range(len(res)-2, -1, -1):\n res[i].data += res[i+1].data\n return root" }, { "code": null, "e": 3701, "s": 3698, "text": "+2" }, { "code": null, "e": 3729, "s": 3701, "text": "himanshukug19cs2 months ago" }, { "code": null, "e": 3743, "s": 3729, "text": "java solution" }, { "code": null, "e": 4039, "s": 3743, "text": "int sum=0; void sol(Node root){ if(root==null) return; sol(root.right); sum=root.data+sum; root.data=sum; sol(root.left); } public Node modify(Node root) { //Write your code here sol(root); return root; }" }, { "code": null, "e": 4042, "s": 4039, "text": "+1" }, { "code": null, "e": 4070, "s": 4042, "text": "shyamprakash8072 months ago" }, { "code": null, "e": 4094, "s": 4070, "text": "Simple Python solution:" }, { "code": null, "e": 4154, "s": 4096, "text": "def modify(root): x = [0] help(root, x) return root" }, { "code": null, "e": 4298, "s": 4154, "text": "def help(root, x): if root == None: return help(root.right, x) root.data = root.data + x[0] x[0] = root.data help(root.left, x)" }, { "code": null, "e": 4300, "s": 4298, "text": "0" }, { "code": null, "e": 4322, "s": 4300, "text": "yanoop2382 months ago" }, { "code": null, "e": 4477, "s": 4322, "text": "void tree(Node* & root , int & a){ if(root==NULL){ return ; } tree(root->right,a); root->data+=a; a=root->data; tree(root->left,a);}" }, { "code": null, "e": 4566, "s": 4477, "text": "Node* modify(Node *root){ int a=0; tree(root,a); return root;// Your code here}" }, { "code": null, "e": 4568, "s": 4566, "text": "0" }, { "code": null, "e": 4595, "s": 4568, "text": "sanisettymanoj2 months ago" }, { "code": null, "e": 4935, "s": 4595, "text": "O(n) recursive \nstatic int sum = 0;\n public Node modify(Node root)\n {\n sum = 0;\n sumEach(root);\n return root;\n }\n public static void sumEach(Node root){\n if(root == null)\n return;\n sumEach(root.right);\n sum +=root.data;\n root.data = sum;\n sumEach(root.left);\n }" }, { "code": null, "e": 5081, "s": 4935, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5117, "s": 5081, "text": " Login to access your submissions. " }, { "code": null, "e": 5127, "s": 5117, "text": "\nProblem\n" }, { "code": null, "e": 5137, "s": 5127, "text": "\nContest\n" }, { "code": null, "e": 5200, "s": 5137, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5348, "s": 5200, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5556, "s": 5348, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 5662, "s": 5556, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Time-Series and Correlations with Stock Market Data using Python | by Bill Voisine | Towards Data Science
I’ve recently created an account with IEX Cloud, a financial data service. As I’ve been learning the features of this new data source (new to me) and experimenting within my Jupyter Notebook, I thought the below may be helpful for others as well. Therefore, I’m creating my first Medium article and will focus it on financial time series data. There are quite a few articles and sources on defining correlation, and the differences between correlation and causation; so what you will find below will primarily show some ways to test correlation and what the results mean. You may find this article beneficial if you’re looking to use IEX Cloud, if you’re looking to do Correlation tests in Python, and if you’re interested in Time-Series data! If you’re following this and coding it yourself, go to https://iexcloud.io/ and get yourself an API key! You’ll need it next! Also, don’t forgot to install an IEX Python library: https://addisonlynch.github.io/iexfinance/ (Lynch, 2019). Install this library using: $ pip3 install iexfinance import configimport os#os.environ['IEX_API_VERSION'] = "iexcloud-sandbox"os.environ['IEX_TOKEN'] = config.iex_api_key # Replace "config.iex_api_key" with your API Key from IEX Cloud! We’ll load up some of the libraries we’ll need next. Also, we’ll be using data between January 1, 2017 and November 22, 2019. from datetime import datetimefrom iexfinance.stocks import get_historical_dataimport matplotlib.pyplot as plt%matplotlib inlinestart = datetime(2017, 1, 1)end = datetime(2019, 11, 22) We’ll arbitrarily choose ‘close’ for the sake of simplicity. From this API data response, you could also choose Open, High, Low, and Volume. We’ll experiment with ‘close.’ Now, let’s make an API call and download more data, ‘SPDR S&P 500 Trust ETF,’ which tracks the S&P 500 (ticker: SPY). We’ll be using this later in some correlation tests. SPY = get_historical_data("SPY", start, end, output_format='pandas')plt.figure(figsize=(10, 4))plt.plot(SPY.index, SPY['close'])plt.title('Daily Times Series for the SPY'); Now, let’s continue to explore the API by downloading data for the FAANG stocks (Facebook, Amazon, Apple, Netflix, and Google) (Kenton, 2019), as well as add an interest of mine, Tesla. Also, chart these up. Pay careful attention to the charts and do a comparison of those with the SPY chart above. Some of these will look very similar to the SPY chart, some won’t. FAANGT = get_historical_data(["FB","AMZN","AAPL","NFLX","GOOG","TSLA"], start, end, output_format='pandas')print(FAANGT.head())FB AMZN \ open high low close volume open high low date 2017-01-03 116.03 117.84 115.51 116.86 20663912 757.92 758.76 747.70 2017-01-04 117.55 119.66 117.29 118.69 19630932 758.39 759.68 754.20 2017-01-05 118.86 120.95 118.32 120.67 19492150 761.55 782.40 760.26 2017-01-06 120.98 123.88 120.03 123.41 28545263 782.36 799.44 778.48 2017-01-09 123.55 125.43 123.04 124.90 22880360 798.00 801.77 791.77 ... GOOG \ close volume ... open high low close volume date ... 2017-01-03 753.67 3521066 ... 778.81 789.63 775.80 786.14 1657268 2017-01-04 757.18 2510526 ... 788.36 791.34 783.16 786.90 1072958 2017-01-05 780.45 5830068 ... 786.08 794.48 785.02 794.02 1335167 2017-01-06 795.99 5986234 ... 795.26 807.90 792.20 806.15 1640170 2017-01-09 796.92 3446109 ... 806.40 809.97 802.83 806.65 1274645 TSLA open high low close volume date 2017-01-03 214.86 220.33 210.96 216.99 5923254 2017-01-04 214.75 228.00 214.31 226.99 11213471 2017-01-05 226.42 227.48 221.95 226.75 5911695 2017-01-06 226.93 230.31 225.45 229.01 5527893 2017-01-09 228.97 231.92 228.00 231.28 3979484 [5 rows x 30 columns]plt.figure(figsize=(15, 4))#FBplt.subplot(1, 2, 1)plt.plot(FAANGT.index, FAANGT['FB']['close'])plt.title('Daily Times Series for the FB')#AMZNplt.subplot(1, 2, 2)plt.plot(FAANGT.index, FAANGT['AMZN']['close'])plt.title('Daily Times Series for the AMZN');plt.figure(figsize=(15, 4))#AAPLplt.subplot(1, 2, 1)plt.plot(FAANGT.index, FAANGT['AAPL']['close'])plt.title('Daily Times Series for the AAPL');#GOOGplt.subplot(1, 2, 2)plt.plot(FAANGT.index, FAANGT['GOOG']['close'])plt.title('Daily Times Series for the GOOG');plt.figure(figsize=(15, 4))#TSLAplt.subplot(1, 2, 1)plt.plot(FAANGT.index, FAANGT['TSLA']['close'])plt.title('Daily Times Series for the TSLA'); Now that we have data for both the FAANG stocks (and TSLA) and the S&P 500, and we’ve plotted these so that we know what they look like; let’s try an experiment! We’re going to try a Pearson Correlation test, to test correlation on all of these equities and the S&P 500. What do you think? Based-on viewing the charts and going by intuition, will they correlate? Correlation will show when the Pearson Correlation Coefficient is between -1 and +1. If closer to +1, we’re seeing a positive correlation. If Pearson’s correlation is closer to -1, a negative correlation (Cheong, 2019). import pandas as pdimport scipy.stats as stats# Slice this up to make it easier to work with.indx = pd.IndexSlicedf1 = FAANGT.loc[:, (indx[:],'close')]c, p = stats.pearsonr(df1['FB'].dropna()['close'], SPY.dropna()['close'])print(f"FB vs SPY Pearson Correlation: {c}\n")c, p = stats.pearsonr(df1['AMZN'].dropna()['close'], SPY.dropna()['close'])print(f"AMZN vs SPY Pearson Correlation: {c}\n")c, p = stats.pearsonr(df1['AAPL'].dropna()['close'], SPY.dropna()['close'])print(f"AAPL vs SPY Pearson Correlation: {c}\n")c, p = stats.pearsonr(df1['GOOG'].dropna()['close'], SPY.dropna()['close'])print(f"GOOG vs SPY Pearson Correlation: {c}\n")c, p = stats.pearsonr(df1['TSLA'].dropna()['close'], SPY.dropna()['close'])print(f"TSLA vs SPY Pearson Correlation: {c}")FB vs SPY Pearson Correlation: 0.7325442525842248AMZN vs SPY Pearson Correlation: 0.910899729798812AAPL vs SPY Pearson Correlation: 0.9176098570966427GOOG vs SPY Pearson Correlation: 0.9485878709468345TSLA vs SPY Pearson Correlation: -0.26968006350226387 As of 11/22/2019, Google (GOOG) has the highest Pearson Correlation Coefficient out of all of these options. Also, Tesla (TSLA) has negative correlation to the S&P 500. Many of these you could find by looking in the charts above and comparing the charts with the S&P 500 chart; but now you have a quantitative approach for correlation! Now, to explore the API a bit more, let’s see how the social sentiment feature looks. We’ll take a look at yesterday (11/22/2019), for Tesla. from iexfinance.altdata import get_social_sentiment, get_ceo_compensationperiod='minute'specDay="20191122"TSLA_Sent = get_social_sentiment("TSLA", period, specDay, output_format='pandas')print(TSLA_Sent.head())minute negative positive sentiment totalScores0 0000 0.12 0.88 0.084958 261 0001 0.12 0.88 0.160624 172 0002 0.11 0.89 0.061056 183 0003 0.29 0.71 -0.180071 174 0004 0.07 0.93 0.066293 15 For yesterday, what was the highest score for the most positive, and most negative, social sentiment of Tesla? TSLA_Sent_Pos = TSLA_Sent['sentiment'].max()TSLA_Sent_Neg = TSLA_Sent['sentiment'].min()print("Highest Social Sentiment on 11/22/2019:", TSLA_Sent_Pos)print("Lowest Social Sentiment on 11/22/2019:", TSLA_Sent_Neg)Highest Social Sentiment on 11/22/2019: 0.9785Lowest Social Sentiment on 11/22/2019: -0.9487 This API also has CEO information! Let’s take a look at CEO information for the FAANG and TSLA stocks we researched earlier. We’ll use df1 which was created and used to simplify when performing the correlation tests. import pprintfor n, q in df1: pprint.pprint(get_ceo_compensation(n)){'bonus': 0, 'companyName': 'Facebook Inc. Class A', 'location': 'Menlo Park, CA', 'name': 'Mark Zuckerberg', 'nonEquityIncentives': 0, 'optionAwards': 0, 'otherComp': 22554542, 'pensionAndDeferred': 0, 'salary': 1, 'stockAwards': 0, 'symbol': 'FB', 'total': 22554543, 'year': '2018'}{'bonus': 0, 'companyName': 'Amazon.com Inc.', 'location': 'Seattle, WA', 'name': 'Jeffrey Bezos', 'nonEquityIncentives': 0, 'optionAwards': 0, 'otherComp': 1600000, 'pensionAndDeferred': 0, 'salary': 81840, 'stockAwards': 0, 'symbol': 'AMZN', 'total': 1681840, 'year': '2018'}{'bonus': 0, 'companyName': 'Apple Inc.', 'location': 'Cupertino, CA', 'name': 'Timothy Cook', 'nonEquityIncentives': 12000000, 'optionAwards': 0, 'otherComp': 682219, 'pensionAndDeferred': 0, 'salary': 3000000, 'stockAwards': 0, 'symbol': 'AAPL', 'total': 15682219, 'year': '2018'}{'bonus': 0, 'companyName': 'Netflix Inc.', 'location': 'Los Gatos, CA', 'name': 'Reed Hastings', 'nonEquityIncentives': 0, 'optionAwards': 35380417, 'otherComp': 0, 'pensionAndDeferred': 0, 'salary': 700000, 'stockAwards': 0, 'symbol': 'NFLX', 'total': 36080417, 'year': '2018'}{'bonus': 0, 'companyName': 'Alphabet Inc. Class A', 'location': 'Mountain View, CA', 'name': 'Larry Page', 'nonEquityIncentives': 0, 'optionAwards': 0, 'otherComp': 0, 'pensionAndDeferred': 0, 'salary': 1, 'stockAwards': 0, 'symbol': 'GOOG', 'total': 1, 'year': '2018'}{'bonus': 0, 'companyName': 'Tesla Inc', 'location': 'Palo Alto, CA', 'name': 'Elon Musk', 'nonEquityIncentives': 0, 'optionAwards': 2283988504, 'otherComp': 0, 'pensionAndDeferred': 0, 'salary': 56380, 'stockAwards': 0, 'symbol': 'TSLA', 'total': 2284044884, 'year': '2018'} There’s a lot more to explore and analyze. In the next article, I plan to explore some “real-time” data of IEX Cloud, such the books. Also, I may continue on with time-series analysis and move on to some basic forecasting. I hope you found this exploration useful! Kenton, W. (2019, November 18). What Are FAANG Stocks? Retrieved November 28, 2019, from https://www.investopedia.com/terms/f/faang-stocks.asp. Lynch, A. (2019, October 24). addisonlynch/iexfinance. Retrieved November 28, 2019, from https://github.com/addisonlynch/iexfinance. Cheong, J. H. (2019, May 13). Four ways to quantify synchrony between time series data. Retrieved November 28, 2019, from https://towardsdatascience.com/four-ways-to-quantify-synchrony-between-time-series-data-b99136c4a9c9.
[ { "code": null, "e": 516, "s": 172, "text": "I’ve recently created an account with IEX Cloud, a financial data service. As I’ve been learning the features of this new data source (new to me) and experimenting within my Jupyter Notebook, I thought the below may be helpful for others as well. Therefore, I’m creating my first Medium article and will focus it on financial time series data." }, { "code": null, "e": 916, "s": 516, "text": "There are quite a few articles and sources on defining correlation, and the differences between correlation and causation; so what you will find below will primarily show some ways to test correlation and what the results mean. You may find this article beneficial if you’re looking to use IEX Cloud, if you’re looking to do Correlation tests in Python, and if you’re interested in Time-Series data!" }, { "code": null, "e": 1181, "s": 916, "text": "If you’re following this and coding it yourself, go to https://iexcloud.io/ and get yourself an API key! You’ll need it next! Also, don’t forgot to install an IEX Python library: https://addisonlynch.github.io/iexfinance/ (Lynch, 2019). Install this library using:" }, { "code": null, "e": 1207, "s": 1181, "text": "$ pip3 install iexfinance" }, { "code": null, "e": 1391, "s": 1207, "text": "import configimport os#os.environ['IEX_API_VERSION'] = \"iexcloud-sandbox\"os.environ['IEX_TOKEN'] = config.iex_api_key # Replace \"config.iex_api_key\" with your API Key from IEX Cloud!" }, { "code": null, "e": 1517, "s": 1391, "text": "We’ll load up some of the libraries we’ll need next. Also, we’ll be using data between January 1, 2017 and November 22, 2019." }, { "code": null, "e": 1701, "s": 1517, "text": "from datetime import datetimefrom iexfinance.stocks import get_historical_dataimport matplotlib.pyplot as plt%matplotlib inlinestart = datetime(2017, 1, 1)end = datetime(2019, 11, 22)" }, { "code": null, "e": 1873, "s": 1701, "text": "We’ll arbitrarily choose ‘close’ for the sake of simplicity. From this API data response, you could also choose Open, High, Low, and Volume. We’ll experiment with ‘close.’" }, { "code": null, "e": 2044, "s": 1873, "text": "Now, let’s make an API call and download more data, ‘SPDR S&P 500 Trust ETF,’ which tracks the S&P 500 (ticker: SPY). We’ll be using this later in some correlation tests." }, { "code": null, "e": 2217, "s": 2044, "text": "SPY = get_historical_data(\"SPY\", start, end, output_format='pandas')plt.figure(figsize=(10, 4))plt.plot(SPY.index, SPY['close'])plt.title('Daily Times Series for the SPY');" }, { "code": null, "e": 2583, "s": 2217, "text": "Now, let’s continue to explore the API by downloading data for the FAANG stocks (Facebook, Amazon, Apple, Netflix, and Google) (Kenton, 2019), as well as add an interest of mine, Tesla. Also, chart these up. Pay careful attention to the charts and do a comparison of those with the SPY chart above. Some of these will look very similar to the SPY chart, some won’t." }, { "code": null, "e": 5047, "s": 2583, "text": "FAANGT = get_historical_data([\"FB\",\"AMZN\",\"AAPL\",\"NFLX\",\"GOOG\",\"TSLA\"], start, end, output_format='pandas')print(FAANGT.head())FB AMZN \\ open high low close volume open high low date 2017-01-03 116.03 117.84 115.51 116.86 20663912 757.92 758.76 747.70 2017-01-04 117.55 119.66 117.29 118.69 19630932 758.39 759.68 754.20 2017-01-05 118.86 120.95 118.32 120.67 19492150 761.55 782.40 760.26 2017-01-06 120.98 123.88 120.03 123.41 28545263 782.36 799.44 778.48 2017-01-09 123.55 125.43 123.04 124.90 22880360 798.00 801.77 791.77 ... GOOG \\ close volume ... open high low close volume date ... 2017-01-03 753.67 3521066 ... 778.81 789.63 775.80 786.14 1657268 2017-01-04 757.18 2510526 ... 788.36 791.34 783.16 786.90 1072958 2017-01-05 780.45 5830068 ... 786.08 794.48 785.02 794.02 1335167 2017-01-06 795.99 5986234 ... 795.26 807.90 792.20 806.15 1640170 2017-01-09 796.92 3446109 ... 806.40 809.97 802.83 806.65 1274645 TSLA open high low close volume date 2017-01-03 214.86 220.33 210.96 216.99 5923254 2017-01-04 214.75 228.00 214.31 226.99 11213471 2017-01-05 226.42 227.48 221.95 226.75 5911695 2017-01-06 226.93 230.31 225.45 229.01 5527893 2017-01-09 228.97 231.92 228.00 231.28 3979484 [5 rows x 30 columns]plt.figure(figsize=(15, 4))#FBplt.subplot(1, 2, 1)plt.plot(FAANGT.index, FAANGT['FB']['close'])plt.title('Daily Times Series for the FB')#AMZNplt.subplot(1, 2, 2)plt.plot(FAANGT.index, FAANGT['AMZN']['close'])plt.title('Daily Times Series for the AMZN');plt.figure(figsize=(15, 4))#AAPLplt.subplot(1, 2, 1)plt.plot(FAANGT.index, FAANGT['AAPL']['close'])plt.title('Daily Times Series for the AAPL');#GOOGplt.subplot(1, 2, 2)plt.plot(FAANGT.index, FAANGT['GOOG']['close'])plt.title('Daily Times Series for the GOOG');plt.figure(figsize=(15, 4))#TSLAplt.subplot(1, 2, 1)plt.plot(FAANGT.index, FAANGT['TSLA']['close'])plt.title('Daily Times Series for the TSLA');" }, { "code": null, "e": 5410, "s": 5047, "text": "Now that we have data for both the FAANG stocks (and TSLA) and the S&P 500, and we’ve plotted these so that we know what they look like; let’s try an experiment! We’re going to try a Pearson Correlation test, to test correlation on all of these equities and the S&P 500. What do you think? Based-on viewing the charts and going by intuition, will they correlate?" }, { "code": null, "e": 5630, "s": 5410, "text": "Correlation will show when the Pearson Correlation Coefficient is between -1 and +1. If closer to +1, we’re seeing a positive correlation. If Pearson’s correlation is closer to -1, a negative correlation (Cheong, 2019)." }, { "code": null, "e": 6645, "s": 5630, "text": "import pandas as pdimport scipy.stats as stats# Slice this up to make it easier to work with.indx = pd.IndexSlicedf1 = FAANGT.loc[:, (indx[:],'close')]c, p = stats.pearsonr(df1['FB'].dropna()['close'], SPY.dropna()['close'])print(f\"FB vs SPY Pearson Correlation: {c}\\n\")c, p = stats.pearsonr(df1['AMZN'].dropna()['close'], SPY.dropna()['close'])print(f\"AMZN vs SPY Pearson Correlation: {c}\\n\")c, p = stats.pearsonr(df1['AAPL'].dropna()['close'], SPY.dropna()['close'])print(f\"AAPL vs SPY Pearson Correlation: {c}\\n\")c, p = stats.pearsonr(df1['GOOG'].dropna()['close'], SPY.dropna()['close'])print(f\"GOOG vs SPY Pearson Correlation: {c}\\n\")c, p = stats.pearsonr(df1['TSLA'].dropna()['close'], SPY.dropna()['close'])print(f\"TSLA vs SPY Pearson Correlation: {c}\")FB vs SPY Pearson Correlation: 0.7325442525842248AMZN vs SPY Pearson Correlation: 0.910899729798812AAPL vs SPY Pearson Correlation: 0.9176098570966427GOOG vs SPY Pearson Correlation: 0.9485878709468345TSLA vs SPY Pearson Correlation: -0.26968006350226387" }, { "code": null, "e": 6981, "s": 6645, "text": "As of 11/22/2019, Google (GOOG) has the highest Pearson Correlation Coefficient out of all of these options. Also, Tesla (TSLA) has negative correlation to the S&P 500. Many of these you could find by looking in the charts above and comparing the charts with the S&P 500 chart; but now you have a quantitative approach for correlation!" }, { "code": null, "e": 7123, "s": 6981, "text": "Now, to explore the API a bit more, let’s see how the social sentiment feature looks. We’ll take a look at yesterday (11/22/2019), for Tesla." }, { "code": null, "e": 7645, "s": 7123, "text": "from iexfinance.altdata import get_social_sentiment, get_ceo_compensationperiod='minute'specDay=\"20191122\"TSLA_Sent = get_social_sentiment(\"TSLA\", period, specDay, output_format='pandas')print(TSLA_Sent.head())minute negative positive sentiment totalScores0 0000 0.12 0.88 0.084958 261 0001 0.12 0.88 0.160624 172 0002 0.11 0.89 0.061056 183 0003 0.29 0.71 -0.180071 174 0004 0.07 0.93 0.066293 15" }, { "code": null, "e": 7756, "s": 7645, "text": "For yesterday, what was the highest score for the most positive, and most negative, social sentiment of Tesla?" }, { "code": null, "e": 8062, "s": 7756, "text": "TSLA_Sent_Pos = TSLA_Sent['sentiment'].max()TSLA_Sent_Neg = TSLA_Sent['sentiment'].min()print(\"Highest Social Sentiment on 11/22/2019:\", TSLA_Sent_Pos)print(\"Lowest Social Sentiment on 11/22/2019:\", TSLA_Sent_Neg)Highest Social Sentiment on 11/22/2019: 0.9785Lowest Social Sentiment on 11/22/2019: -0.9487" }, { "code": null, "e": 8279, "s": 8062, "text": "This API also has CEO information! Let’s take a look at CEO information for the FAANG and TSLA stocks we researched earlier. We’ll use df1 which was created and used to simplify when performing the correlation tests." }, { "code": null, "e": 10018, "s": 8279, "text": "import pprintfor n, q in df1: pprint.pprint(get_ceo_compensation(n)){'bonus': 0, 'companyName': 'Facebook Inc. Class A', 'location': 'Menlo Park, CA', 'name': 'Mark Zuckerberg', 'nonEquityIncentives': 0, 'optionAwards': 0, 'otherComp': 22554542, 'pensionAndDeferred': 0, 'salary': 1, 'stockAwards': 0, 'symbol': 'FB', 'total': 22554543, 'year': '2018'}{'bonus': 0, 'companyName': 'Amazon.com Inc.', 'location': 'Seattle, WA', 'name': 'Jeffrey Bezos', 'nonEquityIncentives': 0, 'optionAwards': 0, 'otherComp': 1600000, 'pensionAndDeferred': 0, 'salary': 81840, 'stockAwards': 0, 'symbol': 'AMZN', 'total': 1681840, 'year': '2018'}{'bonus': 0, 'companyName': 'Apple Inc.', 'location': 'Cupertino, CA', 'name': 'Timothy Cook', 'nonEquityIncentives': 12000000, 'optionAwards': 0, 'otherComp': 682219, 'pensionAndDeferred': 0, 'salary': 3000000, 'stockAwards': 0, 'symbol': 'AAPL', 'total': 15682219, 'year': '2018'}{'bonus': 0, 'companyName': 'Netflix Inc.', 'location': 'Los Gatos, CA', 'name': 'Reed Hastings', 'nonEquityIncentives': 0, 'optionAwards': 35380417, 'otherComp': 0, 'pensionAndDeferred': 0, 'salary': 700000, 'stockAwards': 0, 'symbol': 'NFLX', 'total': 36080417, 'year': '2018'}{'bonus': 0, 'companyName': 'Alphabet Inc. Class A', 'location': 'Mountain View, CA', 'name': 'Larry Page', 'nonEquityIncentives': 0, 'optionAwards': 0, 'otherComp': 0, 'pensionAndDeferred': 0, 'salary': 1, 'stockAwards': 0, 'symbol': 'GOOG', 'total': 1, 'year': '2018'}{'bonus': 0, 'companyName': 'Tesla Inc', 'location': 'Palo Alto, CA', 'name': 'Elon Musk', 'nonEquityIncentives': 0, 'optionAwards': 2283988504, 'otherComp': 0, 'pensionAndDeferred': 0, 'salary': 56380, 'stockAwards': 0, 'symbol': 'TSLA', 'total': 2284044884, 'year': '2018'}" }, { "code": null, "e": 10283, "s": 10018, "text": "There’s a lot more to explore and analyze. In the next article, I plan to explore some “real-time” data of IEX Cloud, such the books. Also, I may continue on with time-series analysis and move on to some basic forecasting. I hope you found this exploration useful!" }, { "code": null, "e": 10427, "s": 10283, "text": "Kenton, W. (2019, November 18). What Are FAANG Stocks? Retrieved November 28, 2019, from https://www.investopedia.com/terms/f/faang-stocks.asp." }, { "code": null, "e": 10560, "s": 10427, "text": "Lynch, A. (2019, October 24). addisonlynch/iexfinance. Retrieved November 28, 2019, from https://github.com/addisonlynch/iexfinance." } ]
DataTables scrollX Option - GeeksforGeeks
31 May, 2021 DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed. The scrollX option is used to specify whether horizontal scrolling should be enabled in a DataTable. This option will enable the user to horizontally scroll any overflowing content in the table itself. This can be used when there are a lot of columns or the columns do not fit in the layout. A true value enables this scrolling and a false value disables it. Syntax: { scrollX: value } Option Value: This option has a single value as mentioned above and described below: value: This is a boolean value that enables or disables the horizontal scrolling of the DataTable. The default value is false. The below example illustrates the use of this option. Example 1: This example enables the horizontal scrolling of the DataTable. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head><body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables scrollX Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap" style="width: 100%"> <thead> <tr> <th>Registration ID</th> <th>Full Name</th> <th>Age at Registration</th> <th>Full Address</th> <th>Phone Number</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam Fisher</td> <td>35</td> <td>Earth, Galaxy</td> <td>01234344043</td> </tr> <tr> <td>2</td> <td>Jack the Ripper</td> <td>30</td> <td>Earth, Galaxy</td> <td>0124334043</td> </tr> <tr> <td>3</td> <td>Reaper the Leviathan</td> <td>45</td> <td>4546B</td> <td>0189994043</td> </tr> <tr> <td>4</td> <td>Ghost the Leviathan</td> <td>105</td> <td>4546B</td> <td>0123489043</td> </tr> <tr> <td>5</td> <td>Robby the Robber</td> <td>19</td> <td>Mars</td> <td>68898988</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Enable the horizontal scrolling // of data in DataTable scrollX: true }); }); </script></body></html> Output: Example 2: This example disables the horizontal scrolling of the DataTable. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head><body> <h1 style="color: green;"> GeeksForGeek s</h1> <h3>DataTables scrollX Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap" style="width: 100%"> <thead> <tr> <th>Registration ID</th> <th>Full Name</th> <th>Age at Registration</th> <th>Full Address</th> <th>Phone Number</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam Fisher</td> <td>35</td> <td>Earth, Galaxy</td> <td>01234344043</td> </tr> <tr> <td>2</td> <td>Jack the Ripper</td> <td>30</td> <td>Earth, Galaxy</td> <td>0124334043</td> </tr> <tr> <td>3</td> <td>Reaper the Leviathan</td> <td>45</td> <td>4546B</td> <td>0189994043</td> </tr> <tr> <td>4</td> <td>Ghost the Leviathan</td> <td>105</td> <td>4546B</td> <td>0123489043</td> </tr> <tr> <td>5</td> <td>Robby the Robber</td> <td>19</td> <td>Mars</td> <td>68898988</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Disable the horizontal scrolling // of data in DataTable scrollX: false }); }); </script></body></html> Output: jQuery-DataTables JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments jQuery | ajax() Method How to prevent Body from scrolling when a modal is opened using jQuery ? How to get the value in an input text box using jQuery ? QR Code Generator using HTML, CSS and jQuery jQuery UI | Date Picker Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25675, "s": 25647, "text": "\n31 May, 2021" }, { "code": null, "e": 26013, "s": 25675, "text": "DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed." }, { "code": null, "e": 26372, "s": 26013, "text": "The scrollX option is used to specify whether horizontal scrolling should be enabled in a DataTable. This option will enable the user to horizontally scroll any overflowing content in the table itself. This can be used when there are a lot of columns or the columns do not fit in the layout. A true value enables this scrolling and a false value disables it." }, { "code": null, "e": 26380, "s": 26372, "text": "Syntax:" }, { "code": null, "e": 26399, "s": 26380, "text": "{ scrollX: value }" }, { "code": null, "e": 26484, "s": 26399, "text": "Option Value: This option has a single value as mentioned above and described below:" }, { "code": null, "e": 26611, "s": 26484, "text": "value: This is a boolean value that enables or disables the horizontal scrolling of the DataTable. The default value is false." }, { "code": null, "e": 26665, "s": 26611, "text": "The below example illustrates the use of this option." }, { "code": null, "e": 26740, "s": 26665, "text": "Example 1: This example enables the horizontal scrolling of the DataTable." }, { "code": null, "e": 26745, "s": 26740, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head><body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables scrollX Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\" style=\"width: 100%\"> <thead> <tr> <th>Registration ID</th> <th>Full Name</th> <th>Age at Registration</th> <th>Full Address</th> <th>Phone Number</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam Fisher</td> <td>35</td> <td>Earth, Galaxy</td> <td>01234344043</td> </tr> <tr> <td>2</td> <td>Jack the Ripper</td> <td>30</td> <td>Earth, Galaxy</td> <td>0124334043</td> </tr> <tr> <td>3</td> <td>Reaper the Leviathan</td> <td>45</td> <td>4546B</td> <td>0189994043</td> </tr> <tr> <td>4</td> <td>Ghost the Leviathan</td> <td>105</td> <td>4546B</td> <td>0123489043</td> </tr> <tr> <td>5</td> <td>Robby the Robber</td> <td>19</td> <td>Mars</td> <td>68898988</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Enable the horizontal scrolling // of data in DataTable scrollX: true }); }); </script></body></html>", "e": 28527, "s": 26745, "text": null }, { "code": null, "e": 28535, "s": 28527, "text": "Output:" }, { "code": null, "e": 28611, "s": 28535, "text": "Example 2: This example disables the horizontal scrolling of the DataTable." }, { "code": null, "e": 28616, "s": 28611, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head><body> <h1 style=\"color: green;\"> GeeksForGeek s</h1> <h3>DataTables scrollX Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\" style=\"width: 100%\"> <thead> <tr> <th>Registration ID</th> <th>Full Name</th> <th>Age at Registration</th> <th>Full Address</th> <th>Phone Number</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam Fisher</td> <td>35</td> <td>Earth, Galaxy</td> <td>01234344043</td> </tr> <tr> <td>2</td> <td>Jack the Ripper</td> <td>30</td> <td>Earth, Galaxy</td> <td>0124334043</td> </tr> <tr> <td>3</td> <td>Reaper the Leviathan</td> <td>45</td> <td>4546B</td> <td>0189994043</td> </tr> <tr> <td>4</td> <td>Ghost the Leviathan</td> <td>105</td> <td>4546B</td> <td>0123489043</td> </tr> <tr> <td>5</td> <td>Robby the Robber</td> <td>19</td> <td>Mars</td> <td>68898988</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Disable the horizontal scrolling // of data in DataTable scrollX: false }); }); </script></body></html>", "e": 30402, "s": 28616, "text": null }, { "code": null, "e": 30410, "s": 30402, "text": "Output:" }, { "code": null, "e": 30428, "s": 30410, "text": "jQuery-DataTables" }, { "code": null, "e": 30435, "s": 30428, "text": "JQuery" }, { "code": null, "e": 30452, "s": 30435, "text": "Web Technologies" }, { "code": null, "e": 30550, "s": 30452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30559, "s": 30550, "text": "Comments" }, { "code": null, "e": 30572, "s": 30559, "text": "Old Comments" }, { "code": null, "e": 30595, "s": 30572, "text": "jQuery | ajax() Method" }, { "code": null, "e": 30668, "s": 30595, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30725, "s": 30668, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 30770, "s": 30725, "text": "QR Code Generator using HTML, CSS and jQuery" }, { "code": null, "e": 30794, "s": 30770, "text": "jQuery UI | Date Picker" }, { "code": null, "e": 30827, "s": 30794, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30869, "s": 30827, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30912, "s": 30869, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30974, "s": 30912, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
\texttt - Tex Command
\texttt - Used to produce text-mode material in typewriter font within a mathematical expression. { \texttt #1} \texttt command is used to produce text-mode material in typewriter font within a mathematical expression. \texttt{\alpha in texttt mode }\alpha \alpha in texttt mode α \texttt{\alpha in texttt mode }\alpha \alpha in texttt mode α \texttt{\alpha in texttt mode }\alpha 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8085, "s": 7986, "text": "\\texttt - Used to produce text-mode material in typewriter font within a mathematical expression." }, { "code": null, "e": 8099, "s": 8085, "text": "{ \\texttt #1}" }, { "code": null, "e": 8206, "s": 8099, "text": "\\texttt command is used to produce text-mode material in typewriter font within a mathematical expression." }, { "code": null, "e": 8273, "s": 8206, "text": "\n\\texttt{\\alpha in texttt mode }\\alpha\n\n\\alpha in texttt mode α\n\n\n" }, { "code": null, "e": 8338, "s": 8273, "text": "\\texttt{\\alpha in texttt mode }\\alpha\n\n\\alpha in texttt mode α\n\n" }, { "code": null, "e": 8376, "s": 8338, "text": "\\texttt{\\alpha in texttt mode }\\alpha" }, { "code": null, "e": 8408, "s": 8376, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8421, "s": 8408, "text": " Ashraf Said" }, { "code": null, "e": 8454, "s": 8421, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8467, "s": 8454, "text": " Ashraf Said" }, { "code": null, "e": 8499, "s": 8467, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8535, "s": 8499, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8570, "s": 8535, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8587, "s": 8570, "text": " Mohammad Nauman" }, { "code": null, "e": 8620, "s": 8587, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8634, "s": 8620, "text": " Daniel Stern" }, { "code": null, "e": 8666, "s": 8634, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8681, "s": 8666, "text": " Nishant Kumar" }, { "code": null, "e": 8688, "s": 8681, "text": " Print" }, { "code": null, "e": 8699, "s": 8688, "text": " Add Notes" } ]
Android - list Fragment
Static library support version of the framework's ListFragment. Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used. The basic implementation of list fragment is for creating list of items in fragments This example will explain you how to create your own list fragment based on arrayAdapter. So let's follow the following steps to similar to what we followed while creating Hello World Example − Before start coding i will initialize of the string constants inside string.xml file under res/values directory <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ListFragmentDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="imgdesc">imgdesc</string> <string-array name="Planets"> <item>Sun</item> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> <item>Jupiter</item> <item>Saturn</item> <item>Uranus</item> <item>Neptune</item> </string-array> </resources> Following will be the content of res/layout/activity_main.xml file. it contained linear layout and fragment tag. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <fragment android:id="@+id/fragment1" android:name="com.example.tutorialspoint7.myapplication.MyListFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Following will be the content of res/layout/list_fragment.xml file. it contained linear layout,list view and text view <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> <TextView android:id="@android:id/empty" android:layout_width="match_parent" android:layout_height="wrap_content" > </TextView> </LinearLayout> following will be the content of src/main/java/myListFragment.java file.before writing to code, need to follow few steps as shown below Create a class MyListFragment and extend it to ListFragment. Create a class MyListFragment and extend it to ListFragment. Inside the onCreateView() method , inflate the view with above defined list_fragment xml layout. Inside the onCreateView() method , inflate the view with above defined list_fragment xml layout. Inside the onActivityCreated() method , create a arrayadapter from resource ie using String array R.array.planet which you can find inside the string.xml and set this adapter to listview and also set the onItem click Listener. Inside the onActivityCreated() method , create a arrayadapter from resource ie using String array R.array.planet which you can find inside the string.xml and set this adapter to listview and also set the onItem click Listener. Inside the OnItemClickListener() method , display a toast message with Item name which is being clicked. Inside the OnItemClickListener() method , display a toast message with Item name which is being clicked. package com.example.tutorialspoint7.myapplication; import android.annotation.SuppressLint; import android.app.ListFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Toast; public class MyListFragment extends ListFragment implements OnItemClickListener { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.list_fragment, container, false); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1); setListAdapter(adapter); getListView().setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position,long id) { Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show(); } } Following code will be the content of MainActivity.java package com.example.tutorialspoint7.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } following code will be the content of manifest.xml, which has placed at res/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.tutorialspoint7.myapplication"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run our SimpleListFragment application we just created. I assume you had created your AVD while doing environment set-up. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3807, "s": 3607, "text": "Static library support version of the framework's ListFragment. Used to write apps that run on platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still used." }, { "code": null, "e": 3892, "s": 3807, "text": "The basic implementation of list fragment is for creating list of items in fragments" }, { "code": null, "e": 4086, "s": 3892, "text": "This example will explain you how to create your own list fragment based on arrayAdapter. So let's follow the following steps to similar to what we followed while creating Hello World Example −" }, { "code": null, "e": 4198, "s": 4086, "text": "Before start coding i will initialize of the string constants inside string.xml file under res/values directory" }, { "code": null, "e": 4749, "s": 4198, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">ListFragmentDemo</string>\n <string name=\"action_settings\">Settings</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"imgdesc\">imgdesc</string>\n \n <string-array name=\"Planets\">\n <item>Sun</item>\n <item>Mercury</item>\n <item>Venus</item>\n <item>Earth</item>\n <item>Mars</item>\n <item>Jupiter</item>\n <item>Saturn</item>\n <item>Uranus</item>\n <item>Neptune</item>\n </string-array>\n\n</resources>" }, { "code": null, "e": 4862, "s": 4749, "text": "Following will be the content of res/layout/activity_main.xml file. it contained linear layout and fragment tag." }, { "code": null, "e": 5326, "s": 4862, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\" >\n \n <fragment\n android:id=\"@+id/fragment1\"\n android:name=\"com.example.tutorialspoint7.myapplication.MyListFragment\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n\n</LinearLayout>" }, { "code": null, "e": 5445, "s": 5326, "text": "Following will be the content of res/layout/list_fragment.xml file. it contained linear layout,list view and text view" }, { "code": null, "e": 5997, "s": 5445, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\" >\n\n <ListView\n android:id=\"@android:id/list\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" >\n </ListView>\n\n <TextView\n android:id=\"@android:id/empty\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" >\n </TextView>\n</LinearLayout>" }, { "code": null, "e": 6133, "s": 5997, "text": "following will be the content of src/main/java/myListFragment.java file.before writing to code, need to follow few steps as shown below" }, { "code": null, "e": 6194, "s": 6133, "text": "Create a class MyListFragment and extend it to ListFragment." }, { "code": null, "e": 6255, "s": 6194, "text": "Create a class MyListFragment and extend it to ListFragment." }, { "code": null, "e": 6352, "s": 6255, "text": "Inside the onCreateView() method , inflate the view with above defined list_fragment xml layout." }, { "code": null, "e": 6449, "s": 6352, "text": "Inside the onCreateView() method , inflate the view with above defined list_fragment xml layout." }, { "code": null, "e": 6677, "s": 6449, "text": "Inside the onActivityCreated() method , create a arrayadapter from resource ie using String array R.array.planet which you can find inside the string.xml and set this adapter to listview and also set the onItem click Listener." }, { "code": null, "e": 6905, "s": 6677, "text": "Inside the onActivityCreated() method , create a arrayadapter from resource ie using String array R.array.planet which you can find inside the string.xml and set this adapter to listview and also set the onItem click Listener." }, { "code": null, "e": 7010, "s": 6905, "text": "Inside the OnItemClickListener() method , display a toast message with Item name which is being clicked." }, { "code": null, "e": 7115, "s": 7010, "text": "Inside the OnItemClickListener() method , display a toast message with Item name which is being clicked." }, { "code": null, "e": 8369, "s": 7115, "text": "package com.example.tutorialspoint7.myapplication;\n\nimport android.annotation.SuppressLint;\nimport android.app.ListFragment;\nimport android.os.Bundle;\n\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\n\nimport android.widget.AdapterView;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.ArrayAdapter;\nimport android.widget.Toast;\n\npublic class MyListFragment extends ListFragment implements OnItemClickListener {\n @Override\n public View onCreateView(LayoutInflater inflater, \n ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.list_fragment, container, false);\n return view;\n }\n\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), \n R.array.Planets, android.R.layout.simple_list_item_1);\n setListAdapter(adapter);\n getListView().setOnItemClickListener(this);\n }\n\n @Override\n public void onItemClick(AdapterView<?> parent, View view, int position,long id) {\n Toast.makeText(getActivity(), \"Item: \" + position, Toast.LENGTH_SHORT).show();\n }\n}" }, { "code": null, "e": 8426, "s": 8369, "text": " Following code will be the content of MainActivity.java" }, { "code": null, "e": 8773, "s": 8426, "text": "package com.example.tutorialspoint7.myapplication;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 8869, "s": 8773, "text": "following code will be the content of manifest.xml, which has placed at res/AndroidManifest.xml" }, { "code": null, "e": 9519, "s": 8869, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.tutorialspoint7.myapplication\">\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 9924, "s": 9519, "text": "Let's try to run our SimpleListFragment application we just created. I assume you had created your AVD while doing environment set-up. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −" }, { "code": null, "e": 9959, "s": 9924, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9971, "s": 9959, "text": " Aditya Dua" }, { "code": null, "e": 10006, "s": 9971, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10020, "s": 10006, "text": " Sharad Kumar" }, { "code": null, "e": 10052, "s": 10020, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 10069, "s": 10052, "text": " Abhilash Nelson" }, { "code": null, "e": 10104, "s": 10069, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10121, "s": 10104, "text": " Abhilash Nelson" }, { "code": null, "e": 10156, "s": 10121, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10173, "s": 10156, "text": " Abhilash Nelson" }, { "code": null, "e": 10206, "s": 10173, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 10223, "s": 10206, "text": " Abhilash Nelson" }, { "code": null, "e": 10230, "s": 10223, "text": " Print" }, { "code": null, "e": 10241, "s": 10230, "text": " Add Notes" } ]